我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用ast.expr()。
def _collect_comprehension_children(self, node): # type: (ComprehensionNode) -> List[ast.expr] if isinstance(node, ast.DictComp): # dict comprehensions have two values to be checked child_nodes = [node.key, node.value] else: child_nodes = [node.elt] if node.generators: first_generator = node.generators[0] child_nodes.append(first_generator.target) for if_expr in first_generator.ifs: child_nodes.append(if_expr) for generator in node.generators[1:]: # rest need to be visited in the child scope child_nodes.append(generator.iter) child_nodes.append(generator.target) for if_expr in generator.ifs: child_nodes.append(if_expr) return child_nodes
def test_call(self): func = ast.Name("x", ast.Load()) args = [ast.Name("y", ast.Load())] keywords = [ast.keyword("w", ast.Name("z", ast.Load()))] stararg = ast.Name("p", ast.Load()) kwarg = ast.Name("q", ast.Load()) call = ast.Call(ast.Name("x", ast.Store()), args, keywords, stararg, kwarg) self.expr(call, "must have Load context") call = ast.Call(func, [None], keywords, stararg, kwarg) self.expr(call, "None disallowed") bad_keywords = [ast.keyword("w", ast.Name("z", ast.Store()))] call = ast.Call(func, args, bad_keywords, stararg, kwarg) self.expr(call, "must have Load context") call = ast.Call(func, args, keywords, ast.Name("z", ast.Store()), kwarg) self.expr(call, "must have Load context") call = ast.Call(func, args, keywords, stararg, ast.Name("w", ast.Store())) self.expr(call, "must have Load context")
def test_subscript(self): sub = ast.Subscript(ast.Name("x", ast.Store()), ast.Index(ast.Num(3)), ast.Load()) self.expr(sub, "must have Load context") x = ast.Name("x", ast.Load()) sub = ast.Subscript(x, ast.Index(ast.Name("y", ast.Store())), ast.Load()) self.expr(sub, "must have Load context") s = ast.Name("x", ast.Store()) for args in (s, None, None), (None, s, None), (None, None, s): sl = ast.Slice(*args) self.expr(ast.Subscript(x, sl, ast.Load()), "must have Load context") sl = ast.ExtSlice([]) self.expr(ast.Subscript(x, sl, ast.Load()), "empty dims on ExtSlice") sl = ast.ExtSlice([ast.Index(s)]) self.expr(ast.Subscript(x, sl, ast.Load()), "must have Load context")
def _translate_rules(ctx, rules, scrutinee_trans): for (pat, branch) in rules: (condition, binding_translations) = ctx.translate_pat( pat, scrutinee_trans) if not pat.bindings.keys() == binding_translations.keys(): raise typy.TypyExtensionError( "All bindings must have translations.") for binding_translation in binding_translations.itervalues(): if not isinstance(binding_translation, ast.expr): raise typy.TypyExtensionError( "Binding translation must be an expression.") ctx_update = pat.ctx_update ctx.variables.push(ctx_update) branch_translation = ctx.translate(branch) ctx.variables.pop() yield (condition, binding_translations, ctx_update, branch_translation)
def _is_ast_expr(node): return isinstance(node, ast.expr)
def visit_Expr(self, expr): return self.visit(expr.value)
def assign(self, expr): """Give *expr* a name.""" name = self.variable() self.statements.append(ast.Assign([ast.Name(name, ast.Store())], expr)) return ast.Name(name, ast.Load())
def display(self, expr): """Call py.io.saferepr on the expression.""" return self.helper("saferepr", expr)
def generic_visit(self, node): """Handle expressions we don't have custom code for.""" assert isinstance(node, ast.expr) res = self.assign(node) return res, self.explanation_param(self.display(res))
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)
def _assertTrueorder(self, ast_node, parent_pos): if not isinstance(ast_node, ast.AST) or ast_node._fields is None: return if isinstance(ast_node, (ast.expr, ast.stmt, ast.excepthandler)): node_pos = (ast_node.lineno, ast_node.col_offset) self.assertTrue(node_pos >= parent_pos) parent_pos = (ast_node.lineno, ast_node.col_offset) for name in ast_node._fields: value = getattr(ast_node, name) if isinstance(value, list): for child in value: self._assertTrueorder(child, parent_pos) elif value is not None: self._assertTrueorder(value, parent_pos)
def test_base_classes(self): self.assertTrue(issubclass(ast.For, ast.stmt)) self.assertTrue(issubclass(ast.Name, ast.expr)) self.assertTrue(issubclass(ast.stmt, ast.AST)) self.assertTrue(issubclass(ast.expr, ast.AST)) self.assertTrue(issubclass(ast.comprehension, ast.AST)) self.assertTrue(issubclass(ast.Gt, ast.AST))
def test_invalid_sum(self): pos = dict(lineno=2, col_offset=3) m = ast.Module([ast.Expr(ast.expr(**pos), **pos)]) with self.assertRaises(TypeError) as cm: compile(m, "<test>", "exec") if support.check_impl_detail(): self.assertIn("but got <_ast.expr", str(cm.exception))
def iter_method_classes(parent, call_node, context, child=None): import_aliases = context._context['import_aliases'] if not isinstance(call_node, ast.Call): raise ValueError('call_node must be of type ast.Call') if not isinstance(call_node.func, ast.Attribute): raise ValueError('call_node must be an attribute') for init_node in iter_expr_values(parent, call_node.func.value, call_node): # the init_node is the one in which the class is initialized # all expr nodes should be either call (Name or Attribute) or Name if not isinstance(init_node, ast.Call): continue if isinstance(init_node.func, ast.Attribute): klass_name = get_attribute_name(init_node.func) if klass_name is None: continue module_name, klass_name = klass_name.rsplit('.', 1) for def_node in get_definition_nodes(parent, init_node.func.value, child=init_node): if isinstance(def_node, (ast.Import, ast.ImportFrom)): yield import_aliases.get(module_name, module_name) + '.' + klass_name elif isinstance(init_node.func, ast.Name): if init_node.func.id in import_aliases: yield import_aliases[init_node.func.id] continue for klass_node in iter_expr_values(parent, init_node.func): if isinstance(klass_node, ast.Attribute): yield get_attribute_name(klass_node, import_aliases)
def node_is_child_of_parent_expr(parent, child): for cursor_node in ast.iter_child_nodes(parent): if cursor_node == child or (isinstance(cursor_node, ast.expr) and node_is_child_of_parent_expr(cursor_node, child)): return True return False
def test_size_ellipsis(): example = """ class Foo: bar[1:2, ...] """ if sys.version_info < (3, 0): check_size(example, 2) else: # ast.Ellipsis is a subclass of ast.expr in Python 3. check_size(example, 3)
def test_invalid_sum(self): pos = dict(lineno=2, col_offset=3) m = ast.Module([ast.Expr(ast.expr(**pos), **pos)]) with self.assertRaises(TypeError) as cm: compile(m, "<test>", "exec") self.assertIn("but got <_ast.expr", str(cm.exception))
def expr(self, node, msg=None, *, exc=ValueError): mod = ast.Module([ast.Expr(node)]) self.mod(mod, msg, exc=exc)
def test_boolop(self): b = ast.BoolOp(ast.And(), []) self.expr(b, "less than 2 values") b = ast.BoolOp(ast.And(), [ast.Num(3)]) self.expr(b, "less than 2 values") b = ast.BoolOp(ast.And(), [ast.Num(4), None]) self.expr(b, "None disallowed") b = ast.BoolOp(ast.And(), [ast.Num(4), ast.Name("x", ast.Store())]) self.expr(b, "must have Load context")
def test_lambda(self): a = ast.arguments([], None, None, [], None, None, [], []) self.expr(ast.Lambda(a, ast.Name("x", ast.Store())), "must have Load context") def fac(args): return ast.Lambda(args, ast.Name("x", ast.Load())) self._check_arguments(fac, self.expr)
def test_ifexp(self): l = ast.Name("x", ast.Load()) s = ast.Name("y", ast.Store()) for args in (s, l, l), (l, s, l), (l, l, s): self.expr(ast.IfExp(*args), "must have Load context")
def test_dict(self): d = ast.Dict([], [ast.Name("x", ast.Load())]) self.expr(d, "same number of keys as values") d = ast.Dict([None], [ast.Name("x", ast.Load())]) self.expr(d, "None disallowed") d = ast.Dict([ast.Name("x", ast.Load())], [None]) self.expr(d, "None disallowed")
def test_set(self): self.expr(ast.Set([None]), "None disallowed") s = ast.Set([ast.Name("x", ast.Store())]) self.expr(s, "must have Load context")
def _check_comprehension(self, fac): self.expr(fac([]), "comprehension with no generators") g = ast.comprehension(ast.Name("x", ast.Load()), ast.Name("x", ast.Load()), []) self.expr(fac([g]), "must have Store context") g = ast.comprehension(ast.Name("x", ast.Store()), ast.Name("x", ast.Store()), []) self.expr(fac([g]), "must have Load context") x = ast.Name("x", ast.Store()) y = ast.Name("y", ast.Load()) g = ast.comprehension(x, y, [None]) self.expr(fac([g]), "None disallowed") g = ast.comprehension(x, y, [ast.Name("x", ast.Store())]) self.expr(fac([g]), "must have Load context")
def test_dictcomp(self): g = ast.comprehension(ast.Name("y", ast.Store()), ast.Name("p", ast.Load()), []) c = ast.DictComp(ast.Name("x", ast.Store()), ast.Name("y", ast.Load()), [g]) self.expr(c, "must have Load context") c = ast.DictComp(ast.Name("x", ast.Load()), ast.Name("y", ast.Store()), [g]) self.expr(c, "must have Load context") def factory(comps): k = ast.Name("x", ast.Load()) v = ast.Name("y", ast.Load()) return ast.DictComp(k, v, comps) self._check_comprehension(factory)
def test_yield(self): self.expr(ast.Yield(ast.Name("x", ast.Store())), "must have Load") self.expr(ast.YieldFrom(ast.Name("x", ast.Store())), "must have Load")
def test_compare(self): left = ast.Name("x", ast.Load()) comp = ast.Compare(left, [ast.In()], []) self.expr(comp, "no comparators") comp = ast.Compare(left, [ast.In()], [ast.Num(4), ast.Num(5)]) self.expr(comp, "different number of comparators and operands") comp = ast.Compare(ast.Num("blah"), [ast.In()], [left]) self.expr(comp, "non-numeric", exc=TypeError) comp = ast.Compare(left, [ast.In()], [ast.Num("blah")]) self.expr(comp, "non-numeric", exc=TypeError)
def test_num(self): class subint(int): pass class subfloat(float): pass class subcomplex(complex): pass for obj in "0", "hello", subint(), subfloat(), subcomplex(): self.expr(ast.Num(obj), "non-numeric", exc=TypeError)
def _sequence(self, fac): self.expr(fac([None], ast.Load()), "None disallowed") self.expr(fac([ast.Name("x", ast.Store())], ast.Load()), "must have Load context")