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


Python ast.Add方法代码示例

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


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

示例1: visit_AugAssign

# 需要导入模块: import ast [as 别名]
# 或者: from ast import Add [as 别名]
def visit_AugAssign(self, node):
        # XXX apparently no signed context required for augmented assigns
        left, op, right = node.target, node.op, node.value
        isFunc = False
        pre, suf = "", ""
        if isinstance(op, (ast.Add, ast.Sub, ast.Mult, ast.Mod, ast.FloorDiv)):
            pre, suf = self.inferBinaryOpCast(node, left, right, op)
        elif isinstance(op, (ast.LShift, ast.RShift)):
            isFunc = True
            pre, suf = self.inferShiftOpCast(node, left, right, op)
        self.visit(left)
        self.write(" := ")
        self.write(pre)
        if isFunc:
            self.write("%s(" % opmap[type(op)])
        self.visit(left)
        if isFunc:
            self.write(", ")
        else:
            self.write(" %s " % opmap[type(op)])
        self.visit(right)
        if isFunc:
            self.write(")")
        self.write(suf)
        self.write(";") 
开发者ID:myhdl,项目名称:myhdl,代码行数:27,代码来源:_toVHDL.py

示例2: augassign_rewrite

# 需要导入模块: import ast [as 别名]
# 或者: from ast import Add [as 别名]
def augassign_rewrite(it: Tokenizer):
    return {
        '+=': ast.Add,
        '-=': ast.Sub,
        '*=': ast.Mult,
        '/=': ast.Div,
        '//=': ast.FloorDiv,
        '@=': ast.MatMult,
        '%=': ast.Mod,
        '&=': ast.BitAnd,
        '|=': ast.BitOr,
        '^=': ast.BitXor,
        '<<=': ast.LShift,
        '>>=': ast.RShift,
        '**=': ast.Pow,
    }[it.value] 
开发者ID:Xython,项目名称:YAPyPy,代码行数:18,代码来源:helper.py

示例3: test_afterSubMult

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

示例4: test_noflattening

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

示例5: test_onBoolOp

# 需要导入模块: import ast [as 别名]
# 或者: from ast import Add [as 别名]
def test_onBoolOp(self):
        'Tests on BoolOp'

        expr_a = ast.BoolOp(ast.Add(), [ast.Num(1), ast.Num(2), ast.Num(3)])
        expr_b = ast.BoolOp(ast.Add(), [ast.Num(3), ast.Num(2), ast.Num(1)])
        self.assertTrue(asttools.Comparator().visit(expr_a, expr_b))

        expr_a = ast.BoolOp(ast.Add, [ast.Num(1), ast.BoolOp(ast.Mult(),
                                                             [ast.Num(5),
                                                              ast.Num(6)]),
                                      ast.Num(4)])
        expr_b = ast.BoolOp(ast.Add, [ast.BoolOp(ast.Mult(), [ast.Num(6),
                                                              ast.Num(5)]),
                                      ast.Num(4),
                                      ast.Num(1)])
        self.assertTrue(asttools.Comparator().visit(expr_a, expr_b)) 
开发者ID:quarkslab,项目名称:sspam,代码行数:18,代码来源:test_asttools.py

示例6: test_flattened

# 需要导入模块: import ast [as 别名]
# 或者: from ast import Add [as 别名]
def test_flattened(self):
        'Test positive matchings for flattened ast'
        pattern_string = "A + 2*B + 3*C"
        test_pos = ["x + 2*y + 3*z", "3*z + 2*y + x", "2*y + 3*z + x"]
        for input_string in test_pos:
            self.generic_test_positive(input_string, pattern_string, True)

        # actual pre-processing only flattens ADD nodes, but this test
        # is for code coverage
        test_neg = ast.parse("x ^ 2*y ^ 2*z")
        test_neg = pre_processing.all_preprocessings(ast.parse(test_neg))
        test_neg = Flattening().visit(test_neg)
        patt_ast = ast.parse(pattern_string)
        patt_ast = pre_processing.all_preprocessings(patt_ast)
        patt_ast = Flattening(ast.Add).visit(patt_ast)
        pat = pattern_matcher.PatternMatcher(test_neg)
        self.assertFalse(pat.visit(test_neg, patt_ast)) 
开发者ID:quarkslab,项目名称:sspam,代码行数:19,代码来源:test_pattern_matcher.py

示例7: visit_BoolOp

# 需要导入模块: import ast [as 别名]
# 或者: from ast import Add [as 别名]
def visit_BoolOp(self, node):
        'A custom BoolOp can be used in flattened AST'
        if type(node.op) not in (ast.Add, ast.Mult,
                                 ast.BitXor, ast.BitAnd, ast.BitOr):
            return self.generic_visit(node)
        # get constant parts of node:
        list_cste = [child for child in node.values
                     if isinstance(child, ast.Num)]
        if len(list_cste) < 2:
            return self.generic_visit(node)
        rest_values = [n for n in node.values if n not in list_cste]
        fake_node = Unflattening().visit(ast.BoolOp(node.op, list_cste))
        fake_node = ast.Expression(fake_node)
        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)
        rest_values.append(new_node)
        return ast.BoolOp(node.op, rest_values) 
开发者ID:quarkslab,项目名称:sspam,代码行数:24,代码来源:asttools.py

示例8: visit_BinOp

# 需要导入模块: import ast [as 别名]
# 或者: from ast import Add [as 别名]
def visit_BinOp(self, node1, node2):
        'Check type of operation and operands'
        if type(node1.op) != type(node2.op):
            return False

        # if operation is commutative, left and right operands are
        # interchangeable
        cond1 = (self.visit(node1.left, node2.left) and
                 self.visit(node1.right, node2.right))
        cond2 = (self.visit(node1.left, node2.right)
                 and self.visit(node1.right, node2.left))

        # non-commutative comparator
        if not self.commut:
            return cond1
        if isinstance(node1.op, (ast.Add, ast.Mult,
                                 ast.BitAnd, ast.BitOr, ast.BitXor)):
            if cond1 or cond2:
                return True
            else:
                return False
        else:
            if cond1:
                return True
        return False 
开发者ID:quarkslab,项目名称:sspam,代码行数:27,代码来源:asttools.py

示例9: test_increment_lineno

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

示例10: _add_global_parameter

# 需要导入模块: import ast [as 别名]
# 或者: from ast import Add [as 别名]
def _add_global_parameter(cls, openmm_object, parameter_name, parameter_value):
        """Add a new global parameter/variable to the OpenMM custom force/integrator.

        Parameters
        ----------
        openmm_object : object
            The OpenMM custom integrator/force to which add the parameter.
        parameter_name : str
            The name of the global parameter.
        parameter_value : float
            The value of the global parameter.

        """
        if cls._is_force(openmm_object):
            openmm_object.addGlobalParameter(parameter_name, parameter_value)
        else:
            openmm_object.addGlobalVariable(parameter_name, parameter_value) 
开发者ID:choderalab,项目名称:openmmtools,代码行数:19,代码来源:utils.py

示例11: test_create_mutant_with_cache

# 需要导入模块: import ast [as 别名]
# 或者: from ast import Add [as 别名]
def test_create_mutant_with_cache(binop_file, stdoutIO):
    """Change ast.Add to ast.Mult in a mutation including pycache changes."""
    genome = Genome(source_file=binop_file)

    # this target is the add_five() function, changing add to mult
    end_lineno = None if sys.version_info < (3, 8) else 10
    end_col_offset = None if sys.version_info < (3, 8) else 16

    target_idx = LocIndex(
        ast_class="BinOp",
        lineno=10,
        col_offset=11,
        op_type=ast.Add,
        end_lineno=end_lineno,
        end_col_offset=end_col_offset,
    )
    mutation_op = ast.Mult

    mutant = genome.mutate(target_idx, mutation_op, write_cache=True)

    # uses the redirection for stdout to capture the value from the final output of binop_file
    with stdoutIO() as s:
        exec(mutant.mutant_code)
        assert int(s.getvalue()) == 25

    tag = sys.implementation.cache_tag
    expected_cfile = binop_file.parent / "__pycache__" / ".".join([binop_file.stem, tag, "pyc"])

    assert mutant.src_file == binop_file
    assert mutant.cfile == expected_cfile
    assert mutant.src_idx == target_idx 
开发者ID:EvanKepner,项目名称:mutatest,代码行数:33,代码来源:test_api.py

示例12: mock_Mutant

# 需要导入模块: import ast [as 别名]
# 或者: from ast import Add [as 别名]
def mock_Mutant():
    """Mock mutant definition."""
    return Mutant(
        mutant_code=None,
        src_file=Path("src.py"),
        cfile=Path("__pycache__") / "src.pyc",
        loader=None,
        mode=1,
        source_stats={"mtime": 1, "size": 1},
        src_idx=LocIndex(ast_class="BinOp", lineno=1, col_offset=2, op_type=ast.Add),
        mutation=ast.Mult,
    ) 
开发者ID:EvanKepner,项目名称:mutatest,代码行数:14,代码来源:conftest.py

示例13: mock_LocIdx

# 需要导入模块: import ast [as 别名]
# 或者: from ast import Add [as 别名]
def mock_LocIdx():
    """Mock Single Location Index, not a valid target member of file."""
    return LocIndex(ast_class="BinOp", lineno=1, col_offset=2, op_type=ast.Add)


####################################################################################################
# TRANSFORMERS: BOOLOP FIXTURES
# This is a special case which has a tmp file with tests as a Python package to run the full pytest
# suite. These tests are marked with the 'slow' marker for easy filtering.
#################################################################################################### 
开发者ID:EvanKepner,项目名称:mutatest,代码行数:12,代码来源:conftest.py

示例14: test_MutateAST_visit_binop_37

# 需要导入模块: import ast [as 别名]
# 或者: from ast import Add [as 别名]
def test_MutateAST_visit_binop_37(binop_file):
    """Read only test to ensure locations are aggregated."""
    tree = Genome(binop_file).ast

    # Py 3.7 vs. Py 3.8
    end_lineno = None if sys.version_info < (3, 8) else 6
    end_col_offset = None if sys.version_info < (3, 8) else 17

    test_idx = LocIndex(
        ast_class="BinOp",
        lineno=6,
        col_offset=11,
        op_type=ast.Add,
        end_lineno=end_lineno,
        end_col_offset=end_col_offset,
    )
    test_mutation = ast.Pow

    # apply the mutation to the original tree copy
    testing_tree = deepcopy(tree)
    mutated_tree = MutateAST(target_idx=test_idx, 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) == 4

    # locs is an unordered set, cycle through to thd target and check the mutation
    for loc in mast.locs:
        if (
            loc.lineno == 6
            and loc.col_offset == 11
            and loc.end_lineno == end_lineno
            and loc.end_col_offset == end_col_offset
        ):
            assert loc.op_type == test_mutation 
开发者ID:EvanKepner,项目名称:mutatest,代码行数:40,代码来源:test_transformers.py

示例15: binop_Add_LocIdx

# 需要导入模块: import ast [as 别名]
# 或者: from ast import Add [as 别名]
def binop_Add_LocIdx():
    """Binop Add LocIdx as a target for mutations."""
    end_lineno = None if sys.version_info < (3, 8) else 10
    end_col_offset = None if sys.version_info < (3, 8) else 16
    return LocIndex(
        ast_class="BinOp",
        lineno=10,
        col_offset=11,
        op_type=ast.Add,
        end_lineno=end_lineno,
        end_col_offset=end_col_offset,
    ) 
开发者ID:EvanKepner,项目名称:mutatest,代码行数:14,代码来源:test_run.py


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