ITookAPill's picture
PyComp First Commit
9273228
|
Raw
History Blame Contribute Delete
75.6 kB

A newer version of the Gradio SDK is available: 6.20.0

Upgrade

!ast{.interpreted-text role="mod"} --- Abstract syntax trees

::: {.module synopsis="Abstract Syntax Tree classes and manipulation."} ast :::

::: testsetup import ast :::

Source code: Lib/ast.py{.interpreted-text role="source"}


The !ast{.interpreted-text role="mod"} module helps Python applications to process trees of the Python abstract syntax grammar. The abstract syntax itself might change with each Python release; this module helps to find out programmatically what the current grammar looks like.

An abstract syntax tree can be generated by passing ast.PyCF_ONLY_AST{.interpreted-text role="data"} as a flag to the compile{.interpreted-text role="func"} built-in function, or using the parse{.interpreted-text role="func"} helper provided in this module. The result will be a tree of objects whose classes all inherit from ast.AST{.interpreted-text role="class"}. An abstract syntax tree can be compiled into a Python code object using the built-in compile{.interpreted-text role="func"} function.

Abstract grammar

The abstract grammar is currently defined as follows:

::: {.literalinclude language="asdl"} ../../Parser/Python.asdl :::

Node classes

:::::::::: AST This is the base of all AST node classes. The actual node classes are derived from the Parser/Python.asdl{.interpreted-text role="file"} file, which is reproduced above <abstract-grammar>{.interpreted-text role="ref"}. They are defined in the !_ast{.interpreted-text role="mod"} C module and re-exported in !ast{.interpreted-text role="mod"}.

There is one class defined for each left-hand side symbol in the abstract grammar (for example, ast.stmt{.interpreted-text role="class"} or ast.expr{.interpreted-text role="class"}). In addition, there is one class defined for each constructor on the right-hand side; these classes inherit from the classes for the left-hand side trees. For example, ast.BinOp{.interpreted-text role="class"} inherits from ast.expr{.interpreted-text role="class"}. For production rules with alternatives (aka "sums"), the left-hand side class is abstract: only instances of specific constructor nodes are ever created.

::: index single: ? (question mark); in AST grammar :::

::: index single: * (asterisk); in AST grammar :::

::: attribute [fields]{#fields}

Each concrete class has an attribute !_fields{.interpreted-text role="attr"} which gives the names of all child nodes.

Each instance of a concrete class has one attribute for each child node, of the type as defined in the grammar. For example, ast.BinOp{.interpreted-text role="class"} instances have an attribute left{.interpreted-text role="attr"} of type ast.expr{.interpreted-text role="class"}.

If these attributes are marked as optional in the grammar (using a question mark), the value might be None. If the attributes can have zero-or-more values (marked with an asterisk), the values are represented as Python lists. All possible attributes must be present and have valid values when compiling an AST with compile{.interpreted-text role="func"}. :::

::::: attribute [field_types]{#field_types}

The !_field_types{.interpreted-text role="attr"} attribute on each concrete class is a dictionary mapping field names (as also listed in _fields{.interpreted-text role="attr"}) to their types.

::: doctest >>> ast.TypeVar._field_types {'name': <class 'str'>, 'bound': ast.expr | None, 'default_value': ast.expr | None} :::

::: versionadded 3.13 ::: :::::

::: attribute lineno col_offset end_lineno end_col_offset

Instances of ast.expr{.interpreted-text role="class"} and ast.stmt{.interpreted-text role="class"} subclasses have lineno{.interpreted-text role="attr"}, col_offset{.interpreted-text role="attr"}, end_lineno{.interpreted-text role="attr"}, and end_col_offset{.interpreted-text role="attr"} attributes. The lineno{.interpreted-text role="attr"} and end_lineno{.interpreted-text role="attr"} are the first and last line numbers of source text span (1-indexed so the first line is line 1) and the col_offset{.interpreted-text role="attr"} and end_col_offset{.interpreted-text role="attr"} 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]. :::

The constructor of a class ast.T{.interpreted-text role="class"} parses its arguments as follows:

  • If there are positional arguments, there must be as many as there are items in T._fields{.interpreted-text role="attr"}; they will be assigned as attributes of these names.
  • If there are keyword arguments, they will set the attributes of the same names to the given values.

For example, to create and populate an ast.UnaryOp{.interpreted-text role="class"} node, you could use :

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

If a field that is optional in the grammar is omitted from the constructor, it defaults to None. If a list field is omitted, it defaults to the empty list. If a field of type !ast.expr_context{.interpreted-text role="class"} is omitted, it defaults to Load() <ast.Load>{.interpreted-text role="class"}. If any other field is omitted, a DeprecationWarning{.interpreted-text role="exc"} is raised and the AST node will not have this field. In Python 3.15, this condition will raise an error. ::::::::::

::: versionchanged 3.8

Class ast.Constant{.interpreted-text role="class"} is now used for all constants. :::

::: versionchanged 3.9

Simple indices are represented by their value, extended slices are represented as tuples. :::

::: versionchanged 3.14

The ~object.__repr__{.interpreted-text role="meth"} output of ~ast.AST{.interpreted-text role="class"} nodes includes the values of the node fields. :::

::: deprecated-removed 3.8 3.14

Previous versions of Python provided the AST classes !ast.Num{.interpreted-text role="class"}, !ast.Str{.interpreted-text role="class"}, !ast.Bytes{.interpreted-text role="class"}, !ast.NameConstant{.interpreted-text role="class"} and !ast.Ellipsis{.interpreted-text role="class"}, which were deprecated in Python 3.8. These classes were removed in Python 3.14, and their functionality has been replaced with ast.Constant{.interpreted-text role="class"}. :::

::: deprecated 3.9

Old classes !ast.Index{.interpreted-text role="class"} and !ast.ExtSlice{.interpreted-text role="class"} 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. :::

::: deprecated-removed 3.13 3.15

Previous versions of Python allowed the creation of AST nodes that were missing required fields. Similarly, AST node constructors allowed arbitrary keyword arguments that were set as attributes of the AST node, even if they did not match any of the fields of the AST node. This behavior is deprecated and will be removed in Python 3.15. :::

:::: note ::: title Note :::

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

Root nodes {#ast-root-nodes}

:::: {.Module(body, .type_ignores)} A Python module, as with file input <file-input>{.interpreted-text role="ref"}. Node type generated by ast.parse{.interpreted-text role="func"} in the default "exec" mode.

body is a list{.interpreted-text role="class"} of the module's ast-statements{.interpreted-text role="ref"}.

type_ignores is a list{.interpreted-text role="class"} of the module's type ignore comments; see ast.parse{.interpreted-text role="func"} for more details.

::: doctest >>> print(ast.dump(ast.parse('x = 1'), indent=4)) Module( body=[ Assign( targets=[ Name(id='x', ctx=Store())], value=Constant(value=1))]) ::: ::::

:::: Expression(body) A single Python expression input <expression-input>{.interpreted-text role="ref"}. Node type generated by ast.parse{.interpreted-text role="func"} when mode is "eval".

body is a single node, one of the expression types <ast-expressions>{.interpreted-text role="ref"}.

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

:::: Interactive(body) A single interactive input <interactive>{.interpreted-text role="ref"}, like in tut-interac{.interpreted-text role="ref"}. Node type generated by ast.parse{.interpreted-text role="func"} when mode is "single".

body is a list{.interpreted-text role="class"} of statement nodes <ast-statements>{.interpreted-text role="ref"}.

::: doctest >>> print(ast.dump(ast.parse('x = 1; y = 2', mode='single'), indent=4)) Interactive( body=[ Assign( targets=[ Name(id='x', ctx=Store())], value=Constant(value=1)), Assign( targets=[ Name(id='y', ctx=Store())], value=Constant(value=2))]) ::: ::::

::::: {.FunctionType(argtypes, .returns)} A representation of an old-style type comments for functions, as Python versions prior to 3.5 didn't support 484{.interpreted-text role="pep"} annotations. Node type generated by ast.parse{.interpreted-text role="func"} when mode is "func_type".

Such type comments would look like this:

def sum_two_number(a, b):
    # type: (int, int) -> int
    return a + b

argtypes is a list{.interpreted-text role="class"} of expression nodes <ast-expressions>{.interpreted-text role="ref"}.

returns is a single expression node <ast-expressions>{.interpreted-text role="ref"}.

::: doctest >>> print(ast.dump(ast.parse('(int, str) -> List[int]', mode='func_type'), indent=4)) FunctionType( argtypes=[ Name(id='int'), Name(id='str')], returns=Subscript( value=Name(id='List'), slice=Name(id='int'))) :::

::: versionadded 3.8 ::: :::::

Literals

:::: Constant(value) A constant value. The value attribute of the Constant literal contains the Python object it represents. The values represented can be instances of str{.interpreted-text role="class"}, bytes{.interpreted-text role="class"}, int{.interpreted-text role="class"}, float{.interpreted-text role="class"}, complex{.interpreted-text role="class"}, and bool{.interpreted-text role="class"}, and the constants None{.interpreted-text role="data"} and Ellipsis{.interpreted-text role="data"}.

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

::: {.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{.interpreted-text role="class"}.

  • value is any expression node (such as a literal, a variable, or a function call).
  • conversion is an integer:
    • -1: no formatting
    • 97 (ord('a')): !a ASCII <ascii>{.interpreted-text role="func"} formatting
    • 114 (ord('r')): !r repr{.interpreted-text role="func"} formatting
    • 115 (ord('s')): !s string <str>{.interpreted-text role="func"} formatting
  • format_spec is a JoinedStr{.interpreted-text role="class"} 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. :::

:::: JoinedStr(values) An f-string, comprising a series of FormattedValue{.interpreted-text role="class"} and Constant{.interpreted-text role="class"} nodes.

::: doctest >>> print(ast.dump(ast.parse('f"sin({a}) is {sin(a):.3}"', mode='eval'), indent=4)) Expression( body=JoinedStr( values=[ Constant(value='sin('), FormattedValue( value=Name(id='a'), conversion=-1), Constant(value=') is '), FormattedValue( value=Call( func=Name(id='sin'), args=[ Name(id='a')]), conversion=-1, format_spec=JoinedStr( values=[ Constant(value='.3')]))])) ::: ::::

::::: {.TemplateStr(values, ./)} ::: versionadded 3.14 :::

Node representing a template string literal, comprising a series of Interpolation{.interpreted-text role="class"} and Constant{.interpreted-text role="class"} nodes. These nodes may be any order, and do not need to be interleaved.

::: doctest >>> expr = ast.parse('t"{name} finished {place:ordinal}"', mode='eval') >>> print(ast.dump(expr, indent=4)) Expression( body=TemplateStr( values=[ Interpolation( value=Name(id='name'), str='name', conversion=-1), Constant(value=' finished '), Interpolation( value=Name(id='place'), str='place', conversion=-1, format_spec=JoinedStr( values=[ Constant(value='ordinal')]))])) ::: :::::

:::: {.Interpolation(value, .str, .conversion, .format_spec=None)} ::: versionadded 3.14 :::

Node representing a single interpolation field in a template string literal.

  • value is any expression node (such as a literal, a variable, or a function call). This has the same meaning as FormattedValue.value.

  • str is a constant containing the text of the interpolation expression.

    If str is set to None, then value is used to generate code when calling ast.unparse{.interpreted-text role="func"}. This no longer guarantees that the generated code is identical to the original and is intended for code generation.

  • conversion is an integer:

    • -1: no conversion
    • 97 (ord('a')): !a ASCII <ascii>{.interpreted-text role="func"} conversion
    • 114 (ord('r')): !r repr{.interpreted-text role="func"} conversion
    • 115 (ord('s')): !s string <str>{.interpreted-text role="func"} conversion

    This has the same meaning as FormattedValue.conversion.

  • format_spec is a JoinedStr{.interpreted-text role="class"} 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. This has the same meaning as FormattedValue.format_spec. ::::

:::: {.List(elts, .ctx) .Tuple(elts, .ctx)} A list or tuple. elts holds a list of nodes representing the elements. ctx is Store{.interpreted-text role="class"} if the container is an assignment target (i.e. (x,y)=something), and Load{.interpreted-text role="class"} otherwise.

::: doctest >>> print(ast.dump(ast.parse('[1, 2, 3]', mode='eval'), indent=4)) Expression( body=List( elts=[ Constant(value=1), Constant(value=2), Constant(value=3)])) >>> print(ast.dump(ast.parse('(1, 2, 3)', mode='eval'), indent=4)) Expression( body=Tuple( elts=[ Constant(value=1), Constant(value=2), Constant(value=3)])) ::: ::::

:::: Set(elts) A set. elts holds a list of nodes representing the set's elements.

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

:::: {.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.

::: doctest >>> print(ast.dump(ast.parse('{"a":1, **d}', mode='eval'), indent=4)) Expression( body=Dict( keys=[ Constant(value='a'), None], values=[ Constant(value=1), Name(id='d')])) ::: ::::

Variables

::: {.Name(id, .ctx)} A variable name. id holds the name as a string, and ctx is one of the following types. :::

:::: {.Load() .Store() .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.

::: doctest >>> print(ast.dump(ast.parse('a'), indent=4)) Module( body=[ Expr( value=Name(id='a'))])

>>> print(ast.dump(ast.parse('a = 1'), indent=4)) Module( body=[ Assign( targets=[ Name(id='a', ctx=Store())], value=Constant(value=1))])

>>> print(ast.dump(ast.parse('del a'), indent=4)) Module( body=[ Delete( targets=[ Name(id='a', ctx=Del())])]) ::: ::::

:::: {.Starred(value, .ctx)} A *var variable reference. value holds the variable, typically a Name{.interpreted-text role="class"} node. This type must be used when building a Call{.interpreted-text role="class"} node with *args.

::: doctest >>> print(ast.dump(ast.parse('a, *b = it'), indent=4)) Module( body=[ Assign( targets=[ Tuple( elts=[ Name(id='a', ctx=Store()), Starred( value=Name(id='b', ctx=Store()), ctx=Store())], ctx=Store())], value=Name(id='it'))]) ::: ::::

Expressions {#ast-expressions}

:::: 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{.interpreted-text role="class"}, a Name{.interpreted-text role="class"}, a Lambda{.interpreted-text role="class"}, a Yield{.interpreted-text role="class"} or YieldFrom{.interpreted-text role="class"} node.

::: doctest >>> print(ast.dump(ast.parse('-a'), indent=4)) Module( body=[ Expr( value=UnaryOp( op=USub(), operand=Name(id='a')))]) ::: ::::

::: {.UnaryOp(op, .operand)} A unary operation. op is the operator, and operand any expression node. :::

:::: {.UAdd .USub .Not .Invert} Unary operator tokens. Not{.interpreted-text role="class"} is the not keyword, Invert{.interpreted-text role="class"} is the ~ operator.

::: doctest >>> print(ast.dump(ast.parse('not x', mode='eval'), indent=4)) Expression( body=UnaryOp( op=Not(), operand=Name(id='x'))) ::: ::::

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

::: doctest >>> print(ast.dump(ast.parse('x + y', mode='eval'), indent=4)) Expression( body=BinOp( left=Name(id='x'), op=Add(), right=Name(id='y'))) ::: ::::

::: {.Add .Sub .Mult .Div .FloorDiv .Mod .Pow .LShift .RShift .BitOr .BitXor .BitAnd .MatMult} Binary operator tokens. :::

:::: {.BoolOp(op, .values)} A boolean operation, 'or' or 'and'. op is Or{.interpreted-text role="class"} or And{.interpreted-text role="class"}. 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{.interpreted-text role="class"}.

::: doctest >>> print(ast.dump(ast.parse('x or y', mode='eval'), indent=4)) Expression( body=BoolOp( op=Or(), values=[ Name(id='x'), Name(id='y')])) ::: ::::

::: {.And .Or} Boolean operator tokens. :::

:::: {.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.

::: doctest >>> print(ast.dump(ast.parse('1 <= a < 10', mode='eval'), indent=4)) Expression( body=Compare( left=Constant(value=1), ops=[ LtE(), Lt()], comparators=[ Name(id='a'), Constant(value=10)])) ::: ::::

::: {.Eq .NotEq .Lt .LtE .Gt .GtE .Is .IsNot .In .NotIn} Comparison operator tokens. :::

:::: {.Call(func, .args, .keywords)} A function call. func is the function, which will often be a Name{.interpreted-text role="class"} or Attribute{.interpreted-text role="class"} object. Of the arguments:

  • args holds a list of the arguments passed by position.
  • keywords holds a list of .keyword{.interpreted-text role="class"} objects representing arguments passed by keyword.

The args and keywords arguments are optional and default to empty lists.

::: doctest >>> print(ast.dump(ast.parse('func(a, b=c, d,*e)', mode='eval'), indent=4)) Expression( body=Call( func=Name(id='func'), args=[ Name(id='a'), Starred( value=Name(id='d'))], keywords=[ keyword( arg='b', value=Name(id='c')), keyword( value=Name(id='e'))])) ::: ::::

::: {.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. :::

:::: {.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{.interpreted-text role="class"} nodes.

::: doctest >>> print(ast.dump(ast.parse('a if b else c', mode='eval'), indent=4)) Expression( body=IfExp( test=Name(id='b'), body=Name(id='a'), orelse=Name(id='c'))) ::: ::::

:::: {.Attribute(value, .attr, .ctx)} Attribute access, e.g. d.keys. value is a node, typically a Name{.interpreted-text role="class"}. attr is a bare string giving the name of the attribute, and ctx is Load{.interpreted-text role="class"}, Store{.interpreted-text role="class"} or Del{.interpreted-text role="class"} according to how the attribute is acted on.

::: doctest >>> print(ast.dump(ast.parse('snake.colour', mode='eval'), indent=4)) Expression( body=Attribute( value=Name(id='snake'), attr='colour')) ::: ::::

::::: {.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{.interpreted-text role="class"} node in which the first argument can be multiple nodes, in this case both target and value must be single nodes.

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

::: versionadded 3.8 ::: :::::

Subscripting

:::: {.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{.interpreted-text role="class"} and contain a Slice{.interpreted-text role="class"}. ctx is Load{.interpreted-text role="class"}, Store{.interpreted-text role="class"} or Del{.interpreted-text role="class"} according to the action performed with the subscript.

::: doctest >>> print(ast.dump(ast.parse('l[1:2, 3]', mode='eval'), indent=4)) Expression( body=Subscript( value=Name(id='l'), slice=Tuple( elts=[ Slice( lower=Constant(value=1), upper=Constant(value=2)), Constant(value=3)]))) ::: ::::

:::: {.Slice(lower, .upper, .step)} Regular slicing (on the form lower:upper or lower:upper:step). Can occur only inside the slice field of Subscript{.interpreted-text role="class"}, either directly or as an element of Tuple{.interpreted-text role="class"}.

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

Comprehensions

:::: {.ListComp(elt, .generators) .SetComp(elt, .generators) .GeneratorExp(elt, .generators) .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{.interpreted-text role="class"} nodes.

::: doctest >>> print(ast.dump( ... ast.parse('[x for x in numbers]', mode='eval'), ... indent=4, ... )) Expression( body=ListComp( elt=Name(id='x'), generators=[ comprehension( target=Name(id='x', ctx=Store()), iter=Name(id='numbers'), is_async=0)])) >>> print(ast.dump( ... ast.parse('{x: x**2 for x in numbers}', mode='eval'), ... indent=4, ... )) Expression( body=DictComp( key=Name(id='x'), value=BinOp( left=Name(id='x'), op=Pow(), right=Constant(value=2)), generators=[ comprehension( target=Name(id='x', ctx=Store()), iter=Name(id='numbers'), is_async=0)])) >>> print(ast.dump( ... ast.parse('{x for x in numbers}', mode='eval'), ... indent=4, ... )) Expression( body=SetComp( elt=Name(id='x'), generators=[ comprehension( target=Name(id='x', ctx=Store()), iter=Name(id='numbers'), is_async=0)])) ::: ::::

:::: {.comprehension(target, .iter, .ifs, .is_async)} One for clause in a comprehension. target is the reference to use for each element - typically a Name{.interpreted-text role="class"} or Tuple{.interpreted-text role="class"} 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).

::: doctest >>> print(ast.dump(ast.parse('[ord(c) for line in file for c in line]', mode='eval'), ... indent=4)) # Multiple comprehensions in one. Expression( body=ListComp( elt=Call( func=Name(id='ord'), args=[ Name(id='c')]), generators=[ comprehension( target=Name(id='line', ctx=Store()), iter=Name(id='file'), is_async=0), comprehension( target=Name(id='c', ctx=Store()), iter=Name(id='line'), is_async=0)]))

>>> print(ast.dump(ast.parse('(n**2 for n in it if n>5 if n<10)', mode='eval'), ... indent=4)) # generator comprehension Expression( body=GeneratorExp( elt=BinOp( left=Name(id='n'), op=Pow(), right=Constant(value=2)), generators=[ comprehension( target=Name(id='n', ctx=Store()), iter=Name(id='it'), ifs=[ Compare( left=Name(id='n'), ops=[ Gt()], comparators=[ Constant(value=5)]), Compare( left=Name(id='n'), ops=[ Lt()], comparators=[ Constant(value=10)])], is_async=0)]))

>>> print(ast.dump(ast.parse('[i async for i in soc]', mode='eval'), ... indent=4)) # Async comprehension Expression( body=ListComp( elt=Name(id='i'), generators=[ comprehension( target=Name(id='i', ctx=Store()), iter=Name(id='soc'), is_async=1)])) ::: ::::

Statements {#ast-statements}

::::: {.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{.interpreted-text role="class"} or List{.interpreted-text role="class"} within targets.

::: attribute type_comment

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

::: doctest >>> print(ast.dump(ast.parse('a = b = 1'), indent=4)) # Multiple assignment Module( body=[ Assign( targets=[ Name(id='a', ctx=Store()), Name(id='b', ctx=Store())], value=Constant(value=1))])

>>> print(ast.dump(ast.parse('a,b = c'), indent=4)) # Unpacking Module( body=[ Assign( targets=[ Tuple( elts=[ Name(id='a', ctx=Store()), Name(id='b', ctx=Store())], ctx=Store())], value=Name(id='c'))]) ::: :::::

:::: {.AnnAssign(target, .annotation, .value, .simple)} An assignment with a type annotation. target is a single node and can be a Name{.interpreted-text role="class"}, an Attribute{.interpreted-text role="class"} or a Subscript{.interpreted-text role="class"}. annotation is the annotation, such as a Constant{.interpreted-text role="class"} or Name{.interpreted-text role="class"} node. value is a single optional node.

simple is always either 0 (indicating a "complex" target) or 1 (indicating a "simple" target). A "simple" target consists solely of a Name{.interpreted-text role="class"} node that does not appear between parentheses; all other targets are considered complex. Only simple targets appear in the ~object.__annotations__{.interpreted-text role="attr"} dictionary of modules and classes.

::: doctest >>> print(ast.dump(ast.parse('c: int'), indent=4)) Module( body=[ AnnAssign( target=Name(id='c', ctx=Store()), annotation=Name(id='int'), simple=1)])

>>> print(ast.dump(ast.parse('(a): int = 1'), indent=4)) # Annotation with parenthesis Module( body=[ AnnAssign( target=Name(id='a', ctx=Store()), annotation=Name(id='int'), value=Constant(value=1), simple=0)])

>>> print(ast.dump(ast.parse('a.b: int'), indent=4)) # Attribute annotation Module( body=[ AnnAssign( target=Attribute( value=Name(id='a'), attr='b', ctx=Store()), annotation=Name(id='int'), simple=0)])

>>> print(ast.dump(ast.parse('a[1]: int'), indent=4)) # Subscript annotation Module( body=[ AnnAssign( target=Subscript( value=Name(id='a'), slice=Constant(value=1), ctx=Store()), annotation=Name(id='int'), simple=0)]) ::: ::::

:::: {.AugAssign(target, .op, .value)} Augmented assignment, such as a += 1. In the following example, target is a Name{.interpreted-text role="class"} node for x (with the Store{.interpreted-text role="class"} context), op is Add{.interpreted-text role="class"}, and value is a Constant{.interpreted-text role="class"} with value for 1.

The target attribute cannot be of class Tuple{.interpreted-text role="class"} or List{.interpreted-text role="class"}, unlike the targets of Assign{.interpreted-text role="class"}.

::: doctest >>> print(ast.dump(ast.parse('x += 2'), indent=4)) Module( body=[ AugAssign( target=Name(id='x', ctx=Store()), op=Add(), value=Constant(value=2))]) ::: ::::

:::: {.Raise(exc, .cause)} A raise statement. exc is the exception object to be raised, normally a Call{.interpreted-text role="class"} or Name{.interpreted-text role="class"}, or None for a standalone raise. cause is the optional part for y in raise x from y.

::: doctest >>> print(ast.dump(ast.parse('raise x from y'), indent=4)) Module( body=[ Raise( exc=Name(id='x'), cause=Name(id='y'))]) ::: ::::

:::: {.Assert(test, .msg)} An assertion. test holds the condition, such as a Compare{.interpreted-text role="class"} node. msg holds the failure message.

::: doctest >>> print(ast.dump(ast.parse('assert x,y'), indent=4)) Module( body=[ Assert( test=Name(id='x'), msg=Name(id='y'))]) ::: ::::

:::: Delete(targets) Represents a del statement. targets is a list of nodes, such as Name{.interpreted-text role="class"}, Attribute{.interpreted-text role="class"} or Subscript{.interpreted-text role="class"} nodes.

::: doctest >>> print(ast.dump(ast.parse('del x,y,z'), indent=4)) Module( body=[ Delete( targets=[ Name(id='x', ctx=Del()), Name(id='y', ctx=Del()), Name(id='z', ctx=Del())])]) ::: ::::

:::: Pass() A pass statement.

::: doctest >>> print(ast.dump(ast.parse('pass'), indent=4)) Module( body=[ Pass()]) ::: ::::

::::: {.TypeAlias(name, .type_params, .value)} A type alias <type-aliases>{.interpreted-text role="ref"} created through the type{.interpreted-text role="keyword"} statement. name is the name of the alias, type_params is a list of type parameters <ast-type-params>{.interpreted-text role="ref"}, and value is the value of the type alias.

::: doctest >>> print(ast.dump(ast.parse('type Alias = int'), indent=4)) Module( body=[ TypeAlias( name=Name(id='Alias', ctx=Store()), value=Name(id='int'))]) :::

::: versionadded 3.12 ::: :::::

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

Imports

:::: Import(names) An import statement. names is a list of alias{.interpreted-text role="class"} nodes.

::: doctest >>> print(ast.dump(ast.parse('import x,y,z'), indent=4)) Module( body=[ Import( names=[ alias(name='x'), alias(name='y'), alias(name='z')], is_lazy=0)]) ::: ::::

:::: {.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).

::: doctest >>> print(ast.dump(ast.parse('from y import x,y,z'), indent=4)) Module( body=[ ImportFrom( module='y', names=[ alias(name='x'), alias(name='y'), alias(name='z')], level=0, is_lazy=0)]) ::: ::::

:::: {.alias(name, .asname)} Both parameters are raw strings of the names. asname can be None if the regular name is to be used.

::: doctest >>> print(ast.dump(ast.parse('from ..foo.bar import a as b, c'), indent=4)) Module( body=[ ImportFrom( module='foo.bar', names=[ alias(name='a', asname='b'), alias(name='c')], level=2, is_lazy=0)]) ::: ::::

Control flow

:::: note ::: title Note :::

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

:::: {.If(test, .body, .orelse)} An if statement. test holds a single node, such as a Compare{.interpreted-text role="class"} 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{.interpreted-text role="class"} nodes within the orelse section of the previous one.

::: doctest >>> print(ast.dump(ast.parse(""" ... if x: ... ... ... elif y: ... ... ... else: ... ... ... """), indent=4)) Module( body=[ If( test=Name(id='x'), body=[ Expr( value=Constant(value=Ellipsis))], orelse=[ If( test=Name(id='y'), body=[ Expr( value=Constant(value=Ellipsis))], orelse=[ Expr( value=Constant(value=Ellipsis))])])]) ::: ::::

::::: {.For(target, .iter, .body, .orelse, .type_comment)} A for loop. target holds the variable(s) the loop assigns to, as a single Name{.interpreted-text role="class"}, Tuple{.interpreted-text role="class"}, List{.interpreted-text role="class"}, Attribute{.interpreted-text role="class"} or Subscript{.interpreted-text role="class"} 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.

::: attribute type_comment

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

::: doctest >>> print(ast.dump(ast.parse(""" ... for x in y: ... ... ... else: ... ... ... """), indent=4)) Module( body=[ For( target=Name(id='x', ctx=Store()), iter=Name(id='y'), body=[ Expr( value=Constant(value=Ellipsis))], orelse=[ Expr( value=Constant(value=Ellipsis))])]) ::: :::::

:::: {.While(test, .body, .orelse)} A while loop. test holds the condition, such as a Compare{.interpreted-text role="class"} node.

::: doctest >>> print(ast.dump(ast.parse(""" ... while x: ... ... ... else: ... ... ... """), indent=4)) Module( body=[ While( test=Name(id='x'), body=[ Expr( value=Constant(value=Ellipsis))], orelse=[ Expr( value=Constant(value=Ellipsis))])]) ::: ::::

:::: {.Break .Continue} The break and continue statements.

::: doctest >>> print(ast.dump(ast.parse("""... for a in b: ... if a > 5: ... break ... else: ... continue ... ... """), indent=4)) Module( body=[ For( target=Name(id='a', ctx=Store()), iter=Name(id='b'), body=[ If( test=Compare( left=Name(id='a'), ops=[ Gt()], comparators=[ Constant(value=5)]), body=[ Break()], orelse=[ Continue()])])]) ::: ::::

:::: {.Try(body, .handlers, .orelse, .finalbody)} try blocks. All attributes are list of nodes to execute, except for handlers, which is a list of ExceptHandler{.interpreted-text role="class"} nodes.

::: doctest >>> print(ast.dump(ast.parse(""" ... try: ... ... ... except Exception: ... ... ... except OtherException as e: ... ... ... else: ... ... ... finally: ... ... ... """), indent=4)) Module( body=[ Try( body=[ Expr( value=Constant(value=Ellipsis))], handlers=[ ExceptHandler( type=Name(id='Exception'), body=[ Expr( value=Constant(value=Ellipsis))]), ExceptHandler( type=Name(id='OtherException'), name='e', body=[ Expr( value=Constant(value=Ellipsis))])], orelse=[ Expr( value=Constant(value=Ellipsis))], finalbody=[ Expr( value=Constant(value=Ellipsis))])]) ::: ::::

::::: {.TryStar(body, .handlers, .orelse, .finalbody)} try blocks which are followed by except* clauses. The attributes are the same as for Try{.interpreted-text role="class"} but the ExceptHandler{.interpreted-text role="class"} nodes in handlers are interpreted as except* blocks rather then except.

::: doctest >>> print(ast.dump(ast.parse(""" ... try: ... ... ... except* Exception: ... ... ... """), indent=4)) Module( body=[ TryStar( body=[ Expr( value=Constant(value=Ellipsis))], handlers=[ ExceptHandler( type=Name(id='Exception'), body=[ Expr( value=Constant(value=Ellipsis))])])]) :::

::: versionadded 3.11 ::: :::::

:::: {.ExceptHandler(type, .name, .body)} A single except clause. type is the exception type it will match, typically a Name{.interpreted-text role="class"} 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.

::: doctest >>> print(ast.dump(ast.parse("""... try: ... a + 1 ... except TypeError: ... pass ... """), indent=4)) Module( body=[ Try( body=[ Expr( value=BinOp( left=Name(id='a'), op=Add(), right=Constant(value=1)))], handlers=[ ExceptHandler( type=Name(id='TypeError'), body=[ Pass()])])]) ::: ::::

:::: {.With(items, .body, .type_comment)} A with block. items is a list of withitem{.interpreted-text role="class"} nodes representing the context managers, and body is the indented block inside the context.

::: attribute type_comment

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

:::: {.withitem(context_expr, .optional_vars)} A single context manager in a with block. context_expr is the context manager, often a Call{.interpreted-text role="class"} node. optional_vars is a Name{.interpreted-text role="class"}, Tuple{.interpreted-text role="class"} or List{.interpreted-text role="class"} for the as foo part, or None if that isn't used.

::: doctest >>> print(ast.dump(ast.parse("""... with a as b, c as d: ... something(b, d) ... """), indent=4)) Module( body=[ With( items=[ withitem( context_expr=Name(id='a'), optional_vars=Name(id='b', ctx=Store())), withitem( context_expr=Name(id='c'), optional_vars=Name(id='d', ctx=Store()))], body=[ Expr( value=Call( func=Name(id='something'), args=[ Name(id='b'), Name(id='d')]))])]) ::: ::::

Pattern matching

:::: {.Match(subject, .cases)} A match statement. subject holds the subject of the match (the object that is being matched against the cases) and cases contains an iterable of match_case{.interpreted-text role="class"} nodes with the different cases.

::: versionadded 3.10 ::: ::::

::::: {.match_case(pattern, .guard, .body)} A single case pattern in a match statement. pattern contains the match pattern that the subject will be matched against. Note that the AST{.interpreted-text role="class"} nodes produced for patterns differ from those produced for expressions, even when they share the same syntax.

The guard attribute contains an expression that will be evaluated if the pattern matches the subject.

body contains a list of nodes to execute if the pattern matches and the result of evaluating the guard expression is true.

::: doctest >>> print(ast.dump(ast.parse(""" ... match x: ... case [x] if x>0: ... ... ... case tuple(): ... ... ... """), indent=4)) Module( body=[ Match( subject=Name(id='x'), cases=[ match_case( pattern=MatchSequence( patterns=[ MatchAs(name='x')]), guard=Compare( left=Name(id='x'), ops=[ Gt()], comparators=[ Constant(value=0)]), body=[ Expr( value=Constant(value=Ellipsis))]), match_case( pattern=MatchClass( cls=Name(id='tuple')), body=[ Expr( value=Constant(value=Ellipsis))])])]) :::

::: versionadded 3.10 ::: :::::

::::: MatchValue(value) A match literal or value pattern that compares by equality. value is an expression node. Permitted value nodes are restricted as described in the match statement documentation. This pattern succeeds if the match subject is equal to the evaluated value.

::: doctest >>> print(ast.dump(ast.parse(""" ... match x: ... case "Relevant": ... ... ... """), indent=4)) Module( body=[ Match( subject=Name(id='x'), cases=[ match_case( pattern=MatchValue( value=Constant(value='Relevant')), body=[ Expr( value=Constant(value=Ellipsis))])])]) :::

::: versionadded 3.10 ::: :::::

::::: MatchSingleton(value) A match literal pattern that compares by identity. value is the singleton to be compared against: None, True, or False. This pattern succeeds if the match subject is the given constant.

::: doctest >>> print(ast.dump(ast.parse(""" ... match x: ... case None: ... ... ... """), indent=4)) Module( body=[ Match( subject=Name(id='x'), cases=[ match_case( pattern=MatchSingleton(value=None), body=[ Expr( value=Constant(value=Ellipsis))])])]) :::

::: versionadded 3.10 ::: :::::

::::: MatchSequence(patterns) A match sequence pattern. patterns contains the patterns to be matched against the subject elements if the subject is a sequence. Matches a variable length sequence if one of the subpatterns is a MatchStar node, otherwise matches a fixed length sequence.

::: doctest >>> print(ast.dump(ast.parse(""" ... match x: ... case [1, 2]: ... ... ... """), indent=4)) Module( body=[ Match( subject=Name(id='x'), cases=[ match_case( pattern=MatchSequence( patterns=[ MatchValue( value=Constant(value=1)), MatchValue( value=Constant(value=2))]), body=[ Expr( value=Constant(value=Ellipsis))])])]) :::

::: versionadded 3.10 ::: :::::

::::: MatchStar(name) Matches the rest of the sequence in a variable length match sequence pattern. If name is not None, a list containing the remaining sequence elements is bound to that name if the overall sequence pattern is successful.

::: doctest >>> print(ast.dump(ast.parse(""" ... match x: ... case [1, 2, rest]: ... ... ... case [_]: ... ... ... """), indent=4)) Module( body=[ Match( subject=Name(id='x'), cases=[ match_case( pattern=MatchSequence( patterns=[ MatchValue( value=Constant(value=1)), MatchValue( value=Constant(value=2)), MatchStar(name='rest')]), body=[ Expr( value=Constant(value=Ellipsis))]), match_case( pattern=MatchSequence( patterns=[ MatchStar()]), body=[ Expr( value=Constant(value=Ellipsis))])])]) :::

::: versionadded 3.10 ::: :::::

::::: {.MatchMapping(keys, .patterns, .rest)} A match mapping pattern. keys is a sequence of expression nodes. patterns is a corresponding sequence of pattern nodes. rest is an optional name that can be specified to capture the remaining mapping elements. Permitted key expressions are restricted as described in the match statement documentation.

This pattern succeeds if the subject is a mapping, all evaluated key expressions are present in the mapping, and the value corresponding to each key matches the corresponding subpattern. If rest is not None, a dict containing the remaining mapping elements is bound to that name if the overall mapping pattern is successful.

::: doctest >>> print(ast.dump(ast.parse(""" ... match x: ... case {1: _, 2: _}: ... ... ... case {**rest}: ... ... ... """), indent=4)) Module( body=[ Match( subject=Name(id='x'), cases=[ match_case( pattern=MatchMapping( keys=[ Constant(value=1), Constant(value=2)], patterns=[ MatchAs(), MatchAs()]), body=[ Expr( value=Constant(value=Ellipsis))]), match_case( pattern=MatchMapping(rest='rest'), body=[ Expr( value=Constant(value=Ellipsis))])])]) :::

::: versionadded 3.10 ::: :::::

::::: {.MatchClass(cls, .patterns, .kwd_attrs, .kwd_patterns)} A match class pattern. cls is an expression giving the nominal class to be matched. patterns is a sequence of pattern nodes to be matched against the class defined sequence of pattern matching attributes. kwd_attrs is a sequence of additional attributes to be matched (specified as keyword arguments in the class pattern), kwd_patterns are the corresponding patterns (specified as keyword values in the class pattern).

This pattern succeeds if the subject is an instance of the nominated class, all positional patterns match the corresponding class-defined attributes, and any specified keyword attributes match their corresponding pattern.

Note: classes may define a property that returns self in order to match a pattern node against the instance being matched. Several builtin types are also matched that way, as described in the match statement documentation.

::: doctest >>> print(ast.dump(ast.parse(""" ... match x: ... case Point2D(0, 0): ... ... ... case Point3D(x=0, y=0, z=0): ... ... ... """), indent=4)) Module( body=[ Match( subject=Name(id='x'), cases=[ match_case( pattern=MatchClass( cls=Name(id='Point2D'), patterns=[ MatchValue( value=Constant(value=0)), MatchValue( value=Constant(value=0))]), body=[ Expr( value=Constant(value=Ellipsis))]), match_case( pattern=MatchClass( cls=Name(id='Point3D'), kwd_attrs=[ 'x', 'y', 'z'], kwd_patterns=[ MatchValue( value=Constant(value=0)), MatchValue( value=Constant(value=0)), MatchValue( value=Constant(value=0))]), body=[ Expr( value=Constant(value=Ellipsis))])])]) :::

::: versionadded 3.10 ::: :::::

::::: {.MatchAs(pattern, .name)} A match "as-pattern", capture pattern or wildcard pattern. pattern contains the match pattern that the subject will be matched against. If the pattern is None, the node represents a capture pattern (i.e a bare name) and will always succeed.

The name attribute contains the name that will be bound if the pattern is successful. If name is None, pattern must also be None and the node represents the wildcard pattern.

::: doctest >>> print(ast.dump(ast.parse(""" ... match x: ... case [x] as y: ... ... ... case _: ... ... ... """), indent=4)) Module( body=[ Match( subject=Name(id='x'), cases=[ match_case( pattern=MatchAs( pattern=MatchSequence( patterns=[ MatchAs(name='x')]), name='y'), body=[ Expr( value=Constant(value=Ellipsis))]), match_case( pattern=MatchAs(), body=[ Expr( value=Constant(value=Ellipsis))])])]) :::

::: versionadded 3.10 ::: :::::

::::: MatchOr(patterns) A match "or-pattern". An or-pattern matches each of its subpatterns in turn to the subject, until one succeeds. The or-pattern is then deemed to succeed. If none of the subpatterns succeed the or-pattern fails. The patterns attribute contains a list of match pattern nodes that will be matched against the subject.

::: doctest >>> print(ast.dump(ast.parse(""" ... match x: ... case [x] | (y): ... ... ... """), indent=4)) Module( body=[ Match( subject=Name(id='x'), cases=[ match_case( pattern=MatchOr( patterns=[ MatchSequence( patterns=[ MatchAs(name='x')]), MatchAs(name='y')]), body=[ Expr( value=Constant(value=Ellipsis))])])]) :::

::: versionadded 3.10 ::: :::::

Type annotations

::::::: {.TypeIgnore(lineno, .tag)} A # type: ignore comment located at lineno. tag is the optional tag specified by the form # type: ignore <tag>.

::: doctest >>> print(ast.dump(ast.parse('x = 1 # type: ignore', type_comments=True), indent=4)) Module( body=[ Assign( targets=[ Name(id='x', ctx=Store())], value=Constant(value=1))], type_ignores=[ TypeIgnore(lineno=1, tag='')]) >>> print(ast.dump(ast.parse('x: bool = 1 # type: ignore[assignment]', type_comments=True), indent=4)) Module( body=[ AnnAssign( target=Name(id='x', ctx=Store()), annotation=Name(id='bool'), value=Constant(value=1), simple=1)], type_ignores=[ TypeIgnore(lineno=1, tag='[assignment]')]) :::

:::: note ::: title Note :::

!TypeIgnore{.interpreted-text role="class"} nodes are not generated when the type_comments parameter is set to False (default). See ast.parse{.interpreted-text role="func"} for more details. ::::

::: versionadded 3.8 ::: :::::::

Type parameters {#ast-type-params}

Type parameters <type-params>{.interpreted-text role="ref"} can exist on classes, functions, and type aliases.

:::::: {.TypeVar(name, .bound, .default_value)} A typing.TypeVar{.interpreted-text role="class"}. name is the name of the type variable. bound is the bound or constraints, if any. If bound is a Tuple{.interpreted-text role="class"}, it represents constraints; otherwise it represents the bound. default_value is the default value; if the !TypeVar{.interpreted-text role="class"} has no default, this attribute will be set to None.

::: doctest >>> print(ast.dump(ast.parse("type Alias[T: int = bool] = list[T]"), indent=4)) Module( body=[ TypeAlias( name=Name(id='Alias', ctx=Store()), type_params=[ TypeVar( name='T', bound=Name(id='int'), default_value=Name(id='bool'))], value=Subscript( value=Name(id='list'), slice=Name(id='T')))]) :::

::: versionadded 3.12 :::

::: versionchanged 3.13 Added the default_value parameter. ::: ::::::

:::::: {.ParamSpec(name, .default_value)} A typing.ParamSpec{.interpreted-text role="class"}. name is the name of the parameter specification. default_value is the default value; if the !ParamSpec{.interpreted-text role="class"} has no default, this attribute will be set to None.

::: doctest >>> print(ast.dump(ast.parse("type Alias[**P = [int, str]] = Callable[P, int]"), indent=4)) Module( body=[ TypeAlias( name=Name(id='Alias', ctx=Store()), type_params=[ ParamSpec( name='P', default_value=List( elts=[ Name(id='int'), Name(id='str')]))], value=Subscript( value=Name(id='Callable'), slice=Tuple( elts=[ Name(id='P'), Name(id='int')])))]) :::

::: versionadded 3.12 :::

::: versionchanged 3.13 Added the default_value parameter. ::: ::::::

:::::: {.TypeVarTuple(name, .default_value)} A typing.TypeVarTuple{.interpreted-text role="class"}. name is the name of the type variable tuple. default_value is the default value; if the !TypeVarTuple{.interpreted-text role="class"} has no default, this attribute will be set to None.

::: doctest >>> print(ast.dump(ast.parse("type Alias[Ts = ()] = tuple[Ts]"), indent=4)) Module( body=[ TypeAlias( name=Name(id='Alias', ctx=Store()), type_params=[ TypeVarTuple(name='Ts', default_value=Tuple())], value=Subscript( value=Name(id='tuple'), slice=Tuple( elts=[ Starred( value=Name(id='Ts'))])))]) :::

::: versionadded 3.12 :::

::: versionchanged 3.13 Added the default_value parameter. ::: ::::::

Function and class definitions

::::: {.FunctionDef(name, .args, .body, .decorator_list, .returns, .type_comment, .type_params)} A function definition.

  • name is a raw string of the function name.
  • args is an arguments{.interpreted-text role="class"} 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_params is a list of type parameters <ast-type-params>{.interpreted-text role="ref"}.

::: attribute type_comment

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

::: versionchanged 3.12 Added type_params. ::: :::::

:::: {.Lambda(args, .body)} lambda is a minimal function definition that can be used inside an expression. Unlike FunctionDef{.interpreted-text role="class"}, body holds a single node.

::: doctest >>> print(ast.dump(ast.parse('lambda x,y: ...'), indent=4)) Module( body=[ Expr( value=Lambda( args=arguments( args=[ arg(arg='x'), arg(arg='y')]), body=Constant(value=Ellipsis)))]) ::: ::::

::: {.arguments(posonlyargs, .args, .vararg, .kwonlyargs, .kw_defaults, .kwarg, .defaults)} The arguments for a function.

  • posonlyargs, args and kwonlyargs are lists of arg{.interpreted-text role="class"} nodes.
  • vararg and kwarg are single arg{.interpreted-text role="class"} 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. :::

::::: {.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 Name{.interpreted-text role="class"} node.

::: attribute type_comment

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

::: doctest >>> print(ast.dump(ast.parse("""... @decorator1 ... @decorator2 ... def f(a: 'annotation', b=1, c=2, d, e, f=3,*g) -> 'return annotation': ... pass ... """), indent=4)) Module( body=[ FunctionDef( name='f', args=arguments( args=[ arg( arg='a', annotation=Constant(value='annotation')), arg(arg='b'), arg(arg='c')], vararg=arg(arg='d'), kwonlyargs=[ arg(arg='e'), arg(arg='f')], kw_defaults=[ None, Constant(value=3)], kwarg=arg(arg='g'), defaults=[ Constant(value=1), Constant(value=2)]), body=[ Pass()], decorator_list=[ Name(id='decorator1'), Name(id='decorator2')], returns=Constant(value='return annotation'))]) ::: :::::

:::: Return(value) A return statement.

::: doctest >>> print(ast.dump(ast.parse('return 4'), indent=4)) Module( body=[ Return( value=Constant(value=4))]) ::: ::::

:::: {.Yield(value) .YieldFrom(value)} A yield or yield from expression. Because these are expressions, they must be wrapped in an Expr{.interpreted-text role="class"} node if the value sent back is not used.

::: doctest >>> print(ast.dump(ast.parse('yield x'), indent=4)) Module( body=[ Expr( value=Yield( value=Name(id='x')))])

>>> print(ast.dump(ast.parse('yield from x'), indent=4)) Module( body=[ Expr( value=YieldFrom( value=Name(id='x')))]) ::: ::::

:::: {.Global(names) .Nonlocal(names)} global and nonlocal statements. names is a list of raw strings.

::: doctest >>> print(ast.dump(ast.parse('global x,y,z'), indent=4)) Module( body=[ Global( names=[ 'x', 'y', 'z'])])

>>> print(ast.dump(ast.parse('nonlocal x,y,z'), indent=4)) Module( body=[ Nonlocal( names=[ 'x', 'y', 'z'])]) ::: ::::

::::: {.ClassDef(name, .bases, .keywords, .body, .decorator_list, .type_params)} 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{.interpreted-text role="class"} nodes, principally for 'metaclass'. Other keywords will be passed to the metaclass, as per 3115{.interpreted-text role="pep"}.
  • body is a list of nodes representing the code within the class definition.
  • decorator_list is a list of nodes, as in FunctionDef{.interpreted-text role="class"}.
  • type_params is a list of type parameters <ast-type-params>{.interpreted-text role="ref"}.

::: doctest >>> print(ast.dump(ast.parse("""... @decorator1 ... @decorator2 ... class Foo(base1, base2, metaclass=meta): ... pass ... """), indent=4)) Module( body=[ ClassDef( name='Foo', bases=[ Name(id='base1'), Name(id='base2')], keywords=[ keyword( arg='metaclass', value=Name(id='meta'))], body=[ Pass()], decorator_list=[ Name(id='decorator1'), Name(id='decorator2')])]) :::

::: versionchanged 3.12 Added type_params. ::: :::::

Async and await

:::: {.AsyncFunctionDef(name, .args, .body, .decorator_list, .returns, .type_comment, .type_params)} An async def function definition. Has the same fields as FunctionDef{.interpreted-text role="class"}.

::: versionchanged 3.12 Added type_params. ::: ::::

::: Await(value) An await expression. value is what it waits for. Only valid in the body of an AsyncFunctionDef{.interpreted-text role="class"}. :::

::: doctest >>> print(ast.dump(ast.parse("""... async def f(): ... await other_func() ... """), indent=4)) Module( body=[ AsyncFunctionDef( name='f', args=arguments(), body=[ Expr( value=Await( value=Call( func=Name(id='other_func'))))])]) :::

::: {.AsyncFor(target, .iter, .body, .orelse, .type_comment) .AsyncWith(items, .body, .type_comment)} async for loops and async with context managers. They have the same fields as For{.interpreted-text role="class"} and With{.interpreted-text role="class"}, respectively. Only valid in the body of an AsyncFunctionDef{.interpreted-text role="class"}. :::

:::: note ::: title Note :::

When a string is parsed by ast.parse{.interpreted-text role="func"}, operator nodes (subclasses of ast.operator{.interpreted-text role="class"}, ast.unaryop{.interpreted-text role="class"}, ast.cmpop{.interpreted-text role="class"}, ast.boolop{.interpreted-text role="class"} and ast.expr_context{.interpreted-text role="class"}) on the returned tree will be singletons. Changes to one will be reflected in all other occurrences of the same value (for example, ast.Add{.interpreted-text role="class"}). ::::

!ast{.interpreted-text role="mod"} helpers

Apart from the node classes, the !ast{.interpreted-text role="mod"} module defines these utility functions and classes for traversing abstract syntax trees:

:::::::::: function parse(source, filename='<unknown>', mode='exec', *, type_comments=False, feature_version=None, optimize=-1, module=None)

Parse the source into an AST node. Equivalent to compile(source, filename, mode, flags=FLAGS_VALUE, optimize=optimize, module=module), where FLAGS_VALUE is ast.PyCF_ONLY_AST if optimize <= 0 and ast.PyCF_OPTIMIZED_AST otherwise.

If type_comments=True is given, the parser is modified to check and return type comments as specified by 484{.interpreted-text role="pep"} and 526{.interpreted-text role="pep"}. This is equivalent to adding ast.PyCF_TYPE_COMMENTS{.interpreted-text role="data"} to the flags passed to compile{.interpreted-text role="func"}. 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{.interpreted-text role="class"} (otherwise it is always an empty list).

In addition, if mode is 'func_type', the input syntax is modified to correspond to 484{.interpreted-text role="pep"} "signature type comments", e.g. (str, int) -> List[str].

Setting feature_version to a tuple (major, minor) will result in a "best-effort" attempt to parse using that Python version's grammar. For example, setting feature_version=(3, 9) will attempt to disallow parsing of match{.interpreted-text role="keyword"} statements. Currently major must equal to 3. The lowest supported version is (3, 7) (and this may increase in future Python versions); the highest is sys.version_info[0:2]. "Best-effort" attempt means there is no guarantee that the parse (or success of the parse) is the same as when run on the Python version corresponding to feature_version.

If source contains a null character (\0), ValueError{.interpreted-text role="exc"} is raised.

:::: warning ::: title Warning :::

Note that successfully parsing source code into an AST object doesn't guarantee that the source code provided is valid Python code that can be executed as the compilation step can raise further SyntaxError{.interpreted-text role="exc"} exceptions. For instance, the source return 42 generates a valid AST node for a return statement, but it cannot be compiled alone (it needs to be inside a function node).

In particular, ast.parse{.interpreted-text role="func"} won't do any scoping checks, which the compilation step does. ::::

:::: warning ::: title Warning :::

It is possible to crash the Python interpreter with a sufficiently large/complex string due to stack depth limitations in Python's AST compiler. ::::

::: versionchanged 3.8 Added type_comments, mode='func_type' and feature_version. :::

::: versionchanged 3.13 The minimum supported version for feature_version is now (3, 7). The optimize argument was added. :::

::: versionadded 3.15 Added the module parameter. ::: ::::::::::

:::::::: function unparse(ast_obj)

Unparse an ast.AST{.interpreted-text role="class"} object and generate a string with code that would produce an equivalent ast.AST{.interpreted-text role="class"} object if parsed back with ast.parse{.interpreted-text role="func"}.

:::: warning ::: title Warning :::

The produced code string will not necessarily be equal to the original code that generated the ast.AST{.interpreted-text role="class"} object (without any compiler optimizations, such as constant tuples/frozensets). ::::

:::: warning ::: title Warning :::

Trying to unparse a highly complex expression would result with RecursionError{.interpreted-text role="exc"}. ::::

::: versionadded 3.9 ::: ::::::::

:::::::: function literal_eval(node_or_string)

Evaluate an expression node or a string containing only a Python literal or container display. The string or node provided may only consist of the following Python literal structures: strings, bytes, numbers, tuples, lists, dicts, sets, booleans, None and Ellipsis.

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

This function had been documented as "safe" in the past without defining what that meant. That was misleading. This is specifically designed not to execute Python code, unlike the more general eval{.interpreted-text role="func"}. There is no namespace, no name lookups, or ability to call out. But it is not free from attack: A relatively small input can lead to memory exhaustion or to C stack exhaustion, crashing the process. There is also the possibility for excessive CPU consumption denial of service on some inputs. Calling it on untrusted data is thus not recommended.

:::: warning ::: title Warning :::

It is possible to crash the Python interpreter due to stack depth limitations in Python's AST compiler.

It can raise ValueError{.interpreted-text role="exc"}, TypeError{.interpreted-text role="exc"}, SyntaxError{.interpreted-text role="exc"}, MemoryError{.interpreted-text role="exc"} and RecursionError{.interpreted-text role="exc"} depending on the malformed input. ::::

::: versionchanged 3.2 Now allows bytes and set literals. :::

::: versionchanged 3.9 Now supports creating empty sets with 'set()'. :::

::: versionchanged 3.10 For string inputs, leading spaces and tabs are now stripped. ::: ::::::::

:::: function get_docstring(node, clean=True)

Return the docstring of the given node (which must be a FunctionDef{.interpreted-text role="class"}, AsyncFunctionDef{.interpreted-text role="class"}, ClassDef{.interpreted-text role="class"}, or Module{.interpreted-text role="class"} node), or None if it has no docstring. If clean is true, clean up the docstring's indentation with inspect.cleandoc{.interpreted-text role="func"}.

::: versionchanged 3.5 AsyncFunctionDef{.interpreted-text role="class"} is now supported. ::: ::::

:::: function get_source_segment(source, node, *, padded=False)

Get source code segment of the source that generated node. If some location information (~ast.AST.lineno{.interpreted-text role="attr"}, ~ast.AST.end_lineno{.interpreted-text role="attr"}, ~ast.AST.col_offset{.interpreted-text role="attr"}, or ~ast.AST.end_col_offset{.interpreted-text role="attr"}) 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.

::: versionadded 3.8 ::: ::::

::: function fix_missing_locations(node)

When you compile a node tree with compile{.interpreted-text role="func"}, the compiler expects ~ast.AST.lineno{.interpreted-text role="attr"} and ~ast.AST.col_offset{.interpreted-text role="attr"} 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. :::

::: function 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. :::

::: function copy_location(new_node, old_node)

Copy source location (~ast.AST.lineno{.interpreted-text role="attr"}, ~ast.AST.col_offset{.interpreted-text role="attr"}, ~ast.AST.end_lineno{.interpreted-text role="attr"}, and ~ast.AST.end_col_offset{.interpreted-text role="attr"}) from old_node to new_node if possible, and return new_node. :::

::: function iter_fields(node)

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

::: function 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. :::

::: function 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. :::

::::::: 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{.interpreted-text role="meth"} method.

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

::: method visit(node)

Visit a node. The default implementation calls the method called self.visit_{classname}{.interpreted-text role="samp"} where classname is the name of the node class, or generic_visit{.interpreted-text role="meth"} if that method doesn't exist. :::

::: method generic_visit(node)

This visitor calls visit{.interpreted-text role="meth"} 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{.interpreted-text role="meth"} or visits them itself. :::

::: method visit_Constant(node)

Handles all constant nodes. :::

Don't use the NodeVisitor{.interpreted-text role="class"} if you want to apply changes to nodes during traversal. For this a special visitor exists (NodeTransformer{.interpreted-text role="class"}) that allows modifications.

::: deprecated-removed 3.8 3.14

Methods !visit_Num{.interpreted-text role="meth"}, !visit_Str{.interpreted-text role="meth"}, !visit_Bytes{.interpreted-text role="meth"}, !visit_NameConstant{.interpreted-text role="meth"} and !visit_Ellipsis{.interpreted-text role="meth"} will not be called in Python 3.14+. Add the visit_Constant{.interpreted-text role="meth"} method instead to handle all constant nodes. ::: :::::::

::: NodeTransformer() A NodeVisitor{.interpreted-text role="class"} subclass that walks the abstract syntax tree and allows modification of nodes.

The NodeTransformer{.interpreted-text role="class"} will walk the AST and use the return value of the visitor methods to replace or remove the old node. If the return value of the visitor method is None, the node will be removed from its location, otherwise it is replaced with the return value. The return value may be the original node in which case no replacement takes place.

Here is an example transformer that rewrites all occurrences of name lookups (foo) to data['foo']:

class RewriteName(NodeTransformer):

    def visit_Name(self, node):
        return Subscript(
            value=Name(id='data'),
            slice=Constant(value=node.id),
            ctx=node.ctx
        )

Keep in mind that if the node you're operating on has child nodes you must either transform the child nodes yourself or call the ~ast.NodeVisitor.generic_visit{.interpreted-text role="meth"} method for the node first.

For nodes that were part of a collection of statements (that applies to all statement nodes), the visitor may also return a list of nodes rather than just a single node.

If NodeTransformer{.interpreted-text role="class"} introduces new nodes (that weren't part of original tree) without giving them location information (such as ~ast.AST.lineno{.interpreted-text role="attr"}), fix_missing_locations{.interpreted-text role="func"} should be called with the new sub-tree to recalculate the location information:

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

Usually you use the transformer like this:

node = YourTransformer().visit(node)

:::

::::::: function dump(node, annotate_fields=True, include_attributes=False, *, indent=None, show_empty=False)

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.

If show_empty is false (the default), optional empty lists and Load() values will be omitted from the output. Optional None values are always omitted.

::: doctest >>> tree = ast.parse('print(None)', '?', 'eval') >>> print(ast.dump(tree, indent=4)) Expression( body=Call( func=Name(id='print'), args=[ Constant(value=None)])) >>> print(ast.dump(tree, indent=4, show_empty=True)) Expression( body=Call( func=Name(id='print', ctx=Load()), args=[ Constant(value=None)], keywords=[])) :::

::: versionchanged 3.9 Added the indent option. :::

::: versionchanged 3.13 Added the show_empty option. :::

::: versionchanged 3.15 Omit optional Load() values by default. ::: :::::::

Compiler flags {#ast-compiler-flags}

The following flags may be passed to compile{.interpreted-text role="func"} in order to change effects on the compilation of a program:

:::: data PyCF_ALLOW_TOP_LEVEL_AWAIT

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

::: versionadded 3.8 ::: ::::

::: data PyCF_ONLY_AST

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

:::: data PyCF_OPTIMIZED_AST

The returned AST is optimized according to the optimize argument in compile{.interpreted-text role="func"} or ast.parse{.interpreted-text role="func"}.

::: versionadded 3.13 ::: ::::

:::: data PyCF_TYPE_COMMENTS

Enables support for 484{.interpreted-text role="pep"} and 526{.interpreted-text role="pep"} style type comments (# type: <type>, # type: ignore <stuff>).

::: versionadded 3.8 ::: ::::

:::: function compare(a, b, /, *, compare_attributes=False)

Recursively compares two ASTs.

compare_attributes affects whether AST attributes are considered in the comparison. If compare_attributes is False (default), then attributes are ignored. Otherwise they must all be equal. This option is useful to check whether the ASTs are structurally equal but differ in whitespace or similar details. Attributes include line numbers and column offsets.

::: versionadded 3.14 ::: ::::

Command-line usage {#ast-cli}

::: versionadded 3.9 :::

The !ast{.interpreted-text role="mod"} module can be executed as a script from the command line. It is as simple as:

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

The following options are accepted:

::: program ast :::

::: option

-h, --help

:

Show the help message and exit. :::

::: option

-m <mode>

:

--mode <mode>

:

Specify what kind of code must be compiled, like the mode argument in parse{.interpreted-text role="func"}. :::

::: option

--no-type-comments

:

Don't parse type comments. :::

::: option

-a, --include-attributes

:

Include attributes such as line numbers and column offsets. :::

::: option

-i <indent>

:

--indent <indent>

:

Indentation of nodes in AST (number of spaces). :::

:::: option

--feature-version <version>

:

Python version in the format 3.x (for example, 3.10). Defaults to the current version of the interpreter.

::: versionadded 3.14 ::: ::::

:::: option

-O <level>

:

--optimize <level>

:

Optimization level for parser. Defaults to no optimization.

::: versionadded 3.14 ::: ::::

:::: option

--show-empty

:

Show empty lists and fields that are None. Defaults to not showing empty objects.

::: versionadded 3.14 ::: ::::

If infile{.interpreted-text role="file"} is specified its contents are parsed to AST and dumped to stdout. Otherwise, the content is read from stdin.

::: seealso 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. :::