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文件,该文件在below中再现。它们在_ast C模块中定义,并在ast中重新导出。

为抽象语法中的每个左侧符号定义一个类(例如,ast.stmtast.expr)。此外,右侧为每个构造函数定义了一个类;这些类继承自左侧树的类。例如,ast.BinOpast.expr继承。对于具有替代的生产规则(也称为“sums”),左侧类是抽象的:只有特定构造函数节点的实例被创建。

_fields

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

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

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

lineno
col_offset

ast.exprast.stmt子类的实例具有linenocol_offset属性。lineno是源文本的行号(1-索引,因此第一行是第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)

32.2.2. 抽象语法

抽象语法目前定义如下:

-- ASDL's six builtin types are identifier, int, string, bytes, object, singleton

module Python
{
    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, expr? returns)
          | AsyncFunctionDef(identifier name, arguments args,
                             stmt* body, expr* decorator_list, expr? returns)

          | ClassDef(identifier name,
             expr* bases,
             keyword* keywords,
             stmt* body,
             expr* decorator_list)
          | Return(expr? value)

          | Delete(expr* targets)
          | Assign(expr* targets, expr value)
          | AugAssign(expr target, operator op, expr value)

          -- use 'orelse' because else is a keyword in target languages
          | For(expr target, expr iter, stmt* body, stmt* orelse)
          | AsyncFor(expr target, expr iter, stmt* body, stmt* orelse)
          | While(expr test, stmt* body, stmt* orelse)
          | If(expr test, stmt* body, stmt* orelse)
          | With(withitem* items, stmt* body)
          | AsyncWith(withitem* items, stmt* body)

          | Raise(expr? exc, expr? cause)
          | Try(stmt* body, excepthandler* handlers, stmt* orelse, stmt* finalbody)
          | Assert(expr test, expr? msg)

          | Import(alias* names)
          | ImportFrom(identifier? module, alias* names, int? level)

          | Global(identifier* names)
          | Nonlocal(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
         | Await(expr value)
         | Yield(expr? value)
         | YieldFrom(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)
         | Num(object n) -- a number as a PyObject.
         | Str(string s) -- need to specify raw, unicode, etc?
         | Bytes(bytes s)
         | NameConstant(singleton value)
         | Ellipsis

         -- the following expression can appear in assignment context
         | Attribute(expr value, identifier attr, expr_context ctx)
         | Subscript(expr value, slice slice, expr_context ctx)
         | Starred(expr value, 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 = Slice(expr? lower, expr? upper, expr? step)
          | ExtSlice(slice* dims)
          | Index(expr value)

    boolop = And | Or

    operator = Add | Sub | Mult | MatMult | 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)

    excepthandler = ExceptHandler(expr? type, identifier? name, stmt* body)
                    attributes (int lineno, int col_offset)

    arguments = (arg* args, arg? vararg, arg* kwonlyargs, expr* kw_defaults,
                 arg? kwarg, expr* defaults)

    arg = (identifier arg, expr? annotation)
           attributes (int lineno, int col_offset)

    -- keyword arguments supplied to call (NULL identifier for **kwargs)
    keyword = (identifier? arg, expr value)

    -- import name with optional 'as' alias.
    alias = (identifier name, identifier? asname)

    withitem = (expr context_expr, expr? optional_vars)
}

32.2.3. ast助手

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

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

将源解析为AST节点。等同于compile(source, filename, 模式, ast.PyCF_ONLY_AST)

ast.literal_eval(node_or_string)

安全计算表达式节点或包含Python字面值或容器显示的字符串。提供的字符串或节点只能由以下Python字面值结构组成:字符串,字节,数字,元组,列表,项,集,布尔值和None

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

在版本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. 如果clean为true,请使用inspect.cleandoc()清除docstring的缩进。

ast.fix_missing_locations(node)

当使用compile()编译节点树时,编译器对于支持它们的每个节点都需要linenocol_offset属性。这是非常繁琐的填充生成的节点,所以这个帮助程序通过将它们设置为父节点的值,递归地添加这些属性尚未设置。它以递归方式从节点开始工作。

ast.increment_lineno(node, n=1)

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

ast.copy_location(new_node, old_node)

如果可能,将源位置(linenocol_offset)从old_node复制到new_node,然后返回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)

产生节点的所有直接子节点,即作为节点的所有字段和作为节点列表的所有字段项。

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

也可以看看

Green Tree Snakes是一个外部文档资源,具有使用Python AST的良好细节。