Python ast.Num() Examples
The following are 30
code examples of ast.Num().
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: setup.py From pypika with Apache License 2.0 | 8 votes |
def version(): path = 'pypika/__init__.py' with open(path, 'r') as file: t = compile(file.read(), path, 'exec', ast.PyCF_ONLY_AST) for node in (n for n in t.body if isinstance(n, ast.Assign)): if len(node.targets) == 1: name = node.targets[0] if isinstance(name, ast.Name) and \ name.id in ('__version__', '__version_info__', 'VERSION'): v = node.value if isinstance(v, ast.Str): return v.s if isinstance(v, ast.Tuple): r = [] for e in v.elts: if isinstance(e, ast.Str): r.append(e.s) elif isinstance(e, ast.Num): r.append(str(e.n)) return '.'.join(r)
Example #2
Source File: checker.py From linter-pylama with MIT License | 7 votes |
def convert_to_value(item): if isinstance(item, ast.Str): return item.s elif hasattr(ast, 'Bytes') and isinstance(item, ast.Bytes): return item.s elif isinstance(item, ast.Tuple): return tuple(convert_to_value(i) for i in item.elts) elif isinstance(item, ast.Num): return item.n elif isinstance(item, ast.Name): result = VariableKey(item=item) constants_lookup = { 'True': True, 'False': False, 'None': None, } return constants_lookup.get( result.name, result, ) elif (not PY2) and isinstance(item, ast.NameConstant): # None, True, False are nameconstants in python3, but names in 2 return item.value else: return UnhandledKeyType()
Example #3
Source File: inflect.py From pybids with MIT License | 7 votes |
def _get_value_from_ast(self, obj): """ Return the value of the ast object. """ if isinstance(obj, ast.Num): return obj.n elif isinstance(obj, ast.Str): return obj.s elif isinstance(obj, ast.List): return [self._get_value_from_ast(e) for e in obj.elts] elif isinstance(obj, ast.Tuple): return tuple([self._get_value_from_ast(e) for e in obj.elts]) # None, True and False are NameConstants in Py3.4 and above. elif sys.version_info.major >= 3 and isinstance(obj, ast.NameConstant): return obj.value # For python versions below 3.4 elif isinstance(obj, ast.Name) and (obj.id in ["True", "False", "None"]): return string_to_constant[obj.id] # Probably passed a variable name. # Or passed a single word without wrapping it in quotes as an argument # ex: p.inflect("I plural(see)") instead of p.inflect("I plural('see')") raise NameError("name '%s' is not defined" % obj.id)
Example #4
Source File: test_asttools.py From sspam with BSD 3-Clause "New" or "Revised" License | 6 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 #5
Source File: topython.py From pyrser with GNU General Public License v3.0 | 6 votes |
def visit_Hook(self, node: parsing.Hook) -> ast.expr: """Generates python code calling a hook. self.evalHook('hookname', self.ruleNodes[-1]) """ return ast.Call( ast.Attribute( ast.Name('self', ast.Load()), 'evalHook', ast.Load()), [ ast.Str(node.name), ast.Subscript( ast.Attribute( ast.Name('self', ast.Load()), 'ruleNodes', ast.Load()), ast.Index(ast.UnaryOp(ast.USub(), ast.Num(1))), ast.Load())], [], None, None)
Example #6
Source File: pyupgrade.py From pyupgrade with MIT License | 6 votes |
def _compare_to_3( test: ast.Compare, op: Union[Type[ast.cmpop], Tuple[Type[ast.cmpop], ...]], ) -> bool: if not ( isinstance(test.ops[0], op) and isinstance(test.comparators[0], ast.Tuple) and len(test.comparators[0].elts) >= 1 and all(isinstance(n, ast.Num) for n in test.comparators[0].elts) ): return False # checked above but mypy needs help elts = cast('List[ast.Num]', test.comparators[0].elts) return elts[0].n == 3 and all(n.n == 0 for n in elts[1:])
Example #7
Source File: pattern_matcher.py From sspam with BSD 3-Clause "New" or "Revised" License | 6 votes |
def check_not(self, target, pattern): 'Check NOT pattern node that could be in another form' if self.is_wildcard(pattern.operand): wkey = pattern.operand.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.operand.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.UnaryOp(ast.Invert(), target) return True return self.check_eq_z3(target, pattern) else: subpattern = pattern.operand newtarget = ast.UnaryOp(ast.Invert(), target) return self.check_eq_z3(newtarget, subpattern)
Example #8
Source File: pattern_matcher.py From sspam with BSD 3-Clause "New" or "Revised" License | 6 votes |
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)
Example #9
Source File: pre_processing.py From sspam with BSD 3-Clause "New" or "Revised" License | 6 votes |
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
Example #10
Source File: _ast_to_ir2.py From tmppy with Apache License 2.0 | 6 votes |
def number_literal_expression_ast_to_ir2(ast_node: ast.Num, compilation_context: CompilationContext, in_match_pattern: bool, check_var_reference: Callable[[ast.Name], None], match_lambda_argument_names: Set[str], positive: bool): n = ast_node.n if isinstance(n, float): raise CompilationError(compilation_context, ast_node, 'Floating-point values are not supported.') if isinstance(n, complex): raise CompilationError(compilation_context, ast_node, 'Complex values are not supported.') assert isinstance(n, int) if not positive: n = -n if n <= -2**63: raise CompilationError(compilation_context, ast_node, 'int value out of bounds: values lower than -2^63+1 are not supported.') if n >= 2**63: raise CompilationError(compilation_context, ast_node, 'int value out of bounds: values greater than 2^63-1 are not supported.') return ir2.IntLiteral(value=n)
Example #11
Source File: test_ast.py From ironpython2 with Apache License 2.0 | 6 votes |
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()
Example #12
Source File: _toVHDL.py From myhdl with GNU Lesser General Public License v2.1 | 6 votes |
def visit_UnaryOp(self, node): # in python3 a negative Num is represented as an USub of a positive Num # Fix: restore python2 behavior by a shortcut: invert value of Num, inherit # vhdl type from UnaryOp node, and visit the modified operand if isinstance(node.op, ast.USub) and isinstance(node.operand, ast.Num): node.operand.n = -node.operand.n node.operand.vhd = node.vhd self.visit(node.operand) return pre, suf = self.inferCast(node.vhd, node.vhdOri) self.write(pre) self.write("(") self.write(opmap[type(node.op)]) self.visit(node.operand) self.write(")") self.write(suf)
Example #13
Source File: asttools.py From sspam with BSD 3-Clause "New" or "Revised" License | 6 votes |
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)
Example #14
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 #15
Source File: asttools.py From sspam with BSD 3-Clause "New" or "Revised" License | 6 votes |
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)
Example #16
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 #17
Source File: math.py From pajbot with MIT License | 5 votes |
def eval_(node): if isinstance(node, ast.Num): # <number> return node.n elif isinstance(node, ast.BinOp): # <left> <operator> <right> return PBMath.operators[type(node.op)](PBMath.eval_(node.left), PBMath.eval_(node.right)) elif isinstance(node, ast.UnaryOp): # <operator> <operand> e.g., -1 return PBMath.operators[type(node.op)](PBMath.eval_(node.operand)) else: raise TypeError(node)
Example #18
Source File: test_ast.py From ironpython2 with Apache License 2.0 | 5 votes |
def test_docexample(self): # used to fail on ironpython for various reason node = ast.UnaryOp(ast.USub(), ast.Num(5, lineno=0, col_offset=0), lineno=0, col_offset=0) # the same with zero argument constructors node = ast.UnaryOp() node.op = ast.USub() node.operand = ast.Num() node.operand.n = 5 node.operand.lineno = 0 node.operand.col_offset = 0 node.lineno = 0 node.col_offset = 0
Example #19
Source File: test_ast.py From BinderFilter with MIT License | 5 votes |
def test_module(self): body = [ast.Num(42)] x = ast.Module(body) self.assertEqual(x.body, body)
Example #20
Source File: test_ast.py From ironpython2 with Apache License 2.0 | 5 votes |
def test_classattrs(self): x = ast.Num() self.assertEqual(x._fields, ('n',)) with self.assertRaises(AttributeError): x.n x = ast.Num(42) self.assertEqual(x.n, 42) with self.assertRaises(AttributeError): x.lineno with self.assertRaises(AttributeError): x.foobar x = ast.Num(lineno=2) self.assertEqual(x.lineno, 2) x = ast.Num(42, lineno=0) self.assertEqual(x.lineno, 0) self.assertEqual(x._fields, ('n',)) self.assertEqual(x.n, 42) self.assertRaises(TypeError, ast.Num, 1, 2) self.assertRaises(TypeError, ast.Num, 1, 2, lineno=0)
Example #21
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 #22
Source File: test_ast.py From oss-ftp with MIT License | 5 votes |
def test_field_attr_writable(self): x = ast.Num() # We can assign to _fields x._fields = 666 self.assertEqual(x._fields, 666)
Example #23
Source File: test_ast.py From BinderFilter with MIT License | 5 votes |
def test_classattrs(self): x = ast.Num() self.assertEqual(x._fields, ('n',)) with self.assertRaises(AttributeError): x.n x = ast.Num(42) self.assertEqual(x.n, 42) with self.assertRaises(AttributeError): x.lineno with self.assertRaises(AttributeError): x.foobar x = ast.Num(lineno=2) self.assertEqual(x.lineno, 2) x = ast.Num(42, lineno=0) self.assertEqual(x.lineno, 0) self.assertEqual(x._fields, ('n',)) self.assertEqual(x.n, 42) self.assertRaises(TypeError, ast.Num, 1, 2) self.assertRaises(TypeError, ast.Num, 1, 2, lineno=0)
Example #24
Source File: test_ast.py From ironpython2 with Apache License 2.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))' )
Example #25
Source File: test_ast.py From ironpython2 with Apache License 2.0 | 5 votes |
def test_module(self): body = [ast.Num(42)] x = ast.Module(body) self.assertEqual(x.body, body)
Example #26
Source File: test_ast.py From ironpython2 with Apache License 2.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))' )
Example #27
Source File: test_ast.py From ironpython2 with Apache License 2.0 | 5 votes |
def test_field_attr_writable(self): x = ast.Num() # We can assign to _fields x._fields = 666 self.assertEqual(x._fields, 666)
Example #28
Source File: rewrite.py From python-netsurv with MIT License | 5 votes |
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)
Example #29
Source File: rewrite.py From python-netsurv with MIT License | 5 votes |
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)
Example #30
Source File: cfscrape_solver.py From bugatsinho.github.io with GNU General Public License v3.0 | 5 votes |
def eval_(node): if isinstance(node, ast.Num): # <number> return node.n elif isinstance(node, ast.BinOp): # <left> <operator> <right> return operators[type(node.op)](eval_(node.left), eval_(node.right)) elif isinstance(node, ast.UnaryOp): # <operator> <operand> e.g., -1 return operators[type(node.op)](eval_(node.operand)) else: raise TypeError(node)