當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。