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


Python ast.Or方法代码示例

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


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

示例1: test_MutateAST_visit_boolop

# 需要导入模块: import ast [as 别名]
# 或者: from ast import Or [as 别名]
def test_MutateAST_visit_boolop(boolop_file, boolop_expected_loc):
    """Test mutation of AND to OR in the boolop."""
    tree = Genome(boolop_file).ast
    test_mutation = ast.Or

    # apply the mutation to the original tree copy
    testing_tree = deepcopy(tree)
    mutated_tree = MutateAST(target_idx=boolop_expected_loc, mutation=test_mutation).visit(
        testing_tree
    )

    # revisit in read-only mode to gather the locations of the new nodes
    mast = MutateAST(readonly=True)
    mast.visit(mutated_tree)

    # four locations from the binary operations in binop_file
    assert len(mast.locs) == 1

    # there will only be one loc, but this still works
    # basedon the col and line offset in the fixture for compare_expected_loc
    for loc in mast.locs:
        if loc.lineno == 2 and loc.col_offset == 11:
            assert loc.op_type == test_mutation 
开发者ID:EvanKepner,项目名称:mutatest,代码行数:25,代码来源:test_transformers.py

示例2: verify_ast

# 需要导入模块: import ast [as 别名]
# 或者: from ast import Or [as 别名]
def verify_ast(expr, variables_and_values):
  """Verifies that |expr| is of the form
  expr ::= expr ( "or" | "and" ) expr
         | identifier "==" ( string | int )
  Also collects the variable identifiers and string/int values in the dict
  |variables_and_values|, in the form {'var': set([val1, val2, ...]), ...}.
  """
  assert isinstance(expr, (ast.BoolOp, ast.Compare))
  if isinstance(expr, ast.BoolOp):
    assert isinstance(expr.op, (ast.And, ast.Or))
    for subexpr in expr.values:
      verify_ast(subexpr, variables_and_values)
  else:
    assert isinstance(expr.left.ctx, ast.Load)
    assert len(expr.ops) == 1
    assert isinstance(expr.ops[0], ast.Eq)
    var_values = variables_and_values.setdefault(expr.left.id, set())
    rhs = expr.comparators[0]
    assert isinstance(rhs, (ast.Str, ast.Num))
    var_values.add(rhs.n if isinstance(rhs, ast.Num) else rhs.s) 
开发者ID:luci,项目名称:luci-py,代码行数:22,代码来源:isolate_format.py

示例3: boolop

# 需要导入模块: import ast [as 别名]
# 或者: from ast import Or [as 别名]
def boolop(self, block, node, var=None):
    #Get the type of operation
    if isinstance(node.op, ast.And):
      op = Operator.bool_and
    elif isinstance(node.op, ast.Or):
      op = Operator.bool_or
    else:
      raise Exception('Unexpected BoolOp (%s)'%(node.op.__class__))
    #Chain operations together
    left = self.expression(block, node.values[0])
    for node_value in node.values[1:]:
      right = self.expression(block, node_value)
      operation = BinaryOperation(left, op, right)
      if node_value == node.values[-1] and var is not None:
        #The last operation in the chain should be assigned to this variable
        temp_var = var
      else:
        #Create a temporary variable to store the intermediate result
        temp_var = self.add_variable(None, is_mask=True)
      assignment = Assignment(temp_var, operation)
      block.add(assignment)
      left = temp_var
    return temp_var

  #Parses an array element (AST Subscript) 
开发者ID:undefx,项目名称:vecpy,代码行数:27,代码来源:parser.py

示例4: normalize_boolop

# 需要导入模块: import ast [as 别名]
# 或者: from ast import Or [as 别名]
def normalize_boolop(expr):
    """
    Normalize a boolop by folding together nested And/Or exprs.
    """
    optype = expr.op
    newvalues = []
    for subexpr in expr.values:
        if not isinstance(subexpr, ast.BoolOp):
            newvalues.append(subexpr)
        elif type(subexpr.op) != type(optype):
            newvalues.append(normalize_boolop(subexpr))
        else:
            # Normalize subexpression, then inline its values into the
            # top-level subexpr.
            newvalues.extend(normalize_boolop(subexpr).values)
    return ast.BoolOp(op=optype, values=newvalues) 
开发者ID:llllllllll,项目名称:codetransformer,代码行数:18,代码来源:_343.py

示例5: p_logic_or_expr

# 需要导入模块: import ast [as 别名]
# 或者: from ast import Or [as 别名]
def p_logic_or_expr(t):
    '''logic_or_expr : logic_or_expr OR logic_and_expr
                     | logic_and_expr'''
    if len(t) == 4:
        if isinstance(t[1], ast.BoolOp) and isinstance(t[1].op, ast.Or):
            t[0] = t[1]
            t[0].values.append(t[3])
        else:
            or_ast = ast.Or()
            or_ast.lineno = t.lineno(2)
            or_ast.col_offset = -1 # XXX
            t[0] = ast.BoolOp(or_ast, [t[1], t[3]])
            t[0].lineno = t.lineno(2)
            t[0].col_offset = -1 # XXX
    else:
        t[0] = t[1] 
开发者ID:yaksok,项目名称:yaksok,代码行数:18,代码来源:yacc.py

示例6: gen_bool_op

# 需要导入模块: import ast [as 别名]
# 或者: from ast import Or [as 别名]
def gen_bool_op(self, condition, yes_block, no_block):
        """ Compile a boolean operator such as 'and' """
        assert len(condition.values) >= 1
        first_values = condition.values[:-1]
        last_value = condition.values[-1]
        if isinstance(condition.op, ast.And):
            # All values must be true here,
            # so bail out on first false value.
            for value in first_values:
                all_true_block = self.builder.new_block()
                self.gen_cond(value, all_true_block, no_block)
                self.builder.set_block(all_true_block)

            self.gen_cond(last_value, yes_block, no_block)
        elif isinstance(condition.op, ast.Or):
            # The first true value is enough to make this work!
            for value in first_values:
                all_false_block = self.builder.new_block()
                self.gen_cond(value, yes_block, all_false_block)
                self.builder.set_block(all_false_block)

            self.gen_cond(last_value, yes_block, no_block)
        else:  # pragma: no cover
            self.not_impl(condition) 
开发者ID:windelbouwman,项目名称:ppci,代码行数:26,代码来源:python2ir.py

示例7: _evaluate

# 需要导入模块: import ast [as 别名]
# 或者: from ast import Or [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

示例8: visit_BoolOp

# 需要导入模块: import ast [as 别名]
# 或者: from ast import Or [as 别名]
def visit_BoolOp(self, boolop):
        is_or = isinstance(boolop.op, ast.Or)
        explanations = []
        for operand in boolop.values:
            explanation, result = self.visit(operand)
            explanations.append(explanation)
            if result == is_or:
                break
        name = is_or and " or " or " and "
        explanation = "(" + name.join(explanations) + ")"
        return explanation, result 
开发者ID:pytest-dev,项目名称:py,代码行数:13,代码来源:_assertionnew.py

示例9: do_boolop

# 需要导入模块: import ast [as 别名]
# 或者: from ast import Or [as 别名]
def do_boolop(self, node):
        result = self.evaluate(node.values[0])
        is_or = node.op.__class__ is ast.Or
        is_and = node.op.__class__ is ast.And
        assert is_or or is_and
        if (is_and and result) or (is_or and not result):
            for n in node.values[1:]:
                result = self.evaluate(n)
                if (is_or and result) or (is_and and not result):
                    break
        return result 
开发者ID:Frank-qlu,项目名称:recruit,代码行数:13,代码来源:markers.py

示例10: visit_Name

# 需要导入模块: import ast [as 别名]
# 或者: from ast import Or [as 别名]
def visit_Name(self, name):
        # Display the repr of the name if it's a local variable or
        # _should_repr_global_name() thinks it's acceptable.
        locs = ast.Call(self.builtin("locals"), [], [])
        inlocs = ast.Compare(ast.Str(name.id), [ast.In()], [locs])
        dorepr = self.helper("_should_repr_global_name", name)
        test = ast.BoolOp(ast.Or(), [inlocs, dorepr])
        expr = ast.IfExp(test, self.display(name), ast.Str(name.id))
        return name, self.explanation_param(expr) 
开发者ID:sofia-netsurv,项目名称:python-netsurv,代码行数:11,代码来源:rewrite.py

示例11: visit_BoolOp

# 需要导入模块: import ast [as 别名]
# 或者: from ast import Or [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

示例12: or_expression_ast_to_ir2

# 需要导入模块: import ast [as 别名]
# 或者: from ast import Or [as 别名]
def or_expression_ast_to_ir2(ast_node: ast.BoolOp,
                             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.Or)

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

    if not compilation_context.current_function_name:
        raise CompilationError(compilation_context, ast_node,
                               'The "or" operator is only supported in functions, not at toplevel.')

    assert len(ast_node.values) >= 2

    exprs = []
    for expr_ast_node in ast_node.values:
        expr = expression_ast_to_ir2(expr_ast_node,
                                     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, expr_ast_node,
                                   'The "or" operator is only supported for booleans, but this value has type %s.' % str(expr.expr_type))
        exprs.append(expr)

    final_expr = exprs[-1]
    for expr in reversed(exprs[:-1]):
        final_expr = ir2.OrExpr(lhs=expr, rhs=final_expr)

    return final_expr 
开发者ID:google,项目名称:tmppy,代码行数:38,代码来源:_ast_to_ir2.py

示例13: visit_CallTrue

# 需要导入模块: import ast [as 别名]
# 或者: from ast import Or [as 别名]
def visit_CallTrue(self, node: parsing.CallTrue) -> ast.expr:
        """Generates python code calling the function and returning True.

        lambda: fn(*args) or True
        """
        return ast.Lambda(
            ast.arguments([], None, None, [], None, None, [], []),
            ast.BoolOp(
                ast.Or(),
                [
                    self.visit_Call(node),
                    ast.Name('True', ast.Load())])) 
开发者ID:LionelAuroux,项目名称:pyrser,代码行数:14,代码来源:topython.py

示例14: visit_Alt

# 需要导入模块: import ast [as 别名]
# 或者: from ast import Or [as 别名]
def visit_Alt(self, node: parsing.Alt) -> [ast.stmt]:
        """Generates python code for alternatives.

        try:
            try:
                <code for clause>  #raise AltFalse when alternative is False
                raise AltTrue()
            except AltFalse:
                pass
            return False
        except AltTrue:
            pass
        """
        clauses = [self.visit(clause) for clause in node.ptlist]
        for clause in clauses:
            if not isinstance(clause, ast.expr):
                break
        else:
            return ast.BoolOp(ast.Or(), clauses)
        res = ast.Try([], [ast.ExceptHandler(
            ast.Name('AltTrue', ast.Load()), None, [ast.Pass()])], [], [])
        alt_true = [ast.Raise(ast.Call(
            ast.Name('AltTrue', ast.Load()), [], [], None, None), None)]
        alt_false = [ast.ExceptHandler(
            ast.Name('AltFalse', ast.Load()), None, [ast.Pass()])]
        self.in_try += 1
        for clause in node.ptlist:
            res.body.append(
                ast.Try(self._clause(self.visit(clause)) + alt_true,
                        alt_false, [], []))
        self.in_try -= 1
        res.body.append(self.__exit_scope())
        return [res] 
开发者ID:LionelAuroux,项目名称:pyrser,代码行数:35,代码来源:topython.py

示例15: visit_RepOptional

# 需要导入模块: import ast [as 别名]
# 或者: from ast import Or [as 别名]
def visit_RepOptional(self, node: parsing.RepOptional) -> ([ast.stmt] or
                                                               ast.expr):
        """Generates python code for an optional clause.

        <code for the clause>
        """
        cl_ast = self.visit(node.pt)
        if isinstance(cl_ast, ast.expr):
            return ast.BoolOp(ast.Or(), [cl_ast, ast.Name('True', ast.Load())])
        self.in_optional += 1
        cl_ast = self.visit(node.pt)
        self.in_optional -= 1
        return cl_ast 
开发者ID:LionelAuroux,项目名称:pyrser,代码行数:15,代码来源:topython.py


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