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
  • ast.exprast.stmt 子类的实例有 linenocol_offset 属性。lineno 是源代码的行数(从1开始, 所以第一行行数是1),而 col_offset 是该生成节点第一个token的UTF-8字节偏移量。记录下UTF-8偏移量的原因是parser内部使用UTF-8。

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

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

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

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

  1. node = ast.UnaryOp()
  2. node.op = ast.USub()
  3. node.operand = ast.Num()
  4. node.operand.n = 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.Num(5, lineno=0, col_offset=0),
  2. lineno=0, col_offset=0)

抽象文法

抽象文法目前定义如下

  1. -- ASDL's 7 builtin types are:
  2. -- identifier, int, string, bytes, object, singleton, constant
  3. --
  4. -- singleton: None, True or False
  5. -- constant can be None, whereas None means "no value" for object.
  6.  
  7. module Python
  8. {
  9. mod = Module(stmt* body)
  10. | Interactive(stmt* body)
  11. | Expression(expr body)
  12.  
  13. -- not really an actual node but useful in Jython's typesystem.
  14. | Suite(stmt* body)
  15.  
  16. stmt = FunctionDef(identifier name, arguments args,
  17. stmt* body, expr* decorator_list, expr? returns)
  18. | AsyncFunctionDef(identifier name, arguments args,
  19. stmt* body, expr* decorator_list, expr? returns)
  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)
  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)
  36. | AsyncFor(expr target, expr iter, stmt* body, stmt* orelse)
  37. | While(expr test, stmt* body, stmt* orelse)
  38. | If(expr test, stmt* body, stmt* orelse)
  39. | With(withitem* items, stmt* body)
  40. | AsyncWith(withitem* items, stmt* body)
  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)
  57.  
  58. -- BoolOp() can use left & right?
  59. expr = BoolOp(boolop op, expr* values)
  60. | BinOp(expr left, operator op, expr right)
  61. | UnaryOp(unaryop op, expr operand)
  62. | Lambda(arguments args, expr body)
  63. | IfExp(expr test, expr body, expr orelse)
  64. | Dict(expr* keys, expr* values)
  65. | Set(expr* elts)
  66. | ListComp(expr elt, comprehension* generators)
  67. | SetComp(expr elt, comprehension* generators)
  68. | DictComp(expr key, expr value, comprehension* generators)
  69. | GeneratorExp(expr elt, comprehension* generators)
  70. -- the grammar constrains where yield expressions can occur
  71. | Await(expr value)
  72. | Yield(expr? value)
  73. | YieldFrom(expr value)
  74. -- need sequences for compare to distinguish between
  75. -- x < 4 < 3 and (x < 4) < 3
  76. | Compare(expr left, cmpop* ops, expr* comparators)
  77. | Call(expr func, expr* args, keyword* keywords)
  78. | Num(object n) -- a number as a PyObject.
  79. | Str(string s) -- need to specify raw, unicode, etc?
  80. | FormattedValue(expr value, int? conversion, expr? format_spec)
  81. | JoinedStr(expr* values)
  82. | Bytes(bytes s)
  83. | NameConstant(singleton value)
  84. | Ellipsis
  85. | Constant(constant value)
  86.  
  87. -- the following expression can appear in assignment context
  88. | Attribute(expr value, identifier attr, expr_context ctx)
  89. | Subscript(expr value, slice slice, expr_context ctx)
  90. | Starred(expr value, expr_context ctx)
  91. | Name(identifier id, expr_context ctx)
  92. | List(expr* elts, expr_context ctx)
  93. | Tuple(expr* elts, expr_context ctx)
  94.  
  95. -- col_offset is the byte offset in the utf8 string the parser uses
  96. attributes (int lineno, int col_offset)
  97.  
  98. expr_context = Load | Store | Del | AugLoad | AugStore | Param
  99.  
  100. slice = Slice(expr? lower, expr? upper, expr? step)
  101. | ExtSlice(slice* dims)
  102. | Index(expr value)
  103.  
  104. boolop = And | Or
  105.  
  106. operator = Add | Sub | Mult | MatMult | Div | Mod | Pow | LShift
  107. | RShift | BitOr | BitXor | BitAnd | FloorDiv
  108.  
  109. unaryop = Invert | Not | UAdd | USub
  110.  
  111. cmpop = Eq | NotEq | Lt | LtE | Gt | GtE | Is | IsNot | In | NotIn
  112.  
  113. comprehension = (expr target, expr iter, expr* ifs, int is_async)
  114.  
  115. excepthandler = ExceptHandler(expr? type, identifier? name, stmt* body)
  116. attributes (int lineno, int col_offset)
  117.  
  118. arguments = (arg* args, arg? vararg, arg* kwonlyargs, expr* kw_defaults,
  119. arg? kwarg, expr* defaults)
  120.  
  121. arg = (identifier arg, expr? annotation)
  122. attributes (int lineno, int col_offset)
  123.  
  124. -- keyword arguments supplied to call (NULL identifier for **kwargs)
  125. keyword = (identifier? arg, expr value)
  126.  
  127. -- import name with optional 'as' alias.
  128. alias = (identifier name, identifier? asname)
  129.  
  130. withitem = (expr context_expr, expr? optional_vars)
  131. }
  132.  

ast 中的辅助函数

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

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

警告

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

  • 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.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 of each node in the tree starting at node by n.This is useful to "move code" to a different location in a file.
  • ast.copylocation(_new_node, old_node)
  • Copy source location (lineno and coloffset) 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.

  • 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=Str(s=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.