Python ast.Add() Examples
The following are 30
code examples of ast.Add().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
ast
, or try the search function
.
Example #1
Source File: test_asttools.py From sspam with BSD 3-Clause "New" or "Revised" License | 7 votes |
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))
Example #2
Source File: test_ast.py From ironpython2 with Apache License 2.0 | 6 votes |
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))' )
Example #3
Source File: _toVHDL.py From myhdl with GNU Lesser General Public License v2.1 | 6 votes |
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(";")
Example #4
Source File: test_ast.py From ironpython3 with Apache License 2.0 | 6 votes |
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))' )
Example #5
Source File: utils.py From openmmtools with MIT License | 6 votes |
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)
Example #6
Source File: helper.py From YAPyPy with MIT License | 6 votes |
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]
Example #7
Source File: test_flattening.py From sspam with BSD 3-Clause "New" or "Revised" License | 6 votes |
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))
Example #8
Source File: test_flattening.py From sspam with BSD 3-Clause "New" or "Revised" License | 6 votes |
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)
Example #9
Source File: test_ast.py From Fluid-Designer with GNU General Public License v3.0 | 6 votes |
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))' )
Example #10
Source File: test_pattern_matcher.py From sspam with BSD 3-Clause "New" or "Revised" License | 6 votes |
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))
Example #11
Source File: test_ast.py From oss-ftp with MIT License | 6 votes |
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))' )
Example #12
Source File: asttools.py From sspam with BSD 3-Clause "New" or "Revised" License | 6 votes |
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)
Example #13
Source File: asttools.py From sspam with BSD 3-Clause "New" or "Revised" License | 6 votes |
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
Example #14
Source File: test_ast.py From BinderFilter with MIT License | 6 votes |
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))' )
Example #15
Source File: test_ast.py From ironpython2 with Apache License 2.0 | 6 votes |
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))' )
Example #16
Source File: test_mock.py From rally-openstack with Apache License 2.0 | 5 votes |
def _get_value(self, node): """Get mock.patch string argument regexp. It is either a string (if we are lucky), string-format of ("%s.something" % GVAL) or (GVAL + ".something") """ val = None if isinstance(node, ast.Str): val = node.s elif isinstance(node, ast.BinOp): if pairwise_isinstance( (node.op, ast.Mod), (node.left, ast.Str), (node.right, ast.Name)): val = node.left.s % self.globals_[node.right.id] elif pairwise_isinstance( (node.op, ast.Add), (node.left, ast.Name), (node.right, ast.Str)): val = self.globals_[node.left.id] + node.right.s elif isinstance(node, ast.Name): val = self.globals_[node.id] if val is None: raise ValueError( "Unable to find value in %s, only the following are parsed: " "GLOBAL, 'pkg.foobar', '%%s.foobar' %% GLOBAL or 'GLOBAL + " "'.foobar'" % ast.dump(node)) return val
Example #17
Source File: parser.py From myia with MIT License | 5 votes |
def add_parameter(self, parameter=None): """Add a parameter to the graph.""" p = parameter or Parameter(self.graph) if self.use_universe: self.graph.parameters.insert(-1, p) else: self.graph.parameters.append(p) return p
Example #18
Source File: test_ast.py From oss-ftp with MIT License | 5 votes |
def test_copy_location(self): src = ast.parse('1 + 1', mode='eval') src.body.right = ast.copy_location(ast.Num(2), src.body.right) self.assertEqual(ast.dump(src, include_attributes=True), 'Expression(body=BinOp(left=Num(n=1, lineno=1, col_offset=0), ' 'op=Add(), right=Num(n=2, lineno=1, col_offset=4), lineno=1, ' 'col_offset=0))' )
Example #19
Source File: checks.py From compute-hyperv with Apache License 2.0 | 5 votes |
def visit_BinOp(self, node): if isinstance(node.op, ast.Add): if self._check_call_names(node.left, self.TRANS_FUNC): self.add_error(node.left) elif self._check_call_names(node.right, self.TRANS_FUNC): self.add_error(node.right) super(CheckForTransAdd, self).generic_visit(node)
Example #20
Source File: candidates.py From flynt with MIT License | 5 votes |
def is_string_concat(node): """ Returns True for nodes representing a string concatenation """ if is_str_literal(node): return True if isinstance(node, ast.BinOp) and isinstance(node.op, ast.Add): return is_string_concat(node.left) or is_string_concat(node.right) return False
Example #21
Source File: checks.py From compute-hyperv with Apache License 2.0 | 5 votes |
def add_error(self, node, message=None): """Add an error caused by a node to the list of errors for pep8.""" message = message or self.CHECK_DESC error = (node.lineno, node.col_offset, message, self.__class__) self._errors.append(error)
Example #22
Source File: source_visitor.py From vermin with MIT License | 5 votes |
def __add_member(self, member, line=None, col=None): """Add member if fully-qualified name is known.""" if member in self.__user_defs: self.__vvvvprint("Ignoring member '{}' because it's user-defined!".format(member)) return if self.__config.is_excluded(member): self.__vvprint("Excluding member: {}".format(member)) return if member in self.__mod_mem_reqs_rules: self.__members.append(member) self.__add_line_col(member, line, col)
Example #23
Source File: source_visitor.py From vermin with MIT License | 5 votes |
def __add_user_def_node(self, node): """Add user-defined name from node, like ast.Name, ast.arg or str.""" if isinstance(node, str): self.__add_user_def(node) if isinstance(node, ast.Name) and hasattr(node, "id"): self.__add_user_def(node.id) elif hasattr(node, "arg"): self.__add_user_def(node.arg)
Example #24
Source File: parser.py From vecpy with MIT License | 5 votes |
def binop(self, block, node, var=None): if var is None: var = self.add_variable(None) left = self.expression(block, node.left) right = self.expression(block, node.right) if isinstance(node.op, ast.Add): op = Operator.add elif isinstance(node.op, ast.Sub): op = Operator.subtract elif isinstance(node.op, ast.Mult): op = Operator.multiply elif isinstance(node.op, ast.Div): op = Operator.divide elif isinstance(node.op, ast.FloorDiv): op = Operator.divide_int elif isinstance(node.op, ast.Mod): op = Operator.mod elif isinstance(node.op, ast.Pow): op = Operator.pow elif isinstance(node.op, ast.BitAnd): op = Operator.bit_and elif isinstance(node.op, ast.BitOr): op = Operator.bit_or elif isinstance(node.op, ast.BitXor): op = Operator.bit_xor elif isinstance(node.op, ast.LShift): op = Operator.shift_left elif isinstance(node.op, ast.RShift): op = Operator.shift_right else: raise Exception('Unexpected BinOp (%s)'%(node.op.__class__)) operation = BinaryOperation(left, op, right) assignment = Assignment(var, operation) block.add(assignment) return var #Parses a unary uperation (AST UnaryOp)
Example #25
Source File: test_ast.py From BinderFilter with MIT License | 5 votes |
def test_copy_location(self): src = ast.parse('1 + 1', mode='eval') src.body.right = ast.copy_location(ast.Num(2), src.body.right) self.assertEqual(ast.dump(src, include_attributes=True), 'Expression(body=BinOp(left=Num(n=1, lineno=1, col_offset=0), ' 'op=Add(), right=Num(n=2, lineno=1, col_offset=4), lineno=1, ' 'col_offset=0))' )
Example #26
Source File: pyast64.py From pyast64 with MIT License | 5 votes |
def visit_For(self, node): # Turn for+range loop into a while loop: # i = start # while i < stop: # body # i = i + step assert isinstance(node.iter, ast.Call) and \ node.iter.func.id == 'range', \ 'for can only be used with range()' range_args = node.iter.args if len(range_args) == 1: start = ast.Num(n=0) stop = range_args[0] step = ast.Num(n=1) elif len(range_args) == 2: start, stop = range_args step = ast.Num(n=1) else: start, stop, step = range_args if (isinstance(step, ast.UnaryOp) and isinstance(step.op, ast.USub) and isinstance(step.operand, ast.Num)): # Handle negative step step = ast.Num(n=-step.operand.n) assert isinstance(step, ast.Num) and step.n != 0, \ 'range() step must be a nonzero integer constant' self.visit(ast.Assign(targets=[node.target], value=start)) test = ast.Compare( left=node.target, ops=[ast.Lt() if step.n > 0 else ast.Gt()], comparators=[stop], ) incr = ast.Assign( targets=[node.target], value=ast.BinOp(left=node.target, op=ast.Add(), right=step), ) self.visit(ast.While(test=test, body=node.body + [incr]))
Example #27
Source File: FileFormat.py From qiew with GNU General Public License v2.0 | 5 votes |
def onReturnPressed(self): expr = str(self.ui.lineEdit.text()) import ast import operator as op # supported operators operators = {ast.Add: op.add, ast.Sub: op.sub, ast.Mult: op.mul, ast.Div: op.floordiv, ast.Pow: op.pow, ast.USub: op.neg} def eval_expr(expr): return eval_(ast.parse(expr, mode='eval').body) def eval_(node): if isinstance(node, ast.Num): return node.n elif isinstance(node, ast.BinOp): return operators[type(node.op)](eval_(node.left), eval_(node.right)) elif isinstance(node, ast.UnaryOp): return operators[type(node.op)](eval_(node.operand)) elif isinstance(node, object): # handle constants k = str(node.id).upper() if k in self.konstants: return self.konstants[k](k) else: raise TypeError(node) else: raise TypeError(node) try: result = eval_expr(expr) except Exception as e: self.ui.label.setText('error.') return self.ui.label.setText('{0} ({1})'.format(hex(result), result)) self.onResult(result)
Example #28
Source File: parser.py From vecpy with MIT License | 5 votes |
def statement(self, block, stmt): #Add a comment self.add_comment(block, stmt) #Parse the statement try: if isinstance(stmt, ast.Assign): self.assign(block, stmt) elif isinstance(stmt, ast.Return): self.return_(block, stmt) elif isinstance(stmt, ast.Expr): self.docstring_(block, stmt) elif isinstance(stmt, ast.If): self.if_(block, stmt) elif isinstance(stmt, ast.While): self.while_(block, stmt) elif isinstance(stmt, ast.AugAssign): self.augassign(block, stmt) else: Parser._dump(stmt, 'Unexpected Statement') raise Exception('Unexpected Statement (%s)'%(stmt.__class__)) except: line = stmt.lineno src = self.source.split('\n')[line - 1].strip() print('Line %d: %s'%(line, src)) raise #=========================================================== # Public interface #=========================================================== #Parses the kernel using the specified live function
Example #29
Source File: test_ast.py From gcblue with BSD 3-Clause "New" or "Revised" License | 5 votes |
def test_copy_location(self): src = ast.parse('1 + 1', mode='eval') src.body.right = ast.copy_location(ast.Num(2), src.body.right) self.assertEqual(ast.dump(src, include_attributes=True), 'Expression(body=BinOp(left=Num(n=1, lineno=1, col_offset=0), ' 'op=Add(), right=Num(n=2, lineno=1, col_offset=4), lineno=1, ' 'col_offset=0))' )
Example #30
Source File: test_ast.py From Fluid-Designer with GNU General Public License v3.0 | 5 votes |
def test_copy_location(self): src = ast.parse('1 + 1', mode='eval') src.body.right = ast.copy_location(ast.Num(2), src.body.right) self.assertEqual(ast.dump(src, include_attributes=True), 'Expression(body=BinOp(left=Num(n=1, lineno=1, col_offset=0), ' 'op=Add(), right=Num(n=2, lineno=1, col_offset=4), lineno=1, ' 'col_offset=0))' )