當前位置: 首頁>>代碼示例>>Python>>正文


Python ast.BinOp方法代碼示例

本文整理匯總了Python中ast.BinOp方法的典型用法代碼示例。如果您正苦於以下問題:Python ast.BinOp方法的具體用法?Python ast.BinOp怎麽用?Python ast.BinOp使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在ast的用法示例。


在下文中一共展示了ast.BinOp方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: visit_Compare

# 需要導入模塊: import ast [as 別名]
# 或者: from ast import BinOp [as 別名]
def visit_Compare(self, node, **kwargs):
        ops = node.ops
        comps = node.comparators

        # base case: we have something like a CMP b
        if len(comps) == 1:
            op = self.translate_In(ops[0])
            binop = ast.BinOp(op=op, left=node.left, right=comps[0])
            return self.visit(binop)

        # recursive case: we have a chained comparison, a CMP b CMP c, etc.
        left = node.left
        values = []
        for op, comp in zip(ops, comps):
            new_node = self.visit(ast.Compare(comparators=[comp], left=left,
                                              ops=[self.translate_In(op)]))
            left = comp
            values.append(new_node)
        return self.visit(ast.BoolOp(op=ast.And(), values=values)) 
開發者ID:Frank-qlu,項目名稱:recruit,代碼行數:21,代碼來源:expr.py

示例2: test_afterSubMult

# 需要導入模塊: import ast [as 別名]
# 或者: from ast import BinOp [as 別名]
def test_afterSubMult(self):
        'Tests after SubToMult pre-processing'

        tests = [("1 + 2 - 3", ast.BoolOp(ast.Add(), [ast.Num(1), ast.Num(2),
                                                      ast.BinOp(ast.Num(-1),
                                                                ast.Mult(),
                                                                ast.Num(3))])),
                 ("1 + 2 - 3 + 4", ast.BoolOp(ast.Add(),
                                              [ast.Num(1),
                                               ast.Num(2),
                                               ast.BinOp(ast.Num(-1),
                                                         ast.Mult(),
                                                         ast.Num(3)),
                                               ast.Num(4)])),
                 ("(1 + 2) - (3 + 4)",
                  ast.BoolOp(ast.Add(),
                             [ast.Num(1), ast.Num(2),
                              ast.BinOp(ast.Num(-1), ast.Mult(),
                                        ast.BinOp(ast.Num(3), ast.Add(),
                                                  ast.Num(4)))]))]
        for teststring, ref_ast in tests:
            test_ast = ast.parse(teststring, mode="eval").body
            test_ast = pre_processing.all_preprocessings(test_ast)
            test_ast = Flattening(ast.Add).visit(test_ast)
            self.assertTrue(Comparator().visit(test_ast, ref_ast)) 
開發者ID:quarkslab,項目名稱:sspam,代碼行數:27,代碼來源:test_flattening.py

示例3: test_noflattening

# 需要導入模塊: import ast [as 別名]
# 或者: from ast import BinOp [as 別名]
def test_noflattening(self):
        'Tests where nothing should be flattened'
        corresp = [(["a + b", "b + a"],
                   ast.BinOp(ast.Name('a', ast.Load()),
                             ast.Add(),
                             ast.Name('b', ast.Load()))),
                   (["c*d", "d*c"],
                    ast.BinOp(ast.Name('c', ast.Load()),
                              ast.Mult(),
                              ast.Name('d', ast.Load()))),
                   (["a + c*d", "d*c + a"],
                    ast.BinOp(ast.Name('a', ast.Load()), ast.Add(),
                              ast.BinOp(ast.Name('c', ast.Load()), ast.Mult(),
                                        ast.Name('d', ast.Load()))))]
        for refstring, result in corresp:
            self.generic_flattening(refstring, result) 
開發者ID:quarkslab,項目名稱:sspam,代碼行數:18,代碼來源:test_flattening.py

示例4: visit_UnaryOp

# 需要導入模塊: import ast [as 別名]
# 或者: from ast import BinOp [as 別名]
def visit_UnaryOp(self, node):
        'Change -x to (-1)*x'
        self.generic_visit(node)
        if isinstance(node.op, ast.USub):
            ope = node.operand
            cond_mult = (isinstance(ope, ast.BinOp) and
                         isinstance(ope.op, ast.Mult))
            if cond_mult:
                if isinstance(ope.left, ast.Num):
                    node = ast.BinOp(ast.Num(-ope.left.n), ast.Mult(),
                                     ope.right)
                elif isinstance(ope.right, ast.Num):
                    node = ast.BinOp(ope.left, ast.Mult(),
                                     ast.Num(-ope.right.n))
                else:
                    node = ast.BinOp(ast.Num(-1), ast.Mult(), ope)
            else:
                node = ast.BinOp(ast.Num(-1), ast.Mult(), ope)
        return node 
開發者ID:quarkslab,項目名稱:sspam,代碼行數:21,代碼來源:pre_processing.py

示例5: check_neg

# 需要導入模塊: import ast [as 別名]
# 或者: from ast import BinOp [as 別名]
def check_neg(self, target, pattern):
        'Check (-1)*... pattern that could be in another form'
        if self.is_wildcard(pattern.right):
            wkey = pattern.right.id
            if isinstance(target, ast.Num):
                if wkey not in self.wildcards:
                    mod = 2**self.nbits
                    self.wildcards[wkey] = ast.Num((-target.n) % mod)
                    return True
                else:
                    wilds2 = self.wildcards[pattern.right.id]
                    num = ast.Num((-target.n) % 2**self.nbits)
                    return asttools.Comparator().visit(wilds2, num)
            else:
                if wkey not in self.wildcards:
                    self.wildcards[wkey] = ast.BinOp(ast.Num(-1),
                                                     ast.Mult(), target)
                    return True
        return self.check_eq_z3(target, pattern) 
開發者ID:quarkslab,項目名稱:sspam,代碼行數:21,代碼來源:pattern_matcher.py

示例6: __init__

# 需要導入模塊: import ast [as 別名]
# 或者: from ast import BinOp [as 別名]
def __init__(self, patt_ast, target_ast, rep_ast, nbits=0):
        'Pattern ast should have as root: BinOp, BoolOp, UnaryOp or Call'
        if isinstance(patt_ast, ast.Module):
            self.patt_ast = patt_ast.body[0].value
        elif isinstance(patt_ast, ast.Expression):
            self.patt_ast = patt_ast.body
        else:
            self.patt_ast = patt_ast
        if isinstance(rep_ast, ast.Module):
            self.rep_ast = deepcopy(rep_ast.body[0].value)
        elif isinstance(rep_ast, ast.Expression):
            self.rep_ast = deepcopy(rep_ast.body)
        else:
            self.rep_ast = deepcopy(rep_ast)

        if not nbits:
            getsize = asttools.GetSize()
            getsize.visit(target_ast)
            if getsize.result:
                self.nbits = getsize.result
            # default bitsize is 8
            else:
                self.nbits = 8
        else:
            self.nbits = nbits 
開發者ID:quarkslab,項目名稱:sspam,代碼行數:27,代碼來源:pattern_matcher.py

示例7: visit_BinOp

# 需要導入模塊: import ast [as 別名]
# 或者: from ast import BinOp [as 別名]
def visit_BinOp(self, node):
        'If node is a constant expression, replace it with its evaluated value'
        if node in self.constexpr:
            # evaluation
            fake_node = ast.Expression(ast.BinOp(node, ast.Mod(),
                                                 ast.Num(self.mod)))
            ast.fix_missing_locations(fake_node)
            code = compile(fake_node, '<constant folding>', 'eval')
            obj_env = globals().copy()
            exec code in obj_env
            value = eval(code, obj_env)

            new_node = ast.Num(value)
            return new_node
        else:
            return self.generic_visit(node) 
開發者ID:quarkslab,項目名稱:sspam,代碼行數:18,代碼來源:asttools.py

示例8: visit_UnaryOp

# 需要導入模塊: import ast [as 別名]
# 或者: from ast import BinOp [as 別名]
def visit_UnaryOp(self, node):
        'Same idea as visit_BinOp'
        if node in self.constexpr:
            # evaluation
            fake_node = ast.Expression(ast.BinOp(node, ast.Mod(),
                                                 ast.Num(self.mod)))
            ast.fix_missing_locations(fake_node)
            code = compile(fake_node, '<constant folding>', 'eval')
            obj_env = globals().copy()
            exec code in obj_env

            value = eval(code, obj_env)
            new_node = ast.Num(value)
            return new_node
        else:
            return self.generic_visit(node) 
開發者ID:quarkslab,項目名稱:sspam,代碼行數:18,代碼來源:asttools.py

示例9: visit_BinOp

# 需要導入模塊: import ast [as 別名]
# 或者: from ast import BinOp [as 別名]
def visit_BinOp(self, node, partial=False):
        'Regroup associative operators'
        if isinstance(node.op, self.op):
            operands = []
            for child in node.left, node.right:
                cond = (isinstance(child, ast.BinOp)
                        and isinstance(child.op, self.op)
                        and self.op in ASSOCIATIVE_OPERATORS)
                if cond:
                    operands.extend(self.visit_BinOp(child, partial=True))
                else:
                    self.visit(child)
                    operands.append(child)
            if not partial:
                self.result_nodes.append(node)
                self.result.append(operands)
            return operands
        else:
            self.generic_visit(node)
            return [] 
開發者ID:quarkslab,項目名稱:sspam,代碼行數:22,代碼來源:cse.py

示例10: pop_format_context

# 需要導入模塊: import ast [as 別名]
# 或者: from ast import BinOp [as 別名]
def pop_format_context(self, expl_expr):
        """Format the %-formatted string with current format context.

        The expl_expr should be an ast.Str instance constructed from
        the %-placeholders created by .explanation_param().  This will
        add the required code to format said string to .expl_stmts and
        return the ast.Name instance of the formatted string.

        """
        current = self.stack.pop()
        if self.stack:
            self.explanation_specifiers = self.stack[-1]
        keys = [ast.Str(key) for key in current.keys()]
        format_dict = ast.Dict(keys, list(current.values()))
        form = ast.BinOp(expl_expr, ast.Mod(), format_dict)
        name = "@py_format" + str(next(self.variable_counter))
        if self.enable_assertion_pass_hook:
            self.format_variables.append(name)
        self.expl_stmts.append(ast.Assign([ast.Name(name, ast.Store())], form))
        return ast.Name(name, ast.Load()) 
開發者ID:sofia-netsurv,項目名稱:python-netsurv,代碼行數:22,代碼來源:rewrite.py

示例11: test_increment_lineno

# 需要導入模塊: import ast [as 別名]
# 或者: from ast import BinOp [as 別名]
def test_increment_lineno(self):
        src = ast.parse('1 + 1', mode='eval')
        self.assertEqual(ast.increment_lineno(src, n=3), src)
        self.assertEqual(ast.dump(src, include_attributes=True),
            'Expression(body=BinOp(left=Num(n=1, lineno=4, col_offset=0), '
            'op=Add(), right=Num(n=1, lineno=4, col_offset=4), lineno=4, '
            'col_offset=0))'
        )
        # issue10869: do not increment lineno of root twice
        src = ast.parse('1 + 1', mode='eval')
        self.assertEqual(ast.increment_lineno(src.body, n=3), src.body)
        self.assertEqual(ast.dump(src, include_attributes=True),
            'Expression(body=BinOp(left=Num(n=1, lineno=4, col_offset=0), '
            'op=Add(), right=Num(n=1, lineno=4, col_offset=4), lineno=4, '
            'col_offset=0))'
        ) 
開發者ID:IronLanguages,項目名稱:ironpython2,代碼行數:18,代碼來源:test_ast.py

示例12: test_nodeclasses

# 需要導入模塊: import ast [as 別名]
# 或者: from ast import BinOp [as 別名]
def test_nodeclasses(self):
        # IronPyhon performs argument typechecking
        l=ast.Str('A')
        o=ast.Mult()
        r=ast.Num('13')
        x=ast.BinOp(l,o,r,lineno=42)
        self.assertEqual(x.left, l)
        self.assertEqual(x.op, o)
        self.assertEqual(x.right, r)
        self.assertEqual(x.lineno, 42)

        # node raises exception when not given enough arguments
        self.assertRaises(TypeError, ast.BinOp, l, o)

        # can set attributes through kwargs too
        x = ast.BinOp(left=l, op=o, right=r, lineno=42)
        self.assertEqual(x.left, l)
        self.assertEqual(x.op, o)
        self.assertEqual(x.right, r)
        self.assertEqual(x.lineno, 42)

        # this used to fail because Sub._fields was None
        x = ast.Sub() 
開發者ID:IronLanguages,項目名稱:ironpython2,代碼行數:25,代碼來源:test_ast.py

示例13: _fix_percent_format_tuple

# 需要導入模塊: import ast [as 別名]
# 或者: from ast import BinOp [as 別名]
def _fix_percent_format_tuple(
        tokens: List[Token],
        start: int,
        node: ast.BinOp,
) -> None:
    # TODO: this is overly timid
    paren = start + 4
    if tokens_to_src(tokens[start + 1:paren + 1]) != ' % (':
        return

    victims = _victims(tokens, paren, node.right, gen=False)
    victims.ends.pop()

    for index in reversed(victims.starts + victims.ends):
        _remove_brace(tokens, index)

    newsrc = _percent_to_format(tokens[start].src)
    tokens[start] = tokens[start]._replace(src=newsrc)
    tokens[start + 1:paren] = [Token('Format', '.format'), Token('OP', '(')] 
開發者ID:asottile,項目名稱:pyupgrade,代碼行數:21,代碼來源:pyupgrade.py

示例14: pop_format_context

# 需要導入模塊: import ast [as 別名]
# 或者: from ast import BinOp [as 別名]
def pop_format_context(self, expl_expr: ast.expr) -> ast.Name:
        """Format the %-formatted string with current format context.

        The expl_expr should be an str ast.expr instance constructed from
        the %-placeholders created by .explanation_param().  This will
        add the required code to format said string to .expl_stmts and
        return the ast.Name instance of the formatted string.

        """
        current = self.stack.pop()
        if self.stack:
            self.explanation_specifiers = self.stack[-1]
        keys = [ast.Str(key) for key in current.keys()]
        format_dict = ast.Dict(keys, list(current.values()))
        form = ast.BinOp(expl_expr, ast.Mod(), format_dict)
        name = "@py_format" + str(next(self.variable_counter))
        if self.enable_assertion_pass_hook:
            self.format_variables.append(name)
        self.expl_stmts.append(ast.Assign([ast.Name(name, ast.Store())], form))
        return ast.Name(name, ast.Load()) 
開發者ID:pytest-dev,項目名稱:pytest,代碼行數:22,代碼來源:rewrite.py

示例15: visit_BinOp

# 需要導入模塊: import ast [as 別名]
# 或者: from ast import BinOp [as 別名]
def visit_BinOp(self, node: ast.BinOp) -> Union[ast.BinOp, ast.Num]:
        """Evaluate binary operation and return ast.Num if operands are bound.

        Args:
            node: Binary operation to evaluate.

        Returns:
            Evaluated value.
        """
        node.left = self.visit(node.left)
        node.right = self.visit(node.right)
        if isinstance(node.left, ast.Num) and isinstance(node.right, ast.Num):
            val = ast.Num(n=self._match_ops(node.op, self._binary_ops,
                                            node.left.n, node.right.n))
            return ast.copy_location(val, node)
        return node 
開發者ID:Qiskit,項目名稱:qiskit-terra,代碼行數:18,代碼來源:parser.py


注:本文中的ast.BinOp方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。