astTools.py 文件源码

python
阅读 28 收藏 0 点赞 0 评论 0

项目:ITAP-django 作者: krivers 项目源码 文件源码
def negate(op):
    """Return the negation of the provided operator"""
    if op == None:
        return None
    top = type(op)
    neg = not op.negated if hasattr(op, "negated") else True
    if top == ast.And:
        newOp = ast.Or()
    elif top == ast.Or:
        newOp = ast.And()
    elif top == ast.Eq:
        newOp = ast.NotEq()
    elif top == ast.NotEq:
        newOp = ast.Eq()
    elif top == ast.Lt:
        newOp = ast.GtE()
    elif top == ast.GtE:
        newOp = ast.Lt()
    elif top == ast.Gt:
        newOp = ast.LtE()
    elif top == ast.LtE:
        newOp = ast.Gt()
    elif top == ast.Is:
        newOp = ast.IsNot()
    elif top == ast.IsNot:
        newOp = ast.Is()
    elif top == ast.In:
        newOp = ast.NotIn()
    elif top == ast.NotIn:
        newOp = ast.In()
    elif top == ast.NameConstant and op.value in [True, False]:
        op.value = not op.value
        op.negated = neg
        return op
    elif top == ast.Compare:
        if len(op.ops) == 1:
            op.ops[0] = negate(op.ops[0])
            op.negated = neg
            return op
        else:
            values = []
            allOperands = [op.left] + op.comparators
            for i in range(len(op.ops)):
                values.append(ast.Compare(allOperands[i], [negate(op.ops[i])],
                                          [allOperands[i+1]], multiCompPart=True))
            newOp = ast.BoolOp(ast.Or(multiCompOp=True), values, multiComp=True)
    elif top == ast.UnaryOp and type(op.op) == ast.Not and \
            eventualType(op.operand) == bool: # this can mess things up type-wise
        return op.operand
    else:
        # this is a normal value, so put a not around it
        newOp = ast.UnaryOp(ast.Not(addedNot=True), op)
    transferMetaData(op, newOp)
    newOp.negated = neg
    return newOp
评论列表
文章目录


问题


面经


文章

微信
公众号

扫码关注公众号