当前位置: 首页>>代码示例>>Python>>正文


Python ast.Not方法代码示例

本文整理汇总了Python中ast.Not方法的典型用法代码示例。如果您正苦于以下问题:Python ast.Not方法的具体用法?Python ast.Not怎么用?Python ast.Not使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在ast的用法示例。


在下文中一共展示了ast.Not方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: visit_UnaryOp

# 需要导入模块: import ast [as 别名]
# 或者: from ast import Not [as 别名]
def visit_UnaryOp(self, node):
        self.visit(node.operand)
        node.vhd = copy(node.operand.vhd)
        if isinstance(node.op, ast.Not):
            # postpone this optimization until initial values are written
            #            if isinstance(node.operand.vhd, vhd_std_logic):
            #                node.vhd = vhd_std_logic()
            #            else:
            #                node.vhd = node.operand.vhd = vhd_boolean()
            node.vhd = node.operand.vhd = vhd_boolean()
        elif isinstance(node.op, ast.USub):
            if isinstance(node.vhd, vhd_unsigned):
                node.vhd = vhd_signed(node.vhd.size + 1)
            elif isinstance(node.vhd, vhd_nat):
                node.vhd = vhd_int()
        node.vhdOri = copy(node.vhd) 
开发者ID:myhdl,项目名称:myhdl,代码行数:18,代码来源:_toVHDL.py

示例2: not_expression_ast_to_ir2

# 需要导入模块: import ast [as 别名]
# 或者: from ast import Not [as 别名]
def not_expression_ast_to_ir2(ast_node: ast.UnaryOp,
                              compilation_context: CompilationContext,
                              in_match_pattern: bool,
                              check_var_reference: Callable[[ast.Name], None],
                              match_lambda_argument_names: Set[str],
                              current_stmt_line: int):
    assert isinstance(ast_node.op, ast.Not)

    if in_match_pattern:
        raise CompilationError(compilation_context, ast_node,
                               'The "not" operator is not allowed in match patterns')

    expr = expression_ast_to_ir2(ast_node.operand,
                                 compilation_context,
                                 in_match_pattern,
                                 check_var_reference,
                                 match_lambda_argument_names,
                                 current_stmt_line)

    if expr.expr_type != ir2.BoolType():
        raise CompilationError(compilation_context, ast_node.operand,
                               'The "not" operator is only supported for booleans, but this value has type %s.' % str(expr.expr_type))

    return ir2.NotExpr(expr=expr) 
开发者ID:google,项目名称:tmppy,代码行数:26,代码来源:_ast_to_ir2.py

示例3: visit_Subscript

# 需要导入模块: import ast [as 别名]
# 或者: from ast import Not [as 别名]
def visit_Subscript(self, node):
        args = self.visit(node.slice)
        if isinstance(node.value, ast.Name):
            array = node.value.id
            _buf = self._get_buffer_from_id(array)
            return _make.Call(_buf.dtype, array, args, _expr.Call.Halide, _buf.op, 0)
        elif isinstance(node.value, ast.Attribute):
            if not isinstance(node.value.value, ast.Name):
                raise ValueError("The root of array access is expect to be a id!")
            if node.value.attr != "shape":
                raise ValueError("Attribute access so far only 'shape' is supported!")
            if len(args) != 1:
                raise ValueError("For 'shape' access the argument should be only one!")
            args = args[0]
            #TODO: maybe support non-constant value later?
            if not isinstance(args, (_expr.IntImm, _expr.UIntImm)):
                raise ValueError("So far only constant shape access supported!")
            buf = self._get_buffer_from_id(node.value.value.id)
            return buf.shape[args.value]
        else:
            raise ValueError("Not supported yet!") 
开发者ID:mlperf,项目名称:training_results_v0.6,代码行数:23,代码来源:parser.py

示例4: p_if_elif_else

# 需要导入模块: import ast [as 别名]
# 或者: from ast import Not [as 别名]
def p_if_elif_else(t):
    '''elif : ELSE IF expression ELSE suite
            | ELSEAND IF expression ELSE suite'''
    # NOTE
    # 아니면 만약, 아니라면 만약 / 아니면서 만약
    # ELSE랑 충분히 헷갈릴 수 있으므로 일단 모두 처리가능하게
    not_ast = ast.Not()
    not_ast.lineno = t.lineno(2)
    nonassoc.col_offset = -1 # XXX

    cond = ast.UnaryOp(not_ast, t[3])
    cond.lineno = t.lineno(2)
    cond.col_offset = -1 # XXX

    elif_block = ast.If(cond, t[5], [])
    elif_block.lineno = t.lineno(4)
    elif_block.col_offset = -1  # XXX
    t[0] = elif_block 
开发者ID:yaksok,项目名称:yaksok,代码行数:20,代码来源:yacc.py

示例5: _evaluate

# 需要导入模块: import ast [as 别名]
# 或者: from ast import Not [as 别名]
def _evaluate(self, expr):
        if isinstance(expr, ast.Expr):
            return self._evaluate(expr.value)
        elif isinstance(expr, ast.BoolOp):
            if isinstance(expr.op, ast.Or):
                evaluated = ['({})'.format(self._evaluate(v)) for v in expr.values]
                return ' or '.join(evaluated)
            elif isinstance(expr.op, ast.And):
                evaluated = ['({})'.format(self._evaluate(v)) for v in expr.values]
                return ' and '.join(evaluated)
        elif isinstance(expr, ast.UnaryOp):
            if isinstance(expr.op, ast.Not):
                return 'not {}'.format(self._evaluate(expr.operand))
        elif isinstance(expr, ast.Num):
            return '"{}" in {}'.format(str(expr.n), self.tags)
        elif isinstance(expr, ast.Str):
            return '"{}" in {}'.format(expr.s, self.tags)
        elif isinstance(expr, ast.Name):
            return '"{}" in {}'.format(expr.id, self.tags)
        else:
            msg = ('unknown expression {}, the only valid operators for tag expressions '
                   'are: \'and\', \'or\' & \'not\''.format(type(expr)))
            raise InvalidTagExpression(msg) 
开发者ID:golemhq,项目名称:golem,代码行数:25,代码来源:tags_manager.py

示例6: visit_Return

# 需要导入模块: import ast [as 别名]
# 或者: from ast import Not [as 别名]
def visit_Return(self, node):
        _internal_assert(all(ty != Symbol.LoopVar for ty, _ in self.symbols.values()), \
                         "Return should not be in a loop body!")
        ids = []
        if isinstance(node.value, ast.Name):
            ids = [node.value.id]
        else:
            _internal_assert(isinstance(node.value, ast.Tuple), \
                             "You should return either a single tensor or a tuple")
            _internal_assert(all(isinstance(i, ast.Name) for i in node.value.elts), \
                             "What do you return?")
            ids = [i.id for i in node.value.elts]
        _internal_assert(len(set(ids)) == len(ids), "Duplicated tensors in the return tuples")
        if len(ids) < len(self.outputs):
            logging.log(logging.CRITICAL, '[Warning] Not all the output buffers returned!')
        self.outputs = [self.symbols[i][1] for i in ids]
        self.returned = True
        return util.make_nop() 
开发者ID:apache,项目名称:incubator-tvm,代码行数:20,代码来源:parser.py

示例7: visit_UnaryOp

# 需要导入模块: import ast [as 别名]
# 或者: from ast import Not [as 别名]
def visit_UnaryOp(self, node):
        self.visit(node.operand)
        op = node.op
        node.obj = node.operand.obj
        if isinstance(op, ast.Not):
            node.obj = bool()
        elif isinstance(op, ast.UAdd):
            node.obj = int(-1)
        elif isinstance(op, ast.USub):
            node.obj = int(-1) 
开发者ID:myhdl,项目名称:myhdl,代码行数:12,代码来源:_analyze.py

示例8: visit_UnaryOp

# 需要导入模块: import ast [as 别名]
# 或者: from ast import Not [as 别名]
def visit_UnaryOp(self, node, **kwargs):
        if isinstance(node.op, (ast.Not, ast.Invert)):
            return UnaryOp('~', self.visit(node.operand))
        elif isinstance(node.op, ast.USub):
            return self.const_type(-self.visit(node.operand).value, self.env)
        elif isinstance(node.op, ast.UAdd):
            raise NotImplementedError('Unary addition not supported') 
开发者ID:Frank-qlu,项目名称:recruit,代码行数:9,代码来源:pytables.py

示例9: visit_BoolOp

# 需要导入模块: import ast [as 别名]
# 或者: from ast import Not [as 别名]
def visit_BoolOp(self, boolop):
        res_var = self.variable()
        expl_list = self.assign(ast.List([], ast.Load()))
        app = ast.Attribute(expl_list, "append", ast.Load())
        is_or = int(isinstance(boolop.op, ast.Or))
        body = save = self.statements
        fail_save = self.expl_stmts
        levels = len(boolop.values) - 1
        self.push_format_context()
        # Process each operand, short-circuiting if needed.
        for i, v in enumerate(boolop.values):
            if i:
                fail_inner = []
                # cond is set in a prior loop iteration below
                self.expl_stmts.append(ast.If(cond, fail_inner, []))  # noqa
                self.expl_stmts = fail_inner
            self.push_format_context()
            res, expl = self.visit(v)
            body.append(ast.Assign([ast.Name(res_var, ast.Store())], res))
            expl_format = self.pop_format_context(ast.Str(expl))
            call = ast.Call(app, [expl_format], [])
            self.expl_stmts.append(ast.Expr(call))
            if i < levels:
                cond = res
                if is_or:
                    cond = ast.UnaryOp(ast.Not(), cond)
                inner = []
                self.statements.append(ast.If(cond, inner, []))
                self.statements = body = inner
        self.statements = save
        self.expl_stmts = fail_save
        expl_template = self.helper("_format_boolop", expl_list, ast.Num(is_or))
        expl = self.pop_format_context(expl_template)
        return ast.Name(res_var, ast.Load()), self.explanation_param(expl) 
开发者ID:sofia-netsurv,项目名称:python-netsurv,代码行数:36,代码来源:rewrite.py

示例10: _clause

# 需要导入模块: import ast [as 别名]
# 或者: from ast import Not [as 别名]
def _clause(self, pt: parsing.ParserTree) -> [ast.stmt]:
        """Normalize a test expression into a statements list.

        Statements list are returned as-is.
        Expression is packaged as:
        if not expr:
            return False
        """
        if isinstance(pt, list):
            return pt
        return [ast.If(ast.UnaryOp(ast.Not(), pt),
                       [self.__exit_scope()],
                       [])] 
开发者ID:LionelAuroux,项目名称:pyrser,代码行数:15,代码来源:topython.py

示例11: invert

# 需要导入模块: import ast [as 别名]
# 或者: from ast import Not [as 别名]
def invert(node):
    """
    Invert the operation in an ast node object (get its negation).

    Args:
        node: An ast node object.

    Returns:
        An ast node object containing the inverse (negation) of the input node.
    """
    inverse = {ast.Eq: ast.NotEq,
               ast.NotEq: ast.Eq,
               ast.Lt: ast.GtE,
               ast.LtE: ast.Gt,
               ast.Gt: ast.LtE,
               ast.GtE: ast.Lt,
               ast.Is: ast.IsNot,
               ast.IsNot: ast.Is,
               ast.In: ast.NotIn,
               ast.NotIn: ast.In}

    if type(node) == ast.Compare:
        op = type(node.ops[0])
        inverse_node = ast.Compare(left=node.left, ops=[inverse[op]()],
                                   comparators=node.comparators)
    elif isinstance(node, ast.BinOp) and type(node.op) in inverse:
        op = type(node.op)
        inverse_node = ast.BinOp(node.left, inverse[op](), node.right)
    elif type(node) == ast.NameConstant and node.value in [True, False]:
        inverse_node = ast.NameConstant(value=not node.value)
    else:
        inverse_node = ast.UnaryOp(op=ast.Not(), operand=node)

    return inverse_node 
开发者ID:coetaur0,项目名称:staticfg,代码行数:36,代码来源:builder.py

示例12: __init__

# 需要导入模块: import ast [as 别名]
# 或者: from ast import Not [as 别名]
def __init__( s, component ):
    super().__init__( component )
    s.loop_var_env = set()
    s.tmp_var_env = set()

    # opmap maps an ast operator to its RTLIR counterpart.
    s.opmap = {
      # Bool operators
      # Note: we do not support boolean operators because Python does
      # not allow overloading And and Or operators. Using them in
      # expressions might lead to inconsistent semantics.
      # ast.And    : bir.And(),       ast.Or     : bir.Or(),
      # Unary operators
      # Note: ast.Not is disallowed because it is a boolean operator
      # ast.Not    : bir.Not(),
      ast.Invert : bir.Invert(),
      ast.UAdd   : bir.UAdd(),      ast.USub   : bir.USub(),
      # Binary operators
      ast.Add    : bir.Add(),       ast.Sub    : bir.Sub(),
      ast.Mult   : bir.Mult(),      ast.Div    : bir.Div(),
      ast.Mod    : bir.Mod(),       ast.Pow    : bir.Pow(),
      ast.LShift : bir.ShiftLeft(), ast.RShift : bir.ShiftRightLogic(),
      ast.BitOr  : bir.BitOr(),     ast.BitAnd : bir.BitAnd(),
      ast.BitXor : bir.BitXor(),
      # Compare bir.bir.operators
      ast.Eq     : bir.Eq(),        ast.NotEq  : bir.NotEq(),
      ast.Lt     : bir.Lt(),        ast.LtE    : bir.LtE(),
      ast.Gt     : bir.Gt(),        ast.GtE    : bir.GtE()
    }

  # Override 
开发者ID:pymtl,项目名称:pymtl3,代码行数:33,代码来源:BehavioralRTLIRGenL2Pass.py

示例13: visit_BoolOp

# 需要导入模块: import ast [as 别名]
# 或者: from ast import Not [as 别名]
def visit_BoolOp(self, boolop: ast.BoolOp) -> Tuple[ast.Name, str]:
        res_var = self.variable()
        expl_list = self.assign(ast.List([], ast.Load()))
        app = ast.Attribute(expl_list, "append", ast.Load())
        is_or = int(isinstance(boolop.op, ast.Or))
        body = save = self.statements
        fail_save = self.expl_stmts
        levels = len(boolop.values) - 1
        self.push_format_context()
        # Process each operand, short-circuiting if needed.
        for i, v in enumerate(boolop.values):
            if i:
                fail_inner = []  # type: List[ast.stmt]
                # cond is set in a prior loop iteration below
                self.expl_stmts.append(ast.If(cond, fail_inner, []))  # noqa
                self.expl_stmts = fail_inner
            self.push_format_context()
            res, expl = self.visit(v)
            body.append(ast.Assign([ast.Name(res_var, ast.Store())], res))
            expl_format = self.pop_format_context(ast.Str(expl))
            call = ast.Call(app, [expl_format], [])
            self.expl_stmts.append(ast.Expr(call))
            if i < levels:
                cond = res  # type: ast.expr
                if is_or:
                    cond = ast.UnaryOp(ast.Not(), cond)
                inner = []  # type: List[ast.stmt]
                self.statements.append(ast.If(cond, inner, []))
                self.statements = body = inner
        self.statements = save
        self.expl_stmts = fail_save
        expl_template = self.helper("_format_boolop", expl_list, ast.Num(is_or))
        expl = self.pop_format_context(expl_template)
        return ast.Name(res_var, ast.Load()), self.explanation_param(expl) 
开发者ID:pytest-dev,项目名称:pytest,代码行数:36,代码来源:rewrite.py

示例14: _translate_unaryop

# 需要导入模块: import ast [as 别名]
# 或者: from ast import Not [as 别名]
def _translate_unaryop(self, operand, op, location):
        value = operand
        if isinstance(op, ast.USub):
            value_node = self._translate_node(value)
            if value_node['pseudo_type'] != 'Int' and value_node['pseudo_type'] != 'Float':
                raise type_check_error('- expects Int or Float',
                    location, self.lines[location[0]],
                    wrong_type=value_node['pseudo_type'])
            if value_node['type'] == 'int':
                return {
                    'type': 'int',
                    'value': -value_node['value'],
                    'pseudo_type': 'Int'
                }
            else:
                return {
                    'type': 'unary_op',
                    'op': '-',
                    'value': value_node,
                    'pseudo_type': value_node['pseudo_type']
                }
        elif isinstance(op, ast.Not):
            value_node = self._testable(self._translate_node(value))
            if value_node['type'] == 'standard_method_call' and value_node['message'] == 'present?':
                value_node['message'] = 'empty?'
                return value_node
            else:
                return {
                    'type': 'unary_op',
                    'op': 'not',
                    'value': value_node,
                    'pseudo_type': 'Boolean'
                }
        else:
            raise translation_error('no support for %s as an unary op' % type(op).__name__,
                location, self.lines[location[0]],
                suggestions='not and - are supported') 
开发者ID:pseudo-lang,项目名称:pseudo-python,代码行数:39,代码来源:ast_translator.py

示例15: visit_UnaryOp

# 需要导入模块: import ast [as 别名]
# 或者: from ast import Not [as 别名]
def visit_UnaryOp(self, node: ast.UnaryOp) -> Any:
        """Visit the node operand and apply the operation on the result."""
        if isinstance(node.op, ast.UAdd):
            result = +self.visit(node=node.operand)
        elif isinstance(node.op, ast.USub):
            result = -self.visit(node=node.operand)
        elif isinstance(node.op, ast.Not):
            result = not self.visit(node=node.operand)
        elif isinstance(node.op, ast.Invert):
            result = ~self.visit(node=node.operand)
        else:
            raise NotImplementedError("Unhandled op of {}: {}".format(node, node.op))

        self.recomputed_values[node] = result
        return result 
开发者ID:Parquery,项目名称:icontract,代码行数:17,代码来源:_recompute.py


注:本文中的ast.Not方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。