32.2. ast — 抽象语法树

源代码: Lib/ast.py


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

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

32.2.1. 节点类

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)

32.2.2. 抽象文法

抽象文法目前定义如下

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

32.2.3. ast 中的辅助函数

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

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

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

警告

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

ast.literal_eval(node_or_string)

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

This can be used for safely evaluating strings containing Python values from untrusted sources without the need to parse the values oneself. It is not capable of evaluating arbitrarily complex expressions, for example involving operators or indexing.

警告

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

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

ast.get_docstring(node, clean=True)

Return the docstring of the given node (which must be a FunctionDef, ClassDef or Module node), or None if it has no docstring. If clean is true, clean up the docstring’s indentation with inspect.cleandoc().

ast.fix_missing_locations(node)

When you compile a node tree with compile(), the compiler expects lineno and col_offset attributes for every node that supports them. This is rather tedious to fill in for generated nodes, so this helper adds these attributes recursively where not already set, by setting them to the values of the parent node. It works recursively starting at node.

ast.increment_lineno(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.copy_location(new_node, old_node)

Copy source location (lineno and col_offset) from old_node to new_node if possible, and return new_node.

ast.iter_fields(node)

Yield a tuple of (fieldname, value) for each field in node._fields that is present on node.

ast.iter_child_nodes(node)

Yield all direct child nodes of node, that is, all fields that are nodes and 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 only want 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 a visitor function for every node found. This function may return a value which is forwarded by the visit() method.

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

  • visit(node)

    Visit a node. The default implementation calls the method called self.visit_*classname* where classname is the name of the node class, or generic_visit() if that method doesn’t exist.

  • generic_visit(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 be visited unless the visitor calls generic_visit() or visits them itself.

Don’t use the NodeVisitor if you want to apply changes to nodes during 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. def visit_Name(self, node):
  3. return copy_location(Subscript(
  4. value=Name(id='data', ctx=Load()),
  5. slice=Index(value=Str(s=node.id)),
  6. ctx=node.ctx
  7. ), 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 for debugging purposes. The returned string will show the names and the values for fields. This makes the code impossible to evaluate, so if evaluation is wanted annotate_fields must be set to False. Attributes such as line numbers 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 good details on working with Python ASTs.