ast —- 抽象语法树

源代码:Lib/ast.py


ast 模块帮助 Python 程序处理 Python 语法的抽象语法树。抽象语法或许会随着 Python 的更新发布而改变;该模块能够帮助理解当前语法在编程层面的样貌。

抽象语法树可通过将 ast.PyCF_ONLY_AST 作为旗标传递给 compile() 内置函数来生成,或是使用此模块中提供的 parse() 辅助函数。返回结果将是一个对象树,,其中的类都继承自 ast.AST。抽象语法树可被内置的 compile() 函数编译为一个 Python 代码对象。

节点类

  • class ast.AST
  • 这是所有 AST 节点类的基类。实际上,这些节点类派生自 Parser/Python.asdl 文件,其中定义的语法树示例 如下。它们在 C 语言模块 _ast 中定义,并被导出至 ast 模块。

抽象语法定义的每个左侧符号(比方说, ast.stmt 或者 ast.expr)定义了一个类。另外,在抽象语法定义的右侧,对每一个构造器也定义了一个类;这些类继承自树左侧的类。比如,ast.BinOp 继承自 ast.expr。对于多分支产生式(也就是"和规则"),树右侧的类是抽象的;只有特定构造器结点的实例能被构造。

  • _fields
  • 每个具体类都有个属性 _fields, 用来给出所有子节点的名字。

每个具体类的实例对它每个子节点都有一个属性,对应类型如文法中所定义。比如,ast.BinOp 的实例有个属性 left,类型是 ast.expr.

如果这些属性在文法中标记为可选(使用问号),对应值可能会是 None。如果这些属性有零或多个(用星号标记),对应值会用Python的列表来表示。所有可能的属性必须在用 compile() 编译得到AST时给出,且是有效的值。

  • lineno
  • col_offset
  • end_lineno
  • end_col_offset
  • Instances of ast.expr and ast.stmt subclasses havelineno, col_offset, lineno, and col_offsetattributes. The lineno and end_lineno are the first andlast line numbers of source text span (1-indexed so the first line is line 1)and the col_offset and end_col_offset are the correspondingUTF-8 byte offsets of the first and last tokens that generated the node.The UTF-8 offset is recorded because the parser uses UTF-8 internally.

Note that the end positions are not required by the compiler and aretherefore optional. The end offset is after the last symbol, for exampleone can get the source segment of a one-line expression node usingsource_line[node.col_offset : node.end_col_offset].

一个类的构造器 ast.T 像下面这样parse它的参数。

  • 如果有位置参数,它们必须和 T._fields 中的元素一样多;他们会像这些名字的属性一样被赋值。

  • 如果有关键字参数,它们必须被设为和给定值同名的属性。

比方说,要创建和填充节点 ast.UnaryOp,你得用

  1. node = ast.UnaryOp()
  2. node.op = ast.USub()
  3. node.operand = ast.Constant()
  4. node.operand.value = 5
  5. node.operand.lineno = 0
  6. node.operand.col_offset = 0
  7. node.lineno = 0
  8. node.col_offset = 0

或者更紧凑点

  1. node = ast.UnaryOp(ast.USub(), ast.Constant(5, lineno=0, col_offset=0),
  2. lineno=0, col_offset=0)

3.8 版后已移除: Class ast.Constant is now used for all constants. Old classesast.Num, ast.Str, ast.Bytes,ast.NameConstant and ast.Ellipsis are still available,but they will be removed in future Python releases.

抽象文法

抽象文法目前定义如下

  1. -- ASDL's 5 builtin types are:
  2. -- identifier, int, string, object, constant
  3.  
  4. module Python
  5. {
  6. mod = Module(stmt* body, type_ignore *type_ignores)
  7. | Interactive(stmt* body)
  8. | Expression(expr body)
  9. | FunctionType(expr* argtypes, expr returns)
  10.  
  11. -- not really an actual node but useful in Jython's typesystem.
  12. | Suite(stmt* body)
  13.  
  14. stmt = FunctionDef(identifier name, arguments args,
  15. stmt* body, expr* decorator_list, expr? returns,
  16. string? type_comment)
  17. | AsyncFunctionDef(identifier name, arguments args,
  18. stmt* body, expr* decorator_list, expr? returns,
  19. string? type_comment)
  20.  
  21. | ClassDef(identifier name,
  22. expr* bases,
  23. keyword* keywords,
  24. stmt* body,
  25. expr* decorator_list)
  26. | Return(expr? value)
  27.  
  28. | Delete(expr* targets)
  29. | Assign(expr* targets, expr value, string? type_comment)
  30. | AugAssign(expr target, operator op, expr value)
  31. -- 'simple' indicates that we annotate simple name without parens
  32. | AnnAssign(expr target, expr annotation, expr? value, int simple)
  33.  
  34. -- use 'orelse' because else is a keyword in target languages
  35. | For(expr target, expr iter, stmt* body, stmt* orelse, string? type_comment)
  36. | AsyncFor(expr target, expr iter, stmt* body, stmt* orelse, string? type_comment)
  37. | While(expr test, stmt* body, stmt* orelse)
  38. | If(expr test, stmt* body, stmt* orelse)
  39. | With(withitem* items, stmt* body, string? type_comment)
  40. | AsyncWith(withitem* items, stmt* body, string? type_comment)
  41.  
  42. | Raise(expr? exc, expr? cause)
  43. | Try(stmt* body, excepthandler* handlers, stmt* orelse, stmt* finalbody)
  44. | Assert(expr test, expr? msg)
  45.  
  46. | Import(alias* names)
  47. | ImportFrom(identifier? module, alias* names, int? level)
  48.  
  49. | Global(identifier* names)
  50. | Nonlocal(identifier* names)
  51. | Expr(expr value)
  52. | Pass | Break | Continue
  53.  
  54. -- XXX Jython will be different
  55. -- col_offset is the byte offset in the utf8 string the parser uses
  56. attributes (int lineno, int col_offset, int? end_lineno, int? end_col_offset)
  57.  
  58. -- BoolOp() can use left & right?
  59. expr = BoolOp(boolop op, expr* values)
  60. | NamedExpr(expr target, expr value)
  61. | BinOp(expr left, operator op, expr right)
  62. | UnaryOp(unaryop op, expr operand)
  63. | Lambda(arguments args, expr body)
  64. | IfExp(expr test, expr body, expr orelse)
  65. | Dict(expr* keys, expr* values)
  66. | Set(expr* elts)
  67. | ListComp(expr elt, comprehension* generators)
  68. | SetComp(expr elt, comprehension* generators)
  69. | DictComp(expr key, expr value, comprehension* generators)
  70. | GeneratorExp(expr elt, comprehension* generators)
  71. -- the grammar constrains where yield expressions can occur
  72. | Await(expr value)
  73. | Yield(expr? value)
  74. | YieldFrom(expr value)
  75. -- need sequences for compare to distinguish between
  76. -- x < 4 < 3 and (x < 4) < 3
  77. | Compare(expr left, cmpop* ops, expr* comparators)
  78. | Call(expr func, expr* args, keyword* keywords)
  79. | FormattedValue(expr value, int? conversion, expr? format_spec)
  80. | JoinedStr(expr* values)
  81. | Constant(constant value, string? kind)
  82.  
  83. -- the following expression can appear in assignment context
  84. | Attribute(expr value, identifier attr, expr_context ctx)
  85. | Subscript(expr value, slice slice, expr_context ctx)
  86. | Starred(expr value, expr_context ctx)
  87. | Name(identifier id, expr_context ctx)
  88. | List(expr* elts, expr_context ctx)
  89. | Tuple(expr* elts, expr_context ctx)
  90.  
  91. -- col_offset is the byte offset in the utf8 string the parser uses
  92. attributes (int lineno, int col_offset, int? end_lineno, int? end_col_offset)
  93.  
  94. expr_context = Load | Store | Del | AugLoad | AugStore | Param
  95.  
  96. slice = Slice(expr? lower, expr? upper, expr? step)
  97. | ExtSlice(slice* dims)
  98. | Index(expr value)
  99.  
  100. boolop = And | Or
  101.  
  102. operator = Add | Sub | Mult | MatMult | Div | Mod | Pow | LShift
  103. | RShift | BitOr | BitXor | BitAnd | FloorDiv
  104.  
  105. unaryop = Invert | Not | UAdd | USub
  106.  
  107. cmpop = Eq | NotEq | Lt | LtE | Gt | GtE | Is | IsNot | In | NotIn
  108.  
  109. comprehension = (expr target, expr iter, expr* ifs, int is_async)
  110.  
  111. excepthandler = ExceptHandler(expr? type, identifier? name, stmt* body)
  112. attributes (int lineno, int col_offset, int? end_lineno, int? end_col_offset)
  113.  
  114. arguments = (arg* posonlyargs, arg* args, arg? vararg, arg* kwonlyargs,
  115. expr* kw_defaults, arg? kwarg, expr* defaults)
  116.  
  117. arg = (identifier arg, expr? annotation, string? type_comment)
  118. attributes (int lineno, int col_offset, int? end_lineno, int? end_col_offset)
  119.  
  120. -- keyword arguments supplied to call (NULL identifier for **kwargs)
  121. keyword = (identifier? arg, expr value)
  122.  
  123. -- import name with optional 'as' alias.
  124. alias = (identifier name, identifier? asname)
  125.  
  126. withitem = (expr context_expr, expr? optional_vars)
  127.  
  128. type_ignore = TypeIgnore(int lineno, string tag)
  129. }

ast 中的辅助函数

除了节点类, ast 模块里为遍历抽象语法树定义了这些工具函数和类:

  • ast.parse(source, filename='', mode='exec', *, type_comments=False, feature_version=None)
  • 把源码解析为AST节点。和 compile(source, filename, mode,ast.PyCF_ONLY_AST) 等价。

If type_comments=True is given, the parser is modified to checkand return type comments as specified by PEP 484 and PEP 526.This is equivalent to adding ast.PyCF_TYPE_COMMENTS to theflags passed to compile(). This will report syntax errorsfor misplaced type comments. Without this flag, type comments willbe ignored, and the type_comment field on selected AST nodeswill always be None. In addition, the locations of # type:ignore comments will be returned as the type_ignoresattribute of Module (otherwise it is always an empty list).

In addition, if mode is 'func_type', the input syntax ismodified to correspond to PEP 484 "signature type comments",e.g. (str, int) -> List[str].

Also, setting feature_version to a tuple (major, minor)will attempt to parse using that Python version's grammar.Currently major must equal to 3. For example, settingfeature_version=(3, 4) will allow the use of async andawait as variable names. The lowest supported version is(3, 4); the highest is sys.version_info[0:2].

警告

足够复杂或是巨大的字符串可能导致Python解释器的崩溃,因为Python的AST编译器是有栈深限制的。

在 3.8 版更改: Added type_comments, mode='func_type' and feature_version.

  • ast.literaleval(_node_or_string)
  • 对表达式节点以及包含Python字面量或容器的字符串进行安全的求值。传入的字符串或者节点里可能只包含下列的Python字面量结构: 字符串,字节对象(bytes),数值,元组,列表,字典,集合,布尔值和 None

This can be used for safely evaluating strings containing Python values fromuntrusted sources without the need to parse the values oneself. It is notcapable of evaluating arbitrarily complex expressions, for example involvingoperators or indexing.

警告

足够复杂或是巨大的字符串可能导致Python解释器的崩溃,因为Python的AST编译器是有栈深限制的。

在 3.2 版更改: 目前支持字节和集合。

  • ast.getdocstring(_node, clean=True)
  • Return the docstring of the given node (which must be aFunctionDef, AsyncFunctionDef, ClassDef,or Module node), or None if it has no docstring.If clean is true, clean up the docstring's indentation withinspect.cleandoc().

在 3.5 版更改: 目前支持 AsyncFunctionDef

  • ast.getsource_segment(_source, node, *, padded=False)
  • Get source code segment of the source that generated node.If some location information (lineno, end_lineno,col_offset, or end_col_offset) is missing, return None.

If padded is True, the first line of a multi-line statement willbe padded with spaces to match its original position.

3.8 新版功能.

  • ast.fixmissing_locations(_node)
  • When you compile a node tree with compile(), the compiler expectslineno and coloffset attributes for every node that supportsthem. This is rather tedious to fill in for generated nodes, so this helperadds these attributes recursively where not already set, by setting them tothe values of the parent node. It works recursively starting at _node.

  • ast.incrementlineno(_node, n=1)

  • Increment the line number and end line number of each node in the treestarting at node by n. This is useful to "move code" to a differentlocation in a file.

  • ast.copylocation(_new_node, old_node)

  • Copy source location (lineno, coloffset, end_lineno,and end_col_offset) from _old_node to new_node if possible,and return new_node.

  • ast.iterfields(_node)

  • Yield a tuple of (fieldname, value) for each field in node.fieldsthat is present on _node.

  • ast.iterchild_nodes(_node)

  • Yield all direct child nodes of node, that is, all fields that are nodesand all items of fields that are lists of nodes.

  • ast.walk(node)

  • Recursively yield all descendant nodes in the tree starting at node(including node itself), in no specified order. This is useful if you onlywant to modify nodes in place and don't care about the context.

  • class ast.NodeVisitor

  • A node visitor base class that walks the abstract syntax tree and calls avisitor function for every node found. This function may return a valuewhich is forwarded by the visit() method.

This class is meant to be subclassed, with the subclass adding visitormethods.

  • visit(node)
  • Visit a node. The default implementation calls the method calledself.visitclassname where _classname is the name of the nodeclass, or generic_visit() if that method doesn't exist.

  • genericvisit(_node)

  • This visitor calls visit() on all children of the node.

Note that child nodes of nodes that have a custom visitor method won't bevisited unless the visitor calls generic_visit() or visits themitself.

Don't use the NodeVisitor if you want to apply changes to nodesduring traversal. For this a special visitor exists(NodeTransformer) that allows modifications.

3.8 版后已移除: Methods visit_Num(), visit_Str(), visit_Bytes(),visit_NameConstant() and visit_Ellipsis() are deprecatednow and will not be called in future Python versions. Add thevisit_Constant() method to handle all constant nodes.

  • class ast.NodeTransformer
  • 子类 NodeVisitor 用于遍历抽象语法树,并允许修改节点。

NodeTransformer 将遍历抽象语法树并使用visitor方法的返回值去替换或移除旧节点。如果visitor方法的返回值为 None , 则该节点将从其位置移除,否则将替换为返回值。当返回值是原始节点时,无需替换。

如下是一个转换器示例,它将所有出现的名称 (foo) 重写为 data['foo']:

  1. class RewriteName(NodeTransformer):
  2.  
  3. def visit_Name(self, node):
  4. return copy_location(Subscript(
  5. value=Name(id='data', ctx=Load()),
  6. slice=Index(value=Constant(value=node.id)),
  7. ctx=node.ctx
  8. ), node)

请记住,如果您正在操作的节点具有子节点,则必须先转换其子节点或为该节点调用 generic_visit() 方法。

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

通常你可以像这样使用转换器:

  1. node = YourTransformer().visit(node)
  • ast.dump(node, annotate_fields=True, include_attributes=False)
  • Return a formatted dump of the tree in node. This is mainly useful fordebugging purposes. If annotate_fields is true (by default),the returned string will show the names and the values for fields.If annotate_fields is false, the result string will be more compact byomitting unambiguous field names. Attributes such as linenumbers and column offsets are not dumped by default. If this is wanted,include_attributes can be set to true.

参见

Green Tree Snakes, an external documentation resource, has gooddetails on working with Python ASTs.