ast

ast - 抽象语法树

2.5版本中的新功能:_ast仅包含节点类的低级模块。

2.6版新增功能:ast包含所有帮助程序的高级模块。

源代码: Lib / ast.py

ast模块帮助Python应用程序处理Python抽象语法语法的树。抽象语法本身可能随着每个Python版本而改变; 这个模块有助于以编程方式找出当前语法的样子。

抽象语法树可以通过ast.PyCF_ONLY_AST作为标志传递给compile()内置函数或使用parse()本模块中提供的帮助程序来生成。结果将是类的所有继承对象的树ast.AST。可以使用内置compile()函数将抽象语法树编译为Python代码对象。

1.节点类

class ast.AST

这是所有AST节点类的基础。实际的节点类是从该Parser/Python.asdl文件派生的,该文件在下面再现。它们在_astC模块中定义并重新导出ast

在抽象语法中为每个左侧符号定义了一个类(例如,ast.stmtast.expr)。另外,右边的每个构造函数都有一个类定义; 这些类继承了左侧树的类。例如,ast.BinOp继承自ast.expr。对于带有替代选项(又名“和”)的生产规则,左侧类是抽象的:只创建特定构造函数节点的实例。

_fields

每个具体类都有一个_fields给出所有子节点名称的属性。

具体类的每个实例对于每个子节点都有一个属性,类型在语法中定义。例如,ast.BinOp实例具有left类型的属性ast.expr

如果这些属性在语法中标记为可选(使用问号),则值可能为None。如果这些属性可以有零个或多个值(用星号标记),则这些值表示为Python列表。在编译AST时,所有可能的属性都必须存在且具有有效值compile()

linenocol_offset

实例ast.exprast.stmt亚类linenocol_offset属性。这lineno是源文本的行数(1-索引,所以第一行是第一行),并且col_offset是生成该节点的第一个令牌的UTF-8字节偏移量。记录UTF-8偏移是因为解析器在内部使用UTF-8。

类的构造函数ast.T解析其参数如下:

  • 如果有位置参数,则必须有多少项目T._fields; 他们将被分配为这些名称的属性。

  • 如果有关键字参数,他们会将相同名称的属性设置为给定值。

例如,要创建并填充ast.UnaryOp节点,可以使用

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

或更紧凑

node = ast.UnaryOp(ast.USub(), ast.Num(5, lineno=0, col_offset=0), lineno=0, col_offset=0)

2.6版新增功能:添加了上面解释的构造函数。在Python 2.5中,必须通过调用没有参数的类构造函数并在之后设置属性来创建节点。

2.抽象语法

该模块定义了一个字符串常量__version__,它是下面显示的文件的十进制Subversion修订号。

抽象语法目前定义如下:

-- ASDL's five builtin types are identifier, int, string, object, bool module Python version "$Revision$" { mod = Module(stmt* body) | Interactive(stmt* body) | Expression(expr body) -- not really an actual node but useful in Jython's typesystem. | Suite(stmt* body) stmt = FunctionDef(identifier name, arguments args, stmt* body, expr* decorator_list) | ClassDef(identifier name, expr* bases, stmt* body, expr* decorator_list) | Return(expr? value) | Delete(expr* targets) | Assign(expr* targets, expr value) | AugAssign(expr target, operator op, expr value) -- not sure if bool is allowed, can always use int | Print(expr? dest, expr* values, bool nl) -- use 'orelse' because else is a keyword in target languages | For(expr target, expr iter, stmt* body, stmt* orelse) | While(expr test, stmt* body, stmt* orelse) | If(expr test, stmt* body, stmt* orelse) | With(expr context_expr, expr? optional_vars, stmt* body) -- 'type' is a bad name | Raise(expr? type, expr? inst, expr? tback) | TryExcept(stmt* body, excepthandler* handlers, stmt* orelse) | TryFinally(stmt* body, stmt* finalbody) | Assert(expr test, expr? msg) | Import(alias* names) | ImportFrom(identifier? module, alias* names, int? level) -- Doesn't capture requirement that locals must be -- defined if globals is -- still supports use as a function! | Exec(expr body, expr? globals, expr? locals) | Global(identifier* names) | Expr(expr value) | Pass | Break | Continue -- XXX Jython will be different -- col_offset is the byte offset in the utf8 string the parser uses attributes (int lineno, int col_offset) -- BoolOp() can use left & right? expr = BoolOp(boolop op, expr* values) | BinOp(expr left, operator op, expr right) | UnaryOp(unaryop op, expr operand) | Lambda(arguments args, expr body) | IfExp(expr test, expr body, expr orelse) | Dict(expr* keys, expr* values) | Set(expr* elts) | ListComp(expr elt, comprehension* generators) | SetComp(expr elt, comprehension* generators) | DictComp(expr key, expr value, comprehension* generators) | GeneratorExp(expr elt, comprehension* generators) -- the grammar constrains where yield expressions can occur | Yield(expr? value) -- need sequences for compare to distinguish between -- x < 4 < 3 and (x < 4) < 3 | Compare(expr left, cmpop* ops, expr* comparators) | Call(expr func, expr* args, keyword* keywords, expr? starargs, expr? kwargs) | Repr(expr value) | Num(object n) -- a number as a PyObject. | Str(string s) -- need to specify raw, unicode, etc? -- other literals? bools? -- the following expression can appear in assignment context | Attribute(expr value, identifier attr, expr_context ctx) | Subscript(expr value, slice slice, expr_context ctx) | Name(identifier id, expr_context ctx) | List(expr* elts, expr_context ctx) | Tuple(expr* elts, expr_context ctx) -- col_offset is the byte offset in the utf8 string the parser uses attributes (int lineno, int col_offset) expr_context = Load | Store | Del | AugLoad | AugStore | Param slice = Ellipsis | Slice(expr? lower, expr? upper, expr? step) | ExtSlice(slice* dims) | Index(expr value) boolop = And | Or operator = Add | Sub | Mult | Div | Mod | Pow | LShift | RShift | BitOr | BitXor | BitAnd | FloorDiv unaryop = Invert | Not | UAdd | USub cmpop = Eq | NotEq | Lt | LtE | Gt | GtE | Is | IsNot | In | NotIn comprehension = (expr target, expr iter, expr* ifs) -- not sure what to call the first argument for raise and except excepthandler = ExceptHandler(expr? type, expr? name, stmt* body) attributes (int lineno, int col_offset) arguments = (expr* args, identifier? vararg, identifier? kwarg, expr* defaults) -- keyword arguments supplied to call keyword = (identifier arg, expr value) -- import name with optional 'as' alias. alias = (identifier name, identifier? asname) }

3.ast 助手

2.6版本中的新功能。

除了节点类,ast模块定义了遍历抽象语法树的这些实用函数和类:

ast.parse(source, filename='<unknown>', mode='exec')

将源解析为AST节点。相当于compile(source, filename, mode, ast.PyCF_ONLY_AST)

ast.literal_eval(node_or_string)

安全地评估包含Python文字或容器显示的表达式节点或Unicode或Latin-1编码的字符串。提供的字符串或节点可能只包含以下Python文字结构:字符串,数字,元组,列表,字典,布尔值和None

这可用于安全地评估包含来自不受信任来源的Python值的字符串,而无需自行解析值。它不能评估任意复杂的表达式,例如涉及操作符或索引。

ast.get_docstring(node, clean=True)

返回给定的文档字符串节点(它必须是一个FunctionDefClassDefModule节点),或None如果它没有文档字符串。如果clean是真的,用清理docstring的缩进inspect.cleandoc()

ast.fix_missing_locations(node)

当你编译一个节点compile(),编译器期望lineno,并col_offset为支持他们的每一个节点的属性。填充生成的节点非常繁琐,所以这个助手通过将这些属性设置为父节点的值来递增地添加这些属性。它从节点开始递归地工作。

ast.increment_lineno(node, n=1)

递增树中的每个节点的起始行号节点通过Ñ。这对于将代码移动到文件中的其他位置很有用。

ast.copy_location(new_node, old_node)

如果可能的话,将源位置(linenocol_offset)从old_node复制new_node,并返回new_node

ast.iter_fields(node)

(fieldname, value)节点node._fields上存在的每个字段生成一个元组。

ast.iter_child_nodes(node)

产生的所有直接子节点的节点,也就是在节点和在节点列表领域的所有项目的所有字段。

ast.walk(node)

节点(包括节点本身)的形式递归地产生树中的所有后代节点,并且没有指定顺序。如果你只想修改节点而不关心上下文,这很有用。

class ast.NodeVisitor

一个节点访问者基类,它遍历抽象语法树并为找到的每个节点调用访问者函数。该函数可能会返回该visit()方法转发的值。

这个类意图被子类化,子类添加访问者方法。

visit(node)

访问一个节点。 默认实现调用名为self.visit_classname的方法,其中classname是节点类的名称,如果该方法不存在,则调用generic_visit()。

generic_visit(node)

该访问者调用visit()该节点的所有子节点。

请注意,除非访问者generic_visit()自己调用或访问它们,否则不会访问具有自定义访问者方法的节点的子节点。

如果要在遍历期间将更改应用于节点,请勿使用NodeVisitor。 为此,存在一个允许修改的特殊访问者(NodeTransformer)。

class ast.NodeTransformer

一个NodeVisitor遍历抽象语法树并允许修改节点的子类。

NodeTransformer会走的AST,并使用访问者方法的返回值来替换或删除旧节点。如果visitor方法的返回值是None,则该节点将从其位置移除,否则将被替换为返回值。返回值可能是原始节点,在这种情况下不会发生替换。

下面是一个示例转换器,它将所有名称查找(foo)重写为data['foo']

class RewriteName(NodeTransformer): def visit_Name(self, node): return copy_location(Subscript( value=Name(id='data', ctx=Load()), slice=Index(value=Str(s=node.id)), ctx=node.ctx ), node)

请记住,如果您正在操作的节点具有子节点,则必须自己变换子节点或首先调用节点的generic_visit()方法。

对于作为语句集合(适用于所有语句节点)的一部分的节点,访问者也可以返回节点列表,而不仅仅是单个节点。

通常你使用这样的变压器:

node = YourTransformer().visit(node)

ast.dump(node, annotate_fields=True, include_attributes=False)

返回节点中 树的格式化转储。这主要用于调试目的。返回的字符串将显示字段的名称和值。这使代码无法评估,因此如果需要评估,必须将annotate_fields设置为False。行号和列偏移等属性默认不会被转储。如果需要,可以将include_attributes设置为True