ast —- 抽象语法树

源代码: Lib/ast.py


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

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

抽象文法

抽象文法目前定义如下

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

节点类

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 have lineno, col_offset, end_lineno, and end_col_offset attributes. The lineno and end_lineno are the first and last line numbers of the source text span (1-indexed so the first line is line 1), and the col_offset and end_col_offset are the corresponding UTF-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 are therefore optional. The end offset is after the last symbol, for example one can get the source segment of a one-line expression node using source_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.

在 3.9 版更改: Simple indices are represented by their value, extended slices are represented as tuples.

3.8 版后已移除: Old classes ast.Num, ast.Str, ast.Bytes, ast.NameConstant and ast.Ellipsis are still available, but they will be removed in future Python releases. In the meantime, instantiating them will return an instance of a different class.

3.9 版后已移除: Old classes ast.Index and ast.ExtSlice are still available, but they will be removed in future Python releases. In the meantime, instantiating them will return an instance of a different class.

注解

The descriptions of the specific node classes displayed here were initially adapted from the fantastic Green Tree Snakes project and all its contributors.

字面值

class ast.Constant(value)

A constant value. The value attribute of the Constant literal contains the Python object it represents. The values represented can be simple types such as a number, string or None, but also immutable container types (tuples and frozensets) if all of their elements are constant.

  1. >>> print(ast.dump(ast.parse('123', mode='eval'), indent=4))
  2. Expression(
  3. body=Constant(value=123))

class ast.FormattedValue(value, conversion, format_spec)

Node representing a single formatting field in an f-string. If the string contains a single formatting field and nothing else the node can be isolated otherwise it appears in JoinedStr.

  • value is any expression node (such as a literal, a variable, or a function call).

  • conversion is an integer:

    • -1: no formatting

    • 115: !s string formatting

    • 114: !r repr formatting

    • 97: !a ascii formatting

  • format_spec is a JoinedStr node representing the formatting of the value, or None if no format was specified. Both conversion and format_spec can be set at the same time.

class ast.JoinedStr(values)

An f-string, comprising a series of FormattedValue and Constant nodes.

  1. >>> print(ast.dump(ast.parse('f"sin({a}) is {sin(a):.3}"', mode='eval'), indent=4))
  2. Expression(
  3. body=JoinedStr(
  4. values=[
  5. Constant(value='sin('),
  6. FormattedValue(
  7. value=Name(id='a', ctx=Load()),
  8. conversion=-1),
  9. Constant(value=') is '),
  10. FormattedValue(
  11. value=Call(
  12. func=Name(id='sin', ctx=Load()),
  13. args=[
  14. Name(id='a', ctx=Load())],
  15. keywords=[]),
  16. conversion=-1,
  17. format_spec=JoinedStr(
  18. values=[
  19. Constant(value='.3')]))]))

class ast.List(elts, ctx)

class ast.Tuple(elts, ctx)

A list or tuple. elts holds a list of nodes representing the elements. ctx is Store if the container is an assignment target (i.e. (x,y)=something), and Load otherwise.

  1. >>> print(ast.dump(ast.parse('[1, 2, 3]', mode='eval'), indent=4))
  2. Expression(
  3. body=List(
  4. elts=[
  5. Constant(value=1),
  6. Constant(value=2),
  7. Constant(value=3)],
  8. ctx=Load()))
  9. >>> print(ast.dump(ast.parse('(1, 2, 3)', mode='eval'), indent=4))
  10. Expression(
  11. body=Tuple(
  12. elts=[
  13. Constant(value=1),
  14. Constant(value=2),
  15. Constant(value=3)],
  16. ctx=Load()))

class ast.Set(elts)

A set. elts holds a list of nodes representing the set’s elements.

  1. >>> print(ast.dump(ast.parse('{1, 2, 3}', mode='eval'), indent=4))
  2. Expression(
  3. body=Set(
  4. elts=[
  5. Constant(value=1),
  6. Constant(value=2),
  7. Constant(value=3)]))

class ast.Dict(keys, values)

A dictionary. keys and values hold lists of nodes representing the keys and the values respectively, in matching order (what would be returned when calling dictionary.keys() and dictionary.values()).

When doing dictionary unpacking using dictionary literals the expression to be expanded goes in the values list, with a None at the corresponding position in keys.

  1. >>> print(ast.dump(ast.parse('{"a":1, **d}', mode='eval'), indent=4))
  2. Expression(
  3. body=Dict(
  4. keys=[
  5. Constant(value='a'),
  6. None],
  7. values=[
  8. Constant(value=1),
  9. Name(id='d', ctx=Load())]))

Variables

class ast.Name(id, ctx)

A variable name. id holds the name as a string, and ctx is one of the following types.

class ast.Load

class ast.Store

class ast.Del

Variable references can be used to load the value of a variable, to assign a new value to it, or to delete it. Variable references are given a context to distinguish these cases.

  1. >>> print(ast.dump(ast.parse('a'), indent=4))
  2. Module(
  3. body=[
  4. Expr(
  5. value=Name(id='a', ctx=Load()))],
  6. type_ignores=[])
  7. >>> print(ast.dump(ast.parse('a = 1'), indent=4))
  8. Module(
  9. body=[
  10. Assign(
  11. targets=[
  12. Name(id='a', ctx=Store())],
  13. value=Constant(value=1))],
  14. type_ignores=[])
  15. >>> print(ast.dump(ast.parse('del a'), indent=4))
  16. Module(
  17. body=[
  18. Delete(
  19. targets=[
  20. Name(id='a', ctx=Del())])],
  21. type_ignores=[])

class ast.Starred(value, ctx)

A *var variable reference. value holds the variable, typically a Name node. This type must be used when building a Call node with *args.

  1. >>> print(ast.dump(ast.parse('a, *b = it'), indent=4))
  2. Module(
  3. body=[
  4. Assign(
  5. targets=[
  6. Tuple(
  7. elts=[
  8. Name(id='a', ctx=Store()),
  9. Starred(
  10. value=Name(id='b', ctx=Store()),
  11. ctx=Store())],
  12. ctx=Store())],
  13. value=Name(id='it', ctx=Load()))],
  14. type_ignores=[])

表达式

class ast.Expr(value)

When an expression, such as a function call, appears as a statement by itself with its return value not used or stored, it is wrapped in this container. value holds one of the other nodes in this section, a Constant, a Name, a Lambda, a Yield or YieldFrom node.

  1. >>> print(ast.dump(ast.parse('-a'), indent=4))
  2. Module(
  3. body=[
  4. Expr(
  5. value=UnaryOp(
  6. op=USub(),
  7. operand=Name(id='a', ctx=Load())))],
  8. type_ignores=[])

class ast.UnaryOp(op, operand)

A unary operation. op is the operator, and operand any expression node.

class ast.UAdd

class ast.USub

class ast.Not

class ast.Invert

Unary operator tokens. Not is the not keyword, Invert is the ~ operator.

  1. >>> print(ast.dump(ast.parse('not x', mode='eval'), indent=4))
  2. Expression(
  3. body=UnaryOp(
  4. op=Not(),
  5. operand=Name(id='x', ctx=Load())))

class ast.BinOp(left, op, right)

A binary operation (like addition or division). op is the operator, and left and right are any expression nodes.

  1. >>> print(ast.dump(ast.parse('x + y', mode='eval'), indent=4))
  2. Expression(
  3. body=BinOp(
  4. left=Name(id='x', ctx=Load()),
  5. op=Add(),
  6. right=Name(id='y', ctx=Load())))

class ast.Add

class ast.Sub

class ast.Mult

class ast.Div

class ast.FloorDiv

class ast.Mod

class ast.Pow

class ast.LShift

class ast.RShift

class ast.BitOr

class ast.BitXor

class ast.BitAnd

class ast.MatMult

Binary operator tokens.

class ast.BoolOp(op, values)

A boolean operation, ‘or’ or ‘and’. op is Or or And. values are the values involved. Consecutive operations with the same operator, such as a or b or c, are collapsed into one node with several values.

This doesn’t include not, which is a UnaryOp.

  1. >>> print(ast.dump(ast.parse('x or y', mode='eval'), indent=4))
  2. Expression(
  3. body=BoolOp(
  4. op=Or(),
  5. values=[
  6. Name(id='x', ctx=Load()),
  7. Name(id='y', ctx=Load())]))

class ast.And

class ast.Or

Boolean operator tokens.

class ast.Compare(left, ops, comparators)

A comparison of two or more values. left is the first value in the comparison, ops the list of operators, and comparators the list of values after the first element in the comparison.

  1. >>> print(ast.dump(ast.parse('1 <= a < 10', mode='eval'), indent=4))
  2. Expression(
  3. body=Compare(
  4. left=Constant(value=1),
  5. ops=[
  6. LtE(),
  7. Lt()],
  8. comparators=[
  9. Name(id='a', ctx=Load()),
  10. Constant(value=10)]))

class ast.Eq

class ast.NotEq

class ast.Lt

class ast.LtE

class ast.Gt

class ast.GtE

class ast.Is

class ast.IsNot

class ast.In

class ast.NotIn

Comparison operator tokens.

class ast.Call(func, args, keywords, starargs, kwargs)

A function call. func is the function, which will often be a Name or Attribute object. Of the arguments:

  • args holds a list of the arguments passed by position.

  • keywords holds a list of keyword objects representing arguments passed by keyword.

When creating a Call node, args and keywords are required, but they can be empty lists. starargs and kwargs are optional.

  1. >>> print(ast.dump(ast.parse('func(a, b=c, *d, **e)', mode='eval'), indent=4))
  2. Expression(
  3. body=Call(
  4. func=Name(id='func', ctx=Load()),
  5. args=[
  6. Name(id='a', ctx=Load()),
  7. Starred(
  8. value=Name(id='d', ctx=Load()),
  9. ctx=Load())],
  10. keywords=[
  11. keyword(
  12. arg='b',
  13. value=Name(id='c', ctx=Load())),
  14. keyword(
  15. value=Name(id='e', ctx=Load()))]))

class ast.keyword(arg, value)

A keyword argument to a function call or class definition. arg is a raw string of the parameter name, value is a node to pass in.

class ast.IfExp(test, body, orelse)

An expression such as a if b else c. Each field holds a single node, so in the following example, all three are Name nodes.

  1. >>> print(ast.dump(ast.parse('a if b else c', mode='eval'), indent=4))
  2. Expression(
  3. body=IfExp(
  4. test=Name(id='b', ctx=Load()),
  5. body=Name(id='a', ctx=Load()),
  6. orelse=Name(id='c', ctx=Load())))

class ast.Attribute(value, attr, ctx)

Attribute access, e.g. d.keys. value is a node, typically a Name. attr is a bare string giving the name of the attribute, and ctx is Load, Store or Del according to how the attribute is acted on.

  1. >>> print(ast.dump(ast.parse('snake.colour', mode='eval'), indent=4))
  2. Expression(
  3. body=Attribute(
  4. value=Name(id='snake', ctx=Load()),
  5. attr='colour',
  6. ctx=Load()))

class ast.NamedExpr(target, value)

A named expression. This AST node is produced by the assignment expressions operator (also known as the walrus operator). As opposed to the Assign node in which the first argument can be multiple nodes, in this case both target and value must be single nodes.

  1. >>> print(ast.dump(ast.parse('(x := 4)', mode='eval'), indent=4))
  2. Expression(
  3. body=NamedExpr(
  4. target=Name(id='x', ctx=Store()),
  5. value=Constant(value=4)))

Subscripting

class ast.Subscript(value, slice, ctx)

A subscript, such as l[1]. value is the subscripted object (usually sequence or mapping). slice is an index, slice or key. It can be a Tuple and contain a Slice. ctx is Load, Store or Del according to the action performed with the subscript.

  1. >>> print(ast.dump(ast.parse('l[1:2, 3]', mode='eval'), indent=4))
  2. Expression(
  3. body=Subscript(
  4. value=Name(id='l', ctx=Load()),
  5. slice=Tuple(
  6. elts=[
  7. Slice(
  8. lower=Constant(value=1),
  9. upper=Constant(value=2)),
  10. Constant(value=3)],
  11. ctx=Load()),
  12. ctx=Load()))

class ast.Slice(lower, upper, step)

Regular slicing (on the form lower:upper or lower:upper:step). Can occur only inside the slice field of Subscript, either directly or as an element of Tuple.

  1. >>> print(ast.dump(ast.parse('l[1:2]', mode='eval'), indent=4))
  2. Expression(
  3. body=Subscript(
  4. value=Name(id='l', ctx=Load()),
  5. slice=Slice(
  6. lower=Constant(value=1),
  7. upper=Constant(value=2)),
  8. ctx=Load()))

Comprehensions

class ast.ListComp(elt, generators)

class ast.SetComp(elt, generators)

class ast.GeneratorExp(elt, generators)

class ast.DictComp(key, value, generators)

List and set comprehensions, generator expressions, and dictionary comprehensions. elt (or key and value) is a single node representing the part that will be evaluated for each item.

generators is a list of comprehension nodes.

  1. >>> print(ast.dump(ast.parse('[x for x in numbers]', mode='eval'), indent=4))
  2. Expression(
  3. body=ListComp(
  4. elt=Name(id='x', ctx=Load()),
  5. generators=[
  6. comprehension(
  7. target=Name(id='x', ctx=Store()),
  8. iter=Name(id='numbers', ctx=Load()),
  9. ifs=[],
  10. is_async=0)]))
  11. >>> print(ast.dump(ast.parse('{x: x**2 for x in numbers}', mode='eval'), indent=4))
  12. Expression(
  13. body=DictComp(
  14. key=Name(id='x', ctx=Load()),
  15. value=BinOp(
  16. left=Name(id='x', ctx=Load()),
  17. op=Pow(),
  18. right=Constant(value=2)),
  19. generators=[
  20. comprehension(
  21. target=Name(id='x', ctx=Store()),
  22. iter=Name(id='numbers', ctx=Load()),
  23. ifs=[],
  24. is_async=0)]))
  25. >>> print(ast.dump(ast.parse('{x for x in numbers}', mode='eval'), indent=4))
  26. Expression(
  27. body=SetComp(
  28. elt=Name(id='x', ctx=Load()),
  29. generators=[
  30. comprehension(
  31. target=Name(id='x', ctx=Store()),
  32. iter=Name(id='numbers', ctx=Load()),
  33. ifs=[],
  34. is_async=0)]))

class ast.comprehension(target, iter, ifs, is_async)

One for clause in a comprehension. target is the reference to use for each element - typically a Name or Tuple node. iter is the object to iterate over. ifs is a list of test expressions: each for clause can have multiple ifs.

is_async indicates a comprehension is asynchronous (using an async for instead of for). The value is an integer (0 or 1).

  1. >>> print(ast.dump(ast.parse('[ord(c) for line in file for c in line]', mode='eval'),
  2. ... indent=4)) # Multiple comprehensions in one.
  3. Expression(
  4. body=ListComp(
  5. elt=Call(
  6. func=Name(id='ord', ctx=Load()),
  7. args=[
  8. Name(id='c', ctx=Load())],
  9. keywords=[]),
  10. generators=[
  11. comprehension(
  12. target=Name(id='line', ctx=Store()),
  13. iter=Name(id='file', ctx=Load()),
  14. ifs=[],
  15. is_async=0),
  16. comprehension(
  17. target=Name(id='c', ctx=Store()),
  18. iter=Name(id='line', ctx=Load()),
  19. ifs=[],
  20. is_async=0)]))
  21. >>> print(ast.dump(ast.parse('(n**2 for n in it if n>5 if n<10)', mode='eval'),
  22. ... indent=4)) # generator comprehension
  23. Expression(
  24. body=GeneratorExp(
  25. elt=BinOp(
  26. left=Name(id='n', ctx=Load()),
  27. op=Pow(),
  28. right=Constant(value=2)),
  29. generators=[
  30. comprehension(
  31. target=Name(id='n', ctx=Store()),
  32. iter=Name(id='it', ctx=Load()),
  33. ifs=[
  34. Compare(
  35. left=Name(id='n', ctx=Load()),
  36. ops=[
  37. Gt()],
  38. comparators=[
  39. Constant(value=5)]),
  40. Compare(
  41. left=Name(id='n', ctx=Load()),
  42. ops=[
  43. Lt()],
  44. comparators=[
  45. Constant(value=10)])],
  46. is_async=0)]))
  47. >>> print(ast.dump(ast.parse('[i async for i in soc]', mode='eval'),
  48. ... indent=4)) # Async comprehension
  49. Expression(
  50. body=ListComp(
  51. elt=Name(id='i', ctx=Load()),
  52. generators=[
  53. comprehension(
  54. target=Name(id='i', ctx=Store()),
  55. iter=Name(id='soc', ctx=Load()),
  56. ifs=[],
  57. is_async=1)]))

Statements

class ast.Assign(targets, value, type_comment)

An assignment. targets is a list of nodes, and value is a single node.

Multiple nodes in targets represents assigning the same value to each. Unpacking is represented by putting a Tuple or List within targets.

  • type_comment

    type_comment is an optional string with the type annotation as a comment.

  1. >>> print(ast.dump(ast.parse('a = b = 1'), indent=4)) # Multiple assignment
  2. Module(
  3. body=[
  4. Assign(
  5. targets=[
  6. Name(id='a', ctx=Store()),
  7. Name(id='b', ctx=Store())],
  8. value=Constant(value=1))],
  9. type_ignores=[])
  10. >>> print(ast.dump(ast.parse('a,b = c'), indent=4)) # Unpacking
  11. Module(
  12. body=[
  13. Assign(
  14. targets=[
  15. Tuple(
  16. elts=[
  17. Name(id='a', ctx=Store()),
  18. Name(id='b', ctx=Store())],
  19. ctx=Store())],
  20. value=Name(id='c', ctx=Load()))],
  21. type_ignores=[])

class ast.AnnAssign(target, annotation, value, simple)

An assignment with a type annotation. target is a single node and can be a Name, a Attribute or a Subscript. annotation is the annotation, such as a Constant or Name node. value is a single optional node. simple is a boolean integer set to True for a Name node in target that do not appear in between parenthesis and are hence pure names and not expressions.

  1. >>> print(ast.dump(ast.parse('c: int'), indent=4))
  2. Module(
  3. body=[
  4. AnnAssign(
  5. target=Name(id='c', ctx=Store()),
  6. annotation=Name(id='int', ctx=Load()),
  7. simple=1)],
  8. type_ignores=[])
  9. >>> print(ast.dump(ast.parse('(a): int = 1'), indent=4)) # Annotation with parenthesis
  10. Module(
  11. body=[
  12. AnnAssign(
  13. target=Name(id='a', ctx=Store()),
  14. annotation=Name(id='int', ctx=Load()),
  15. value=Constant(value=1),
  16. simple=0)],
  17. type_ignores=[])
  18. >>> print(ast.dump(ast.parse('a.b: int'), indent=4)) # Attribute annotation
  19. Module(
  20. body=[
  21. AnnAssign(
  22. target=Attribute(
  23. value=Name(id='a', ctx=Load()),
  24. attr='b',
  25. ctx=Store()),
  26. annotation=Name(id='int', ctx=Load()),
  27. simple=0)],
  28. type_ignores=[])
  29. >>> print(ast.dump(ast.parse('a[1]: int'), indent=4)) # Subscript annotation
  30. Module(
  31. body=[
  32. AnnAssign(
  33. target=Subscript(
  34. value=Name(id='a', ctx=Load()),
  35. slice=Constant(value=1),
  36. ctx=Store()),
  37. annotation=Name(id='int', ctx=Load()),
  38. simple=0)],
  39. type_ignores=[])

class ast.AugAssign(target, op, value)

Augmented assignment, such as a += 1. In the following example, target is a Name node for x (with the Store context), op is Add, and value is a Constant with value for 1.

The target attribute connot be of class Tuple or List, unlike the targets of Assign.

  1. >>> print(ast.dump(ast.parse('x += 2'), indent=4))
  2. Module(
  3. body=[
  4. AugAssign(
  5. target=Name(id='x', ctx=Store()),
  6. op=Add(),
  7. value=Constant(value=2))],
  8. type_ignores=[])

class ast.Raise(exc, cause)

A raise statement. exc is the exception object to be raised, normally a Call or Name, or None for a standalone raise. cause is the optional part for y in raise x from y.

  1. >>> print(ast.dump(ast.parse('raise x from y'), indent=4))
  2. Module(
  3. body=[
  4. Raise(
  5. exc=Name(id='x', ctx=Load()),
  6. cause=Name(id='y', ctx=Load()))],
  7. type_ignores=[])

class ast.Assert(test, msg)

An assertion. test holds the condition, such as a Compare node. msg holds the failure message.

  1. >>> print(ast.dump(ast.parse('assert x,y'), indent=4))
  2. Module(
  3. body=[
  4. Assert(
  5. test=Name(id='x', ctx=Load()),
  6. msg=Name(id='y', ctx=Load()))],
  7. type_ignores=[])

class ast.Delete(targets)

Represents a del statement. targets is a list of nodes, such as Name, Attribute or Subscript nodes.

  1. >>> print(ast.dump(ast.parse('del x,y,z'), indent=4))
  2. Module(
  3. body=[
  4. Delete(
  5. targets=[
  6. Name(id='x', ctx=Del()),
  7. Name(id='y', ctx=Del()),
  8. Name(id='z', ctx=Del())])],
  9. type_ignores=[])

class ast.Pass

A pass statement.

  1. >>> print(ast.dump(ast.parse('pass'), indent=4))
  2. Module(
  3. body=[
  4. Pass()],
  5. type_ignores=[])

Other statements which are only applicable inside functions or loops are described in other sections.

Imports

class ast.Import(names)

An import statement. names is a list of alias nodes.

  1. >>> print(ast.dump(ast.parse('import x,y,z'), indent=4))
  2. Module(
  3. body=[
  4. Import(
  5. names=[
  6. alias(name='x'),
  7. alias(name='y'),
  8. alias(name='z')])],
  9. type_ignores=[])

class ast.ImportFrom(module, names, level)

Represents from x import y. module is a raw string of the ‘from’ name, without any leading dots, or None for statements such as from . import foo. level is an integer holding the level of the relative import (0 means absolute import).

  1. >>> print(ast.dump(ast.parse('from y import x,y,z'), indent=4))
  2. Module(
  3. body=[
  4. ImportFrom(
  5. module='y',
  6. names=[
  7. alias(name='x'),
  8. alias(name='y'),
  9. alias(name='z')],
  10. level=0)],
  11. type_ignores=[])

class ast.alias(name, asname)

Both parameters are raw strings of the names. asname can be None if the regular name is to be used.

  1. >>> print(ast.dump(ast.parse('from ..foo.bar import a as b, c'), indent=4))
  2. Module(
  3. body=[
  4. ImportFrom(
  5. module='foo.bar',
  6. names=[
  7. alias(name='a', asname='b'),
  8. alias(name='c')],
  9. level=2)],
  10. type_ignores=[])

Control flow

注解

Optional clauses such as else are stored as an empty list if they’re not present.

class ast.If(test, body, orelse)

An if statement. test holds a single node, such as a Compare node. body and orelse each hold a list of nodes.

elif clauses don’t have a special representation in the AST, but rather appear as extra If nodes within the orelse section of the previous one.

  1. >>> print(ast.dump(ast.parse("""
  2. ... if x:
  3. ... ...
  4. ... elif y:
  5. ... ...
  6. ... else:
  7. ... ...
  8. ... """), indent=4))
  9. Module(
  10. body=[
  11. If(
  12. test=Name(id='x', ctx=Load()),
  13. body=[
  14. Expr(
  15. value=Constant(value=Ellipsis))],
  16. orelse=[
  17. If(
  18. test=Name(id='y', ctx=Load()),
  19. body=[
  20. Expr(
  21. value=Constant(value=Ellipsis))],
  22. orelse=[
  23. Expr(
  24. value=Constant(value=Ellipsis))])])],
  25. type_ignores=[])

class ast.For(target, iter, body, orelse, type_comment)

A for loop. target holds the variable(s) the loop assigns to, as a single Name, Tuple or List node. iter holds the item to be looped over, again as a single node. body and orelse contain lists of nodes to execute. Those in orelse are executed if the loop finishes normally, rather than via a break statement.

  • type_comment

    type_comment is an optional string with the type annotation as a comment.

  1. >>> print(ast.dump(ast.parse("""
  2. ... for x in y:
  3. ... ...
  4. ... else:
  5. ... ...
  6. ... """), indent=4))
  7. Module(
  8. body=[
  9. For(
  10. target=Name(id='x', ctx=Store()),
  11. iter=Name(id='y', ctx=Load()),
  12. body=[
  13. Expr(
  14. value=Constant(value=Ellipsis))],
  15. orelse=[
  16. Expr(
  17. value=Constant(value=Ellipsis))])],
  18. type_ignores=[])

class ast.While(test, body, orelse)

A while loop. test holds the condition, such as a Compare node.

  1. >> print(ast.dump(ast.parse("""
  2. ... while x:
  3. ... ...
  4. ... else:
  5. ... ...
  6. ... """), indent=4))
  7. Module(
  8. body=[
  9. While(
  10. test=Name(id='x', ctx=Load()),
  11. body=[
  12. Expr(
  13. value=Constant(value=Ellipsis))],
  14. orelse=[
  15. Expr(
  16. value=Constant(value=Ellipsis))])],
  17. type_ignores=[])

class ast.Break

class ast.Continue

The break and continue statements.

  1. >>> print(ast.dump(ast.parse("""\
  2. ... for a in b:
  3. ... if a > 5:
  4. ... break
  5. ... else:
  6. ... continue
  7. ...
  8. ... """), indent=4))
  9. Module(
  10. body=[
  11. For(
  12. target=Name(id='a', ctx=Store()),
  13. iter=Name(id='b', ctx=Load()),
  14. body=[
  15. If(
  16. test=Compare(
  17. left=Name(id='a', ctx=Load()),
  18. ops=[
  19. Gt()],
  20. comparators=[
  21. Constant(value=5)]),
  22. body=[
  23. Break()],
  24. orelse=[
  25. Continue()])],
  26. orelse=[])],
  27. type_ignores=[])

class ast.Try(body, handlers, orelse, finalbody)

try blocks. All attributes are list of nodes to execute, except for handlers, which is a list of ExceptHandler nodes.

  1. >>> print(ast.dump(ast.parse("""
  2. ... try:
  3. ... ...
  4. ... except Exception:
  5. ... ...
  6. ... except OtherException as e:
  7. ... ...
  8. ... else:
  9. ... ...
  10. ... finally:
  11. ... ...
  12. ... """), indent=4))
  13. Module(
  14. body=[
  15. Try(
  16. body=[
  17. Expr(
  18. value=Constant(value=Ellipsis))],
  19. handlers=[
  20. ExceptHandler(
  21. type=Name(id='Exception', ctx=Load()),
  22. body=[
  23. Expr(
  24. value=Constant(value=Ellipsis))]),
  25. ExceptHandler(
  26. type=Name(id='OtherException', ctx=Load()),
  27. name='e',
  28. body=[
  29. Expr(
  30. value=Constant(value=Ellipsis))])],
  31. orelse=[
  32. Expr(
  33. value=Constant(value=Ellipsis))],
  34. finalbody=[
  35. Expr(
  36. value=Constant(value=Ellipsis))])],
  37. type_ignores=[])

class ast.ExceptHandler(type, name, body)

A single except clause. type is the exception type it will match, typically a Name node (or None for a catch-all except: clause). name is a raw string for the name to hold the exception, or None if the clause doesn’t have as foo. body is a list of nodes.

  1. >>> print(ast.dump(ast.parse("""\
  2. ... try:
  3. ... a + 1
  4. ... except TypeError:
  5. ... pass
  6. ... """), indent=4))
  7. Module(
  8. body=[
  9. Try(
  10. body=[
  11. Expr(
  12. value=BinOp(
  13. left=Name(id='a', ctx=Load()),
  14. op=Add(),
  15. right=Constant(value=1)))],
  16. handlers=[
  17. ExceptHandler(
  18. type=Name(id='TypeError', ctx=Load()),
  19. body=[
  20. Pass()])],
  21. orelse=[],
  22. finalbody=[])],
  23. type_ignores=[])

class ast.With(items, body, type_comment)

A with block. items is a list of withitem nodes representing the context managers, and body is the indented block inside the context.

  • type_comment

    type_comment is an optional string with the type annotation as a comment.

class ast.withitem(context_expr, optional_vars)

A single context manager in a with block. context_expr is the context manager, often a Call node. optional_vars is a Name, Tuple or List for the as foo part, or None if that isn’t used.

  1. >>> print(ast.dump(ast.parse("""\
  2. ... with a as b, c as d:
  3. ... something(b, d)
  4. ... """), indent=4))
  5. Module(
  6. body=[
  7. With(
  8. items=[
  9. withitem(
  10. context_expr=Name(id='a', ctx=Load()),
  11. optional_vars=Name(id='b', ctx=Store())),
  12. withitem(
  13. context_expr=Name(id='c', ctx=Load()),
  14. optional_vars=Name(id='d', ctx=Store()))],
  15. body=[
  16. Expr(
  17. value=Call(
  18. func=Name(id='something', ctx=Load()),
  19. args=[
  20. Name(id='b', ctx=Load()),
  21. Name(id='d', ctx=Load())],
  22. keywords=[]))])],
  23. type_ignores=[])

Function and class definitions

class ast.FunctionDef(name, args, body, decorator_list, returns, type_comment)

A function definition.

  • name is a raw string of the function name.

  • args is a arguments node.

  • body is the list of nodes inside the function.

  • decorator_list is the list of decorators to be applied, stored outermost first (i.e. the first in the list will be applied last).

  • returns is the return annotation.

  • type_comment

    type_comment is an optional string with the type annotation as a comment.

class ast.Lambda(args, body)

lambda is a minimal function definition that can be used inside an expression. Unlike FunctionDef, body holds a single node.

  1. >>> print(ast.dump(ast.parse('lambda x,y: ...'), indent=4))
  2. Module(
  3. body=[
  4. Expr(
  5. value=Lambda(
  6. args=arguments(
  7. posonlyargs=[],
  8. args=[
  9. arg(arg='x'),
  10. arg(arg='y')],
  11. kwonlyargs=[],
  12. kw_defaults=[],
  13. defaults=[]),
  14. body=Constant(value=Ellipsis)))],
  15. type_ignores=[])

class ast.arguments(posonlyargs, args, vararg, kwonlyargs, kw_defaults, kwarg, defaults)

The arguments for a function.

  • posonlyargs, args and kwonlyargs are lists of arg nodes.

  • vararg and kwarg are single arg nodes, referring to the *args, **kwargs parameters.

  • kw_defaults is a list of default values for keyword-only arguments. If one is None, the corresponding argument is required.

  • defaults is a list of default values for arguments that can be passed positionally. If there are fewer defaults, they correspond to the last n arguments.

class ast.arg(arg, annotation, type_comment)

A single argument in a list. arg is a raw string of the argument name, annotation is its annotation, such as a Str or Name node.

  • type_comment

    type_comment is an optional string with the type annotation as a comment

  1. >>> print(ast.dump(ast.parse("""\
  2. ... @decorator1
  3. ... @decorator2
  4. ... def f(a: 'annotation', b=1, c=2, *d, e, f=3, **g) -> 'return annotation':
  5. ... pass
  6. ... """), indent=4))
  7. Module(
  8. body=[
  9. FunctionDef(
  10. name='f',
  11. args=arguments(
  12. posonlyargs=[],
  13. args=[
  14. arg(
  15. arg='a',
  16. annotation=Constant(value='annotation')),
  17. arg(arg='b'),
  18. arg(arg='c')],
  19. vararg=arg(arg='d'),
  20. kwonlyargs=[
  21. arg(arg='e'),
  22. arg(arg='f')],
  23. kw_defaults=[
  24. None,
  25. Constant(value=3)],
  26. kwarg=arg(arg='g'),
  27. defaults=[
  28. Constant(value=1),
  29. Constant(value=2)]),
  30. body=[
  31. Pass()],
  32. decorator_list=[
  33. Name(id='decorator1', ctx=Load()),
  34. Name(id='decorator2', ctx=Load())],
  35. returns=Constant(value='return annotation'))],
  36. type_ignores=[])

class ast.Return(value)

A return statement.

  1. >>> print(ast.dump(ast.parse('return 4'), indent=4))
  2. Module(
  3. body=[
  4. Return(
  5. value=Constant(value=4))],
  6. type_ignores=[])

class ast.Yield(value)

class ast.YieldFrom(value)

A yield or yield from expression. Because these are expressions, they must be wrapped in a Expr node if the value sent back is not used.

  1. >>> print(ast.dump(ast.parse('yield x'), indent=4))
  2. Module(
  3. body=[
  4. Expr(
  5. value=Yield(
  6. value=Name(id='x', ctx=Load())))],
  7. type_ignores=[])
  8. >>> print(ast.dump(ast.parse('yield from x'), indent=4))
  9. Module(
  10. body=[
  11. Expr(
  12. value=YieldFrom(
  13. value=Name(id='x', ctx=Load())))],
  14. type_ignores=[])

class ast.Global(names)

class ast.Nonlocal(names)

global and nonlocal statements. names is a list of raw strings.

  1. >>> print(ast.dump(ast.parse('global x,y,z'), indent=4))
  2. Module(
  3. body=[
  4. Global(
  5. names=[
  6. 'x',
  7. 'y',
  8. 'z'])],
  9. type_ignores=[])
  10. >>> print(ast.dump(ast.parse('nonlocal x,y,z'), indent=4))
  11. Module(
  12. body=[
  13. Nonlocal(
  14. names=[
  15. 'x',
  16. 'y',
  17. 'z'])],
  18. type_ignores=[])

class ast.ClassDef(name, bases, keywords, starargs, kwargs, body, decorator_list)

A class definition.

  • name is a raw string for the class name

  • bases is a list of nodes for explicitly specified base classes.

  • keywords is a list of keyword nodes, principally for ‘metaclass’. Other keywords will be passed to the metaclass, as per PEP-3115.

  • starargs and kwargs are each a single node, as in a function call. starargs will be expanded to join the list of base classes, and kwargs will be passed to the metaclass.

  • body is a list of nodes representing the code within the class definition.

  • decorator_list is a list of nodes, as in FunctionDef.

  1. >>> print(ast.dump(ast.parse("""\
  2. ... @decorator1
  3. ... @decorator2
  4. ... class Foo(base1, base2, metaclass=meta):
  5. ... pass
  6. ... """), indent=4))
  7. Module(
  8. body=[
  9. ClassDef(
  10. name='Foo',
  11. bases=[
  12. Name(id='base1', ctx=Load()),
  13. Name(id='base2', ctx=Load())],
  14. keywords=[
  15. keyword(
  16. arg='metaclass',
  17. value=Name(id='meta', ctx=Load()))],
  18. body=[
  19. Pass()],
  20. decorator_list=[
  21. Name(id='decorator1', ctx=Load()),
  22. Name(id='decorator2', ctx=Load())])],
  23. type_ignores=[])

Async and await

class ast.AsyncFunctionDef(name, args, body, decorator_list, returns, type_comment)

An async def function definition. Has the same fields as FunctionDef.

class ast.Await(value)

An await expression. value is what it waits for. Only valid in the body of an AsyncFunctionDef.

  1. >>> print(ast.dump(ast.parse("""\
  2. ... async def f():
  3. ... await other_func()
  4. ... """), indent=4))
  5. Module(
  6. body=[
  7. AsyncFunctionDef(
  8. name='f',
  9. args=arguments(
  10. posonlyargs=[],
  11. args=[],
  12. kwonlyargs=[],
  13. kw_defaults=[],
  14. defaults=[]),
  15. body=[
  16. Expr(
  17. value=Await(
  18. value=Call(
  19. func=Name(id='other_func', ctx=Load()),
  20. args=[],
  21. keywords=[])))],
  22. decorator_list=[])],
  23. type_ignores=[])

class ast.AsyncFor(target, iter, body, orelse, type_comment)

class ast.AsyncWith(items, body, type_comment)

async for loops and async with context managers. They have the same fields as For and With, respectively. Only valid in the body of an AsyncFunctionDef.

注解

When a string is parsed by ast.parse(), operator nodes (subclasses of ast.operator, ast.unaryop, ast.cmpop, ast.boolop and ast.expr_context) on the returned tree will be singletons. Changes to one will be reflected in all other occurrences of the same value (e.g. ast.Add).

ast 中的辅助函数

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

ast.parse(source, filename=’<unknown>’, 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 check and return type comments as specified by PEP 484 and PEP 526. This is equivalent to adding ast.PyCF_TYPE_COMMENTS to the flags passed to compile(). This will report syntax errors for misplaced type comments. Without this flag, type comments will be ignored, and the type_comment field on selected AST nodes will always be None. In addition, the locations of # type: ignore comments will be returned as the type_ignores attribute of Module (otherwise it is always an empty list).

In addition, if mode is 'func_type', the input syntax is modified 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, setting feature_version=(3, 4) will allow the use of async and await 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.unparse(ast_obj)

Unparse an ast.AST object and generate a string with code that would produce an equivalent ast.AST object if parsed back with ast.parse().

警告

The produced code string will not necessarily be equal to the original code that generated the ast.AST object (without any compiler optimizations, such as constant tuples/frozensets).

警告

Trying to unparse a highly complex expression would result with RecursionError.

3.9 新版功能.

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 版更改: 目前支持字节和集合。

在 3.9 版更改: Now supports creating empty sets with 'set()'.

ast.get_docstring(node, clean=True)

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

在 3.5 版更改: 目前支持 AsyncFunctionDef

ast.get_source_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 will be padded with spaces to match its original position.

3.8 新版功能.

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 and end 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, col_offset, end_lineno, and end_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.

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

class ast.NodeTransformer

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

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

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

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

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

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

If NodeTransformer introduces new nodes (that weren’t part of original tree) without giving them location information (such as lineno), fix_missing_locations() should be called with the new sub-tree to recalculate the location information:

  1. tree = ast.parse('foo', mode='eval')
  2. new_tree = fix_missing_locations(RewriteName().visit(tree))

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

  1. node = YourTransformer().visit(node)

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

Return a formatted dump of the tree in node. This is mainly useful for debugging 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 by omitting unambiguous field names. Attributes such as line numbers and column offsets are not dumped by default. If this is wanted, include_attributes can be set to true.

If indent is a non-negative integer or string, then the tree will be pretty-printed with that indent level. An indent level of 0, negative, or "" will only insert newlines. None (the default) selects the single line representation. Using a positive integer indent indents that many spaces per level. If indent is a string (such as "\t"), that string is used to indent each level.

在 3.9 版更改: Added the indent option.

Compiler Flags

The following flags may be passed to compile() in order to change effects on the compilation of a program:

ast.PyCF_ALLOW_TOP_LEVEL_AWAIT

Enables support for top-level await, async for, async with and async comprehensions.

3.8 新版功能.

ast.PyCF_ONLY_AST

Generates and returns an abstract syntax tree instead of returning a compiled code object.

ast.PyCF_TYPE_COMMENTS

Enables support for PEP 484 and PEP 526 style type comments (# type: <type>, # type: ignore <stuff>).

3.8 新版功能.

Command-Line Usage

3.9 新版功能.

The ast module can be executed as a script from the command line. It is as simple as:

  1. python -m ast [-m <mode>] [-a] [infile]

The following options are accepted:

-h``, --help

Show the help message and exit.

-m <mode>

--mode <mode>

Specify what kind of code must be compiled, like the mode argument in parse().

--no-type-comments

Don’t parse type comments.

-a``, --include-attributes

Include attributes such as line numbers and column offsets.

-i <indent>

--indent <indent>

Indentation of nodes in AST (number of spaces).

If infile is specified its contents are parsed to AST and dumped to stdout. Otherwise, the content is read from stdin.

参见

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

ASTTokens annotates Python ASTs with the positions of tokens and text in the source code that generated them. This is helpful for tools that make source code transformations.

leoAst.py unifies the token-based and parse-tree-based views of python programs by inserting two-way links between tokens and ast nodes.

LibCST parses code as a Concrete Syntax Tree that looks like an ast tree and keeps all formatting details. It’s useful for building automated refactoring (codemod) applications and linters.

Parso is a Python parser that supports error recovery and round-trip parsing for different Python versions (in multiple Python versions). Parso is also able to list multiple syntax errors in your python file.