ast — Abstract Syntax Trees

Source code:Lib/ast.py


Theast module helps Python applications to process trees of the Pythonabstract syntax grammar. The abstract syntax itself might change with eachPython release; this module helps to find out programmatically what the currentgrammar looks like.

An abstract syntax tree can be generated by passingast.PyCF_ONLY_AST asa flag to thecompile() built-in function, or using theparse()helper provided in this module. The result will be a tree of objects whoseclasses all inherit fromast.AST. An abstract syntax tree can becompiled into a Python code object using the built-incompile() function.

Abstract Grammar

The abstract grammar is currently defined as follows:

-- ASDL's 4 builtin types are:-- identifier, int, string, constantmodulePython{mod=Module(stmt*body,type_ignore*type_ignores)|Interactive(stmt*body)|Expression(exprbody)|FunctionType(expr*argtypes,exprreturns)stmt=FunctionDef(identifiername,argumentsargs,stmt*body,expr*decorator_list,expr?returns,string?type_comment,type_param*type_params)|AsyncFunctionDef(identifiername,argumentsargs,stmt*body,expr*decorator_list,expr?returns,string?type_comment,type_param*type_params)|ClassDef(identifiername,expr*bases,keyword*keywords,stmt*body,expr*decorator_list,type_param*type_params)|Return(expr?value)|Delete(expr*targets)|Assign(expr*targets,exprvalue,string?type_comment)|TypeAlias(exprname,type_param*type_params,exprvalue)|AugAssign(exprtarget,operatorop,exprvalue)-- 'simple' indicates that we annotate simple name without parens|AnnAssign(exprtarget,exprannotation,expr?value,intsimple)-- use 'orelse' because else is a keyword in target languages|For(exprtarget,expriter,stmt*body,stmt*orelse,string?type_comment)|AsyncFor(exprtarget,expriter,stmt*body,stmt*orelse,string?type_comment)|While(exprtest,stmt*body,stmt*orelse)|If(exprtest,stmt*body,stmt*orelse)|With(withitem*items,stmt*body,string?type_comment)|AsyncWith(withitem*items,stmt*body,string?type_comment)|Match(exprsubject,match_case*cases)|Raise(expr?exc,expr?cause)|Try(stmt*body,excepthandler*handlers,stmt*orelse,stmt*finalbody)|TryStar(stmt*body,excepthandler*handlers,stmt*orelse,stmt*finalbody)|Assert(exprtest,expr?msg)|Import(alias*names)|ImportFrom(identifier?module,alias*names,int?level)|Global(identifier*names)|Nonlocal(identifier*names)|Expr(exprvalue)|Pass|Break|Continue-- col_offset is the byte offset in the utf8 string the parser usesattributes(intlineno,intcol_offset,int?end_lineno,int?end_col_offset)-- BoolOp() can use left & right?expr=BoolOp(boolopop,expr*values)|NamedExpr(exprtarget,exprvalue)|BinOp(exprleft,operatorop,exprright)|UnaryOp(unaryopop,exproperand)|Lambda(argumentsargs,exprbody)|IfExp(exprtest,exprbody,exprorelse)|Dict(expr*keys,expr*values)|Set(expr*elts)|ListComp(exprelt,comprehension*generators)|SetComp(exprelt,comprehension*generators)|DictComp(exprkey,exprvalue,comprehension*generators)|GeneratorExp(exprelt,comprehension*generators)-- the grammar constrains where yield expressions can occur|Await(exprvalue)|Yield(expr?value)|YieldFrom(exprvalue)-- need sequences for compare to distinguish between-- x < 4 < 3 and (x < 4) < 3|Compare(exprleft,cmpop*ops,expr*comparators)|Call(exprfunc,expr*args,keyword*keywords)|FormattedValue(exprvalue,intconversion,expr?format_spec)|JoinedStr(expr*values)|Constant(constantvalue,string?kind)-- the following expression can appear in assignment context|Attribute(exprvalue,identifierattr,expr_contextctx)|Subscript(exprvalue,exprslice,expr_contextctx)|Starred(exprvalue,expr_contextctx)|Name(identifierid,expr_contextctx)|List(expr*elts,expr_contextctx)|Tuple(expr*elts,expr_contextctx)-- can appear only in Subscript|Slice(expr?lower,expr?upper,expr?step)-- col_offset is the byte offset in the utf8 string the parser usesattributes(intlineno,intcol_offset,int?end_lineno,int?end_col_offset)expr_context=Load|Store|Delboolop=And|Oroperator=Add|Sub|Mult|MatMult|Div|Mod|Pow|LShift|RShift|BitOr|BitXor|BitAnd|FloorDivunaryop=Invert|Not|UAdd|USubcmpop=Eq|NotEq|Lt|LtE|Gt|GtE|Is|IsNot|In|NotIncomprehension=(exprtarget,expriter,expr*ifs,intis_async)excepthandler=ExceptHandler(expr?type,identifier?name,stmt*body)attributes(intlineno,intcol_offset,int?end_lineno,int?end_col_offset)arguments=(arg*posonlyargs,arg*args,arg?vararg,arg*kwonlyargs,expr*kw_defaults,arg?kwarg,expr*defaults)arg=(identifierarg,expr?annotation,string?type_comment)attributes(intlineno,intcol_offset,int?end_lineno,int?end_col_offset)-- keyword arguments supplied to call (NULL identifier for **kwargs)keyword=(identifier?arg,exprvalue)attributes(intlineno,intcol_offset,int?end_lineno,int?end_col_offset)-- import name with optional 'as' alias.alias=(identifiername,identifier?asname)attributes(intlineno,intcol_offset,int?end_lineno,int?end_col_offset)withitem=(exprcontext_expr,expr?optional_vars)match_case=(patternpattern,expr?guard,stmt*body)pattern=MatchValue(exprvalue)|MatchSingleton(constantvalue)|MatchSequence(pattern*patterns)|MatchMapping(expr*keys,pattern*patterns,identifier?rest)|MatchClass(exprcls,pattern*patterns,identifier*kwd_attrs,pattern*kwd_patterns)|MatchStar(identifier?name)-- The optional "rest" MatchMapping parameter handles capturing extra mapping keys|MatchAs(pattern?pattern,identifier?name)|MatchOr(pattern*patterns)attributes(intlineno,intcol_offset,intend_lineno,intend_col_offset)type_ignore=TypeIgnore(intlineno,stringtag)type_param=TypeVar(identifiername,expr?bound,expr?default_value)|ParamSpec(identifiername,expr?default_value)|TypeVarTuple(identifiername,expr?default_value)attributes(intlineno,intcol_offset,intend_lineno,intend_col_offset)}

Node classes

classast.AST

This is the base of all AST node classes. The actual node classes arederived from theParser/Python.asdl file, which is reproducedabove. They are defined in the_ast Cmodule and re-exported inast.

There is one class defined for each left-hand side symbol in the abstractgrammar (for example,ast.stmt orast.expr). In addition,there is one class defined for each constructor on the right-hand side; theseclasses inherit from the classes for the left-hand side trees. For example,ast.BinOp inherits fromast.expr. For production ruleswith alternatives (aka “sums”), the left-hand side class is abstract: onlyinstances of specific constructor nodes are ever created.

_fields

Each concrete class has an attribute_fields which gives the namesof 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.BinOpinstances have an attributeleft of typeast.expr.

If these attributes are marked as optional in the grammar (using aquestion mark), the value might beNone. If the attributes can havezero-or-more values (marked with an asterisk), the values are representedas Python lists. All possible attributes must be present and have validvalues when compiling an AST withcompile().

_field_types

The_field_types attribute on each concrete class is a dictionarymapping field names (as also listed in_fields) to their types.

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

Added in version 3.13.

lineno
col_offset
end_lineno
end_col_offset

Instances ofast.expr andast.stmt subclasses havelineno,col_offset,end_lineno, andend_col_offset attributes. Thelineno andend_linenoare the first and last line numbers of source text span (1-indexed so thefirst line is line 1) and thecol_offset andend_col_offsetare the corresponding UTF-8 byte offsets of the first and last tokens thatgenerated the node. The UTF-8 offset is recorded because the parser usesUTF-8 internally.

Note that the end positions are not required by the compiler and aretherefore optional. The end offset isafter the last symbol, for exampleone can get the source segment of a one-line expression node usingsource_line[node.col_offset:node.end_col_offset].

The constructor of a classast.T parses its arguments as follows:

  • If there are positional arguments, there must be as many as there are itemsinT._fields; they will be assigned as attributes of these names.

  • If there are keyword arguments, they will set the attributes of the samenames to the given values.

For example, to create and populate anast.UnaryOp node, you coulduse

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 toNone. If a list field is omitted, it defaults to the emptylist. If a field of typeast.expr_context is omitted, it defaults toLoad(). If any other field is omitted, aDeprecationWarning is raisedand the AST node will not have this field. In Python 3.15, this condition willraise an error.

Changed in version 3.8:Classast.Constant is now used for all constants.

Changed in version 3.9:Simple indices are represented by their value, extended slices arerepresented as tuples.

Deprecated since version 3.8:Old classesast.Num,ast.Str,ast.Bytes,ast.NameConstant andast.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.

Deprecated since version 3.9:Old classesast.Index andast.ExtSlice are stillavailable, but they will be removed in future Python releases.In the meantime, instantiating them will return an instance ofa different class.

Deprecated since version 3.13, will be removed in version 3.15:Previous versions of Python allowed the creation of AST nodes that were missingrequired fields. Similarly, AST node constructors allowed arbitrary keywordarguments that were set as attributes of the AST node, even if they did notmatch any of the fields of the AST node. This behavior is deprecated and willbe removed in Python 3.15.

Note

The descriptions of the specific node classes displayed herewere initially adapted from the fantasticGreen TreeSnakes project andall its contributors.

Root nodes

classast.Module(body,type_ignores)

A Python module, as withfile input.Node type generated byast.parse() in the default"exec"mode.

body is alist of the module’sStatements.

type_ignores is alist of the module’s type ignore comments;seeast.parse() for more details.

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

A single Pythonexpression input.Node type generated byast.parse() whenmode is"eval".

body is a single node,one of theexpression types.

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

A singleinteractive input, like inInteractive Mode.Node type generated byast.parse() whenmode is"single".

body is alist ofstatement nodes.

>>>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))])
classast.FunctionType(argtypes,returns)

A representation of an old-style type comments for functions,as Python versions prior to 3.5 didn’t supportPEP 484 annotations.Node type generated byast.parse() whenmode is"func_type".

Such type comments would look like this:

defsum_two_number(a,b):# type: (int, int) -> intreturna+b

argtypes is alist ofexpression nodes.

returns is a singleexpression node.

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

Added in version 3.8.

Literals

classast.Constant(value)

A constant value. Thevalue attribute of theConstant literal contains thePython object it represents. The values represented can be simple typessuch as a number, string orNone, but also immutable container types(tuples and frozensets) if all of their elements are constant.

>>>print(ast.dump(ast.parse('123',mode='eval'),indent=4))Expression(    body=Constant(value=123))
classast.FormattedValue(value,conversion,format_spec)

Node representing a single formatting field in an f-string. If the stringcontains a single formatting field and nothing else the node can beisolated otherwise it appears inJoinedStr.

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

  • conversion is an integer:

    • -1: no formatting

    • 115:!s string formatting

    • 114:!r repr formatting

    • 97:!a ascii formatting

  • format_spec is aJoinedStr node representing the formattingof the value, orNone if no format was specified. Bothconversion andformat_spec can be set at the same time.

classast.JoinedStr(values)

An f-string, comprising a series ofFormattedValue andConstantnodes.

>>>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', ctx=Load()),                conversion=-1),            Constant(value=') is '),            FormattedValue(                value=Call(                    func=Name(id='sin', ctx=Load()),                    args=[                        Name(id='a', ctx=Load())]),                conversion=-1,                format_spec=JoinedStr(                    values=[                        Constant(value='.3')]))]))
classast.List(elts,ctx)
classast.Tuple(elts,ctx)

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

>>>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)],        ctx=Load()))>>>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)],        ctx=Load()))
classast.Set(elts)

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

>>>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)]))
classast.Dict(keys,values)

A dictionary.keys andvalues hold lists of nodes representing thekeys and the values respectively, in matching order (what would be returnedwhen callingdictionary.keys() anddictionary.values()).

When doing dictionary unpacking using dictionary literals the expression to beexpanded goes in thevalues list, with aNone at the correspondingposition inkeys.

>>>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', ctx=Load())]))

Variables

classast.Name(id,ctx)

A variable name.id holds the name as a string, andctx is one ofthe following types.

classast.Load
classast.Store
classast.Del

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

>>>print(ast.dump(ast.parse('a'),indent=4))Module(    body=[        Expr(            value=Name(id='a', ctx=Load()))])>>>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())])])
classast.Starred(value,ctx)

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

>>>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', ctx=Load()))])

Expressions

classast.Expr(value)

When an expression, such as a function call, appears as a statement by itselfwith its return value not used or stored, it is wrapped in this container.value holds one of the other nodes in this section, aConstant, aName, aLambda, aYield orYieldFrom node.

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

A unary operation.op is the operator, andoperand any expressionnode.

classast.UAdd
classast.USub
classast.Not
classast.Invert

Unary operator tokens.Not is thenot keyword,Invertis the~ operator.

>>>print(ast.dump(ast.parse('not x',mode='eval'),indent=4))Expression(    body=UnaryOp(        op=Not(),        operand=Name(id='x', ctx=Load())))
classast.BinOp(left,op,right)

A binary operation (like addition or division).op is the operator, andleft andright are any expression nodes.

>>>print(ast.dump(ast.parse('x + y',mode='eval'),indent=4))Expression(    body=BinOp(        left=Name(id='x', ctx=Load()),        op=Add(),        right=Name(id='y', ctx=Load())))
classast.Add
classast.Sub
classast.Mult
classast.Div
classast.FloorDiv
classast.Mod
classast.Pow
classast.LShift
classast.RShift
classast.BitOr
classast.BitXor
classast.BitAnd
classast.MatMult

Binary operator tokens.

classast.BoolOp(op,values)

A boolean operation, ‘or’ or ‘and’.op isOr orAnd.values are the values involved. Consecutive operations with the sameoperator, such asaorborc, are collapsed into one node with severalvalues.

This doesn’t includenot, which is aUnaryOp.

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

Boolean operator tokens.

classast.Compare(left,ops,comparators)

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

>>>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', ctx=Load()),            Constant(value=10)]))
classast.Eq
classast.NotEq
classast.Lt
classast.LtE
classast.Gt
classast.GtE
classast.Is
classast.IsNot
classast.In
classast.NotIn

Comparison operator tokens.

classast.Call(func,args,keywords)

A function call.func is the function, which will often be aName orAttribute object. Of the arguments:

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

  • keywords holds a list ofkeyword objects representingarguments passed by keyword.

Theargs andkeywords arguments are optional and default to empty lists.

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

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

classast.IfExp(test,body,orelse)

An expression such asaifbelsec. Each field holds a single node, soin the following example, all three areName nodes.

>>>print(ast.dump(ast.parse('a if b else c',mode='eval'),indent=4))Expression(    body=IfExp(        test=Name(id='b', ctx=Load()),        body=Name(id='a', ctx=Load()),        orelse=Name(id='c', ctx=Load())))
classast.Attribute(value,attr,ctx)

Attribute access, e.g.d.keys.value is a node, typically aName.attr is a bare string giving the name of the attribute,andctx isLoad,Store orDel according to howthe attribute is acted on.

>>>print(ast.dump(ast.parse('snake.colour',mode='eval'),indent=4))Expression(    body=Attribute(        value=Name(id='snake', ctx=Load()),        attr='colour',        ctx=Load()))
classast.NamedExpr(target,value)

A named expression. This AST node is produced by the assignment expressionsoperator (also known as the walrus operator). As opposed to theAssignnode in which the first argument can be multiple nodes, in this case bothtarget andvalue must be single nodes.

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

Added in version 3.8.

Subscripting

classast.Subscript(value,slice,ctx)

A subscript, such asl[1].value is the subscripted object(usually sequence or mapping).slice is an index, slice or key.It can be aTuple and contain aSlice.ctx isLoad,Store orDelaccording to the action performed with the subscript.

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

Regular slicing (on the formlower:upper orlower:upper:step).Can occur only inside theslice field ofSubscript, eitherdirectly or as an element ofTuple.

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

Comprehensions

classast.ListComp(elt,generators)
classast.SetComp(elt,generators)
classast.GeneratorExp(elt,generators)
classast.DictComp(key,value,generators)

List and set comprehensions, generator expressions, and dictionarycomprehensions.elt (orkey andvalue) is a single noderepresenting the part that will be evaluated for each item.

generators is a list ofcomprehension nodes.

>>>print(ast.dump(...ast.parse('[x for x in numbers]',mode='eval'),...indent=4,...))Expression(    body=ListComp(        elt=Name(id='x', ctx=Load()),        generators=[            comprehension(                target=Name(id='x', ctx=Store()),                iter=Name(id='numbers', ctx=Load()),                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', ctx=Load()),        value=BinOp(            left=Name(id='x', ctx=Load()),            op=Pow(),            right=Constant(value=2)),        generators=[            comprehension(                target=Name(id='x', ctx=Store()),                iter=Name(id='numbers', ctx=Load()),                is_async=0)]))>>>print(ast.dump(...ast.parse('{x for x in numbers}',mode='eval'),...indent=4,...))Expression(    body=SetComp(        elt=Name(id='x', ctx=Load()),        generators=[            comprehension(                target=Name(id='x', ctx=Store()),                iter=Name(id='numbers', ctx=Load()),                is_async=0)]))
classast.comprehension(target,iter,ifs,is_async)

Onefor clause in a comprehension.target is the reference to use foreach element - typically aName orTuple node.iteris the object to iterate over.ifs is a list of test expressions: eachfor clause can have multipleifs.

is_async indicates a comprehension is asynchronous (using anasyncfor instead offor). The value is an integer (0 or 1).

>>>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', ctx=Load()),            args=[                Name(id='c', ctx=Load())]),        generators=[            comprehension(                target=Name(id='line', ctx=Store()),                iter=Name(id='file', ctx=Load()),                is_async=0),            comprehension(                target=Name(id='c', ctx=Store()),                iter=Name(id='line', ctx=Load()),                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 comprehensionExpression(    body=GeneratorExp(        elt=BinOp(            left=Name(id='n', ctx=Load()),            op=Pow(),            right=Constant(value=2)),        generators=[            comprehension(                target=Name(id='n', ctx=Store()),                iter=Name(id='it', ctx=Load()),                ifs=[                    Compare(                        left=Name(id='n', ctx=Load()),                        ops=[                            Gt()],                        comparators=[                            Constant(value=5)]),                    Compare(                        left=Name(id='n', ctx=Load()),                        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 comprehensionExpression(    body=ListComp(        elt=Name(id='i', ctx=Load()),        generators=[            comprehension(                target=Name(id='i', ctx=Store()),                iter=Name(id='soc', ctx=Load()),                is_async=1)]))

Statements

classast.Assign(targets,value,type_comment)

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

Multiple nodes intargets represents assigning the same value to each.Unpacking is represented by putting aTuple orListwithintargets.

type_comment

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

>>>print(ast.dump(ast.parse('a = b = 1'),indent=4))# Multiple assignmentModule(    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))# UnpackingModule(    body=[        Assign(            targets=[                Tuple(                    elts=[                        Name(id='a', ctx=Store()),                        Name(id='b', ctx=Store())],                    ctx=Store())],            value=Name(id='c', ctx=Load()))])
classast.AnnAssign(target,annotation,value,simple)

An assignment with a type annotation.target is a single node and canbe aName, anAttribute or aSubscript.annotation is the annotation, such as aConstant orNamenode.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 aName node that does not appear between parentheses; all othertargets are considered complex. Only simple targets appear inthe__annotations__ dictionary of modules and classes.

>>>print(ast.dump(ast.parse('c: int'),indent=4))Module(    body=[        AnnAssign(            target=Name(id='c', ctx=Store()),            annotation=Name(id='int', ctx=Load()),            simple=1)])>>>print(ast.dump(ast.parse('(a): int = 1'),indent=4))# Annotation with parenthesisModule(    body=[        AnnAssign(            target=Name(id='a', ctx=Store()),            annotation=Name(id='int', ctx=Load()),            value=Constant(value=1),            simple=0)])>>>print(ast.dump(ast.parse('a.b: int'),indent=4))# Attribute annotationModule(    body=[        AnnAssign(            target=Attribute(                value=Name(id='a', ctx=Load()),                attr='b',                ctx=Store()),            annotation=Name(id='int', ctx=Load()),            simple=0)])>>>print(ast.dump(ast.parse('a[1]: int'),indent=4))# Subscript annotationModule(    body=[        AnnAssign(            target=Subscript(                value=Name(id='a', ctx=Load()),                slice=Constant(value=1),                ctx=Store()),            annotation=Name(id='int', ctx=Load()),            simple=0)])
classast.AugAssign(target,op,value)

Augmented assignment, such asa+=1. In the following example,target is aName node forx (with theStorecontext),op isAdd, andvalue is aConstant withvalue for 1.

Thetarget attribute cannot be of classTuple orList,unlike the targets ofAssign.

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

Araise statement.exc is the exception object to be raised, normally aCall orName, orNone for a standaloneraise.cause is the optional part fory inraisexfromy.

>>>print(ast.dump(ast.parse('raise x from y'),indent=4))Module(    body=[        Raise(            exc=Name(id='x', ctx=Load()),            cause=Name(id='y', ctx=Load()))])
classast.Assert(test,msg)

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

>>>print(ast.dump(ast.parse('assert x,y'),indent=4))Module(    body=[        Assert(            test=Name(id='x', ctx=Load()),            msg=Name(id='y', ctx=Load()))])
classast.Delete(targets)

Represents adel statement.targets is a list of nodes, such asName,Attribute orSubscript nodes.

>>>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())])])
classast.Pass

Apass statement.

>>>print(ast.dump(ast.parse('pass'),indent=4))Module(    body=[        Pass()])
classast.TypeAlias(name,type_params,value)

Atype alias created through thetypestatement.name is the name of the alias,type_params is a list oftype parameters, andvalue is the value of thetype alias.

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

Added in version 3.12.

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

Imports

classast.Import(names)

An import statement.names is a list ofalias nodes.

>>>print(ast.dump(ast.parse('import x,y,z'),indent=4))Module(    body=[        Import(            names=[                alias(name='x'),                alias(name='y'),                alias(name='z')])])
classast.ImportFrom(module,names,level)

Representsfromximporty.module is a raw string of the ‘from’ name,without any leading dots, orNone for statements such asfrom.importfoo.level is an integer holding the level of the relative import (0 meansabsolute import).

>>>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)])
classast.alias(name,asname)

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

>>>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)])

Control flow

Note

Optional clauses such aselse are stored as an empty list if they’renot present.

classast.If(test,body,orelse)

Anif statement.test holds a single node, such as aComparenode.body andorelse each hold a list of nodes.

elif clauses don’t have a special representation in the AST, but ratherappear as extraIf nodes within theorelse section of theprevious one.

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

Afor loop.target holds the variable(s) the loop assigns to, as asingleName,Tuple,List,Attribute orSubscript node.iter holds the item to be looped over, againas a single node.body andorelse contain lists of nodes to execute.Those inorelse are executed if the loop finishes normally, rather thanvia abreak statement.

type_comment

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

>>>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', ctx=Load()),            body=[                Expr(                    value=Constant(value=Ellipsis))],            orelse=[                Expr(                    value=Constant(value=Ellipsis))])])
classast.While(test,body,orelse)

Awhile loop.test holds the condition, such as aComparenode.

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

Thebreak andcontinue statements.

>>>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', ctx=Load()),            body=[                If(                    test=Compare(                        left=Name(id='a', ctx=Load()),                        ops=[                            Gt()],                        comparators=[                            Constant(value=5)]),                    body=[                        Break()],                    orelse=[                        Continue()])])])
classast.Try(body,handlers,orelse,finalbody)

try blocks. All attributes are list of nodes to execute, except forhandlers, which is a list ofExceptHandler nodes.

>>>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', ctx=Load()),                    body=[                        Expr(                            value=Constant(value=Ellipsis))]),                ExceptHandler(                    type=Name(id='OtherException', ctx=Load()),                    name='e',                    body=[                        Expr(                            value=Constant(value=Ellipsis))])],            orelse=[                Expr(                    value=Constant(value=Ellipsis))],            finalbody=[                Expr(                    value=Constant(value=Ellipsis))])])
classast.TryStar(body,handlers,orelse,finalbody)

try blocks which are followed byexcept* clauses. The attributes are thesame as forTry but theExceptHandler nodes inhandlersare interpreted asexcept* blocks rather thenexcept.

>>>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', ctx=Load()),                    body=[                        Expr(                            value=Constant(value=Ellipsis))])])])

Added in version 3.11.

classast.ExceptHandler(type,name,body)

A singleexcept clause.type is the exception type it will match,typically aName node (orNone for a catch-allexcept: clause).name is a raw string for the name to hold the exception, orNone ifthe clause doesn’t haveasfoo.body is a list of nodes.

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

Awith block.items is a list ofwithitem nodes representingthe context managers, andbody is the indented block inside the context.

type_comment

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

classast.withitem(context_expr,optional_vars)

A single context manager in awith block.context_expr is the contextmanager, often aCall node.optional_vars is aName,Tuple orList for theasfoo part, orNone if thatisn’t used.

>>>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', ctx=Load()),                    optional_vars=Name(id='b', ctx=Store())),                withitem(                    context_expr=Name(id='c', ctx=Load()),                    optional_vars=Name(id='d', ctx=Store()))],            body=[                Expr(                    value=Call(                        func=Name(id='something', ctx=Load()),                        args=[                            Name(id='b', ctx=Load()),                            Name(id='d', ctx=Load())]))])])

Pattern matching

classast.Match(subject,cases)

Amatch statement.subject holds the subject of the match (the objectthat is being matched against the cases) andcases contains an iterable ofmatch_case nodes with the different cases.

Added in version 3.10.

classast.match_case(pattern,guard,body)

A single case pattern in amatch statement.pattern contains thematch pattern that the subject will be matched against. Note that theAST nodes produced for patterns differ from those produced forexpressions, even when they share the same syntax.

Theguard attribute contains an expression that will be evaluated ifthe pattern matches the subject.

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

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

Added in version 3.10.

classast.MatchValue(value)

A match literal or value pattern that compares by equality.value isan expression node. Permitted value nodes are restricted as described inthe match statement documentation. This pattern succeeds if the matchsubject is equal to the evaluated value.

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

Added in version 3.10.

classast.MatchSingleton(value)

A match literal pattern that compares by identity.value is thesingleton to be compared against:None,True, orFalse. Thispattern succeeds if the match subject is the given constant.

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

Added in version 3.10.

classast.MatchSequence(patterns)

A match sequence pattern.patterns contains the patterns to be matchedagainst the subject elements if the subject is a sequence. Matches a variablelength sequence if one of the subpatterns is aMatchStar node, otherwisematches a fixed length sequence.

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

Added in version 3.10.

classast.MatchStar(name)

Matches the rest of the sequence in a variable length match sequence pattern.Ifname is notNone, a list containing the remaining sequenceelements is bound to that name if the overall sequence pattern is successful.

>>>print(ast.dump(ast.parse("""...match x:...    case [1, 2, *rest]:...        ......    case [*_]:...        ......"""),indent=4))Module(    body=[        Match(            subject=Name(id='x', ctx=Load()),            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))])])])

Added in version 3.10.

classast.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 anoptional name that can be specified to capture the remaining mapping elements.Permitted key expressions are restricted as described in the match statementdocumentation.

This pattern succeeds if the subject is a mapping, all evaluated keyexpressions are present in the mapping, and the value corresponding to eachkey matches the corresponding subpattern. Ifrest is notNone, a dictcontaining the remaining mapping elements is bound to that name if the overallmapping pattern is successful.

>>>print(ast.dump(ast.parse("""...match x:...    case {1: _, 2: _}:...        ......    case {**rest}:...        ......"""),indent=4))Module(    body=[        Match(            subject=Name(id='x', ctx=Load()),            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))])])])

Added in version 3.10.

classast.MatchClass(cls,patterns,kwd_attrs,kwd_patterns)

A match class pattern.cls is an expression giving the nominal class tobe matched.patterns is a sequence of pattern nodes to be matched againstthe class defined sequence of pattern matching attributes.kwd_attrs is asequence of additional attributes to be matched (specified as keyword argumentsin 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, andany specified keyword attributes match their corresponding pattern.

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

>>>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', ctx=Load()),            cases=[                match_case(                    pattern=MatchClass(                        cls=Name(id='Point2D', ctx=Load()),                        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', ctx=Load()),                        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))])])])

Added in version 3.10.

classast.MatchAs(pattern,name)

A match “as-pattern”, capture pattern or wildcard pattern.patterncontains the match pattern that the subject will be matched against.If the pattern isNone, the node represents a capture pattern (i.e abare name) and will always succeed.

Thename attribute contains the name that will be bound if the patternis successful. Ifname isNone,pattern must also beNoneand the node represents the wildcard pattern.

>>>print(ast.dump(ast.parse("""...match x:...    case [x] as y:...        ......    case _:...        ......"""),indent=4))Module(    body=[        Match(            subject=Name(id='x', ctx=Load()),            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))])])])

Added in version 3.10.

classast.MatchOr(patterns)

A match “or-pattern”. An or-pattern matches each of its subpatterns in turnto the subject, until one succeeds. The or-pattern is then deemed tosucceed. If none of the subpatterns succeed the or-pattern fails. Thepatterns attribute contains a list of match pattern nodes that will bematched against the subject.

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

Added in version 3.10.

Type annotations

classast.TypeIgnore(lineno,tag)

A#type:ignore comment located atlineno.tag is the optional tag specified by the form#type:ignore<tag>.

>>>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', ctx=Load()),            value=Constant(value=1),            simple=1)],    type_ignores=[        TypeIgnore(lineno=1, tag='[assignment]')])

Note

TypeIgnore nodes are not generated when thetype_comments parameteris set toFalse (default). Seeast.parse() for more details.

Added in version 3.8.

Type parameters

Type parameters can exist on classes, functions, and typealiases.

classast.TypeVar(name,bound,default_value)

Atyping.TypeVar.name is the name of the type variable.bound is the bound or constraints, if any. Ifbound is aTuple,it represents constraints; otherwise it represents the bound.default_valueis the default value; if theTypeVar has no default, thisattribute will be set toNone.

>>>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', ctx=Load()),                    default_value=Name(id='bool', ctx=Load()))],            value=Subscript(                value=Name(id='list', ctx=Load()),                slice=Name(id='T', ctx=Load()),                ctx=Load()))])

Added in version 3.12.

Changed in version 3.13:Added thedefault_value parameter.

classast.ParamSpec(name,default_value)

Atyping.ParamSpec.name is the name of the parameter specification.default_value is the default value; if theParamSpec has no default,this attribute will be set toNone.

>>>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', ctx=Load()),                            Name(id='str', ctx=Load())],                        ctx=Load()))],            value=Subscript(                value=Name(id='Callable', ctx=Load()),                slice=Tuple(                    elts=[                        Name(id='P', ctx=Load()),                        Name(id='int', ctx=Load())],                    ctx=Load()),                ctx=Load()))])

Added in version 3.12.

Changed in version 3.13:Added thedefault_value parameter.

classast.TypeVarTuple(name,default_value)

Atyping.TypeVarTuple.name is the name of the type variable tuple.default_value is the default value; if theTypeVarTuple has nodefault, this attribute will be set toNone.

>>>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(ctx=Load()))],            value=Subscript(                value=Name(id='tuple', ctx=Load()),                slice=Tuple(                    elts=[                        Starred(                            value=Name(id='Ts', ctx=Load()),                            ctx=Load())],                    ctx=Load()),                ctx=Load()))])

Added in version 3.12.

Changed in version 3.13:Added thedefault_value parameter.

Function and class definitions

classast.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 anarguments node.

  • body is the list of nodes inside the function.

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

  • returns is the return annotation.

  • type_params is a list oftype parameters.

type_comment

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

Changed in version 3.12:Addedtype_params.

classast.Lambda(args,body)

lambda is a minimal function definition that can be used inside anexpression. UnlikeFunctionDef,body holds a single node.

>>>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)))])
classast.arguments(posonlyargs,args,vararg,kwonlyargs,kw_defaults,kwarg,defaults)

The arguments for a function.

  • posonlyargs,args andkwonlyargs are lists ofarg nodes.

  • vararg andkwarg are singlearg nodes, referring to the*args,**kwargs parameters.

  • kw_defaults is a list of default values for keyword-only arguments. Ifone isNone, the corresponding argument is required.

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

classast.arg(arg,annotation,type_comment)

A single argument in a list.arg is a raw string of the argumentname;annotation is its annotation, such as aName node.

type_comment

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

>>>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', ctx=Load()),                Name(id='decorator2', ctx=Load())],            returns=Constant(value='return annotation'))])
classast.Return(value)

Areturn statement.

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

Ayield oryieldfrom expression. Because these are expressions, theymust be wrapped in anExpr node if the value sent back is not used.

>>>print(ast.dump(ast.parse('yield x'),indent=4))Module(    body=[        Expr(            value=Yield(                value=Name(id='x', ctx=Load())))])>>>print(ast.dump(ast.parse('yield from x'),indent=4))Module(    body=[        Expr(            value=YieldFrom(                value=Name(id='x', ctx=Load())))])
classast.Global(names)
classast.Nonlocal(names)

global andnonlocal statements.names is a list of raw strings.

>>>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'])])
classast.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 ofkeyword nodes, principally for ‘metaclass’.Other keywords will be passed to the metaclass, as perPEP 3115.

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

  • decorator_list is a list of nodes, as inFunctionDef.

  • type_params is a list oftype parameters.

>>>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', ctx=Load()),                Name(id='base2', ctx=Load())],            keywords=[                keyword(                    arg='metaclass',                    value=Name(id='meta', ctx=Load()))],            body=[                Pass()],            decorator_list=[                Name(id='decorator1', ctx=Load()),                Name(id='decorator2', ctx=Load())])])

Changed in version 3.12:Addedtype_params.

Async and await

classast.AsyncFunctionDef(name,args,body,decorator_list,returns,type_comment,type_params)

Anasyncdef function definition. Has the same fields asFunctionDef.

Changed in version 3.12:Addedtype_params.

classast.Await(value)

Anawait expression.value is what it waits for.Only valid in the body of anAsyncFunctionDef.

>>>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', ctx=Load()))))])])
classast.AsyncFor(target,iter,body,orelse,type_comment)
classast.AsyncWith(items,body,type_comment)

asyncfor loops andasyncwith context managers. They have the samefields asFor andWith, respectively. Only valid in thebody of anAsyncFunctionDef.

Note

When a string is parsed byast.parse(), operator nodes (subclassesofast.operator,ast.unaryop,ast.cmpop,ast.boolop andast.expr_context) on the returned treewill be singletons. Changes to one will be reflected in all otheroccurrences of the same value (e.g.ast.Add).

ast Helpers

Apart from the node classes, theast module defines these utility functionsand classes for traversing abstract syntax trees:

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

Parse the source into an AST node. Equivalent tocompile(source,filename,mode,flags=FLAGS_VALUE,optimize=optimize),whereFLAGS_VALUE isast.PyCF_ONLY_AST ifoptimize<=0andast.PyCF_OPTIMIZED_AST otherwise.

Iftype_comments=True is given, the parser is modified to checkand return type comments as specified byPEP 484 andPEP 526.This is equivalent to addingast.PyCF_TYPE_COMMENTS to theflags passed tocompile(). This will report syntax errorsfor misplaced type comments. Without this flag, type comments willbe ignored, and thetype_comment field on selected AST nodeswill always beNone. In addition, the locations of#type:ignore comments will be returned as thetype_ignoresattribute ofModule (otherwise it is always an empty list).

In addition, ifmode is'func_type', the input syntax ismodified to correspond toPEP 484 “signature type comments”,e.g.(str,int)->List[str].

Settingfeature_version to a tuple(major,minor) will result ina “best-effort” attempt to parse using that Python version’s grammar.For example, settingfeature_version=(3,9) will attempt to disallowparsing ofmatch statements.Currentlymajor must equal to3. The lowest supported version is(3,7) (and this may increase in future Python versions);the highest issys.version_info[0:2]. “Best-effort” attempt means thereis no guarantee that the parse (or success of the parse) is the same aswhen run on the Python version corresponding tofeature_version.

If source contains a null character (\0),ValueError is raised.

Warning

Note that successfully parsing source code into an AST object doesn’tguarantee that the source code provided is valid Python code that canbe executed as the compilation step can raise furtherSyntaxErrorexceptions. For instance, the sourcereturn42 generates a validAST node for a return statement, but it cannot be compiled alone (it needsto be inside a function node).

In particular,ast.parse() won’t do any scoping checks, which thecompilation step does.

Warning

It is possible to crash the Python interpreter with asufficiently large/complex string due to stack depth limitationsin Python’s AST compiler.

Changed in version 3.8:Addedtype_comments,mode='func_type' andfeature_version.

Changed in version 3.13:The minimum supported version forfeature_version is now(3,7).Theoptimize argument was added.

ast.unparse(ast_obj)

Unparse anast.AST object and generate a string with codethat would produce an equivalentast.AST object if parsedback withast.parse().

Warning

The produced code string will not necessarily be equal to the originalcode that generated theast.AST object (without any compileroptimizations, such as constant tuples/frozensets).

Warning

Trying to unparse a highly complex expression would result withRecursionError.

Added in version 3.9.

ast.literal_eval(node_or_string)

Evaluate an expression node or a string containing only a Python literal orcontainer display. The string or node provided may only consist of thefollowing Python literal structures: strings, bytes, numbers, tuples, lists,dicts, sets, booleans,None andEllipsis.

This can be used for evaluating strings containing Python values without theneed to parse the values oneself. It is not capable of evaluatingarbitrarily complex expressions, for example involving operators orindexing.

This function had been documented as “safe” in the past without definingwhat that meant. That was misleading. This is specifically designed not toexecute Python code, unlike the more generaleval(). There is nonamespace, no name lookups, or ability to call out. But it is not free fromattack: A relatively small input can lead to memory exhaustion or to C stackexhaustion, crashing the process. There is also the possibility forexcessive CPU consumption denial of service on some inputs. Calling it onuntrusted data is thus not recommended.

Warning

It is possible to crash the Python interpreter due to stack depthlimitations in Python’s AST compiler.

It can raiseValueError,TypeError,SyntaxError,MemoryError andRecursionError depending on the malformedinput.

Changed in version 3.2:Now allows bytes and set literals.

Changed in version 3.9:Now supports creating empty sets with'set()'.

Changed in version 3.10:For string inputs, leading spaces and tabs are now stripped.

ast.get_docstring(node,clean=True)

Return the docstring of the givennode (which must be aFunctionDef,AsyncFunctionDef,ClassDef,orModule node), orNone if it has no docstring.Ifclean is true, clean up the docstring’s indentation withinspect.cleandoc().

Changed in version 3.5:AsyncFunctionDef is now supported.

ast.get_source_segment(source,node,*,padded=False)

Get source code segment of thesource that generatednode.If some location information (lineno,end_lineno,col_offset, orend_col_offset) is missing, returnNone.

Ifpadded isTrue, the first line of a multi-line statement willbe padded with spaces to match its original position.

Added in version 3.8.

ast.fix_missing_locations(node)

When you compile a node tree withcompile(), the compiler expectslineno andcol_offset attributes for every node that supportsthem. This is rather tedious to fill in for generated nodes, so this helperadds these attributes recursively where not already set, by setting them tothe values of the parent node. It works recursively starting atnode.

ast.increment_lineno(node,n=1)

Increment the line number and end line number of each node in the treestarting atnode byn. This is useful to “move code” to a differentlocation in a file.

ast.copy_location(new_node,old_node)

Copy source location (lineno,col_offset,end_lineno,andend_col_offset) fromold_node tonew_node if possible,and returnnew_node.

ast.iter_fields(node)

Yield a tuple of(fieldname,value) for each field innode._fieldsthat is present onnode.

ast.iter_child_nodes(node)

Yield all direct child nodes ofnode, that is, all fields that are nodesand all items of fields that are lists of nodes.

ast.walk(node)

Recursively yield all descendant nodes in the tree starting atnode(includingnode itself), in no specified order. This is useful if you onlywant to modify nodes in place and don’t care about the context.

classast.NodeVisitor

A node visitor base class that walks the abstract syntax tree and calls avisitor function for every node found. This function may return a valuewhich is forwarded by thevisit() method.

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

visit(node)

Visit a node. The default implementation calls the method calledself.visit_classname whereclassname is the name of the nodeclass, orgeneric_visit() if that method doesn’t exist.

generic_visit(node)

This visitor callsvisit() on all children of the node.

Note that child nodes of nodes that have a custom visitor method won’t bevisited unless the visitor callsgeneric_visit() or visits themitself.

visit_Constant(node)

Handles all constant nodes.

Don’t use theNodeVisitor if you want to apply changes to nodesduring traversal. For this a special visitor exists(NodeTransformer) that allows modifications.

Deprecated since version 3.8:Methodsvisit_Num(),visit_Str(),visit_Bytes(),visit_NameConstant() andvisit_Ellipsis() are deprecatednow and will not be called in future Python versions. Add thevisit_Constant() method to handle all constant nodes.

classast.NodeTransformer

ANodeVisitor subclass that walks the abstract syntax tree andallows modification of nodes.

TheNodeTransformer will walk the AST and use the return value ofthe visitor methods to replace or remove the old node. If the return valueof the visitor method isNone, the node will be removed from itslocation, otherwise it is replaced with the return value. The return valuemay be the original node in which case no replacement takes place.

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

classRewriteName(NodeTransformer):defvisit_Name(self,node):returnSubscript(value=Name(id='data',ctx=Load()),slice=Constant(value=node.id),ctx=node.ctx)

Keep in mind that if the node you’re operating on has child nodes you musteither transform the child nodes yourself or call thegeneric_visit()method for the node first.

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

IfNodeTransformer introduces new nodes (that weren’t part oforiginal tree) without giving them location information (such aslineno),fix_missing_locations() should be called withthe 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)
ast.dump(node,annotate_fields=True,include_attributes=False,*,indent=None,show_empty=False)

Return a formatted dump of the tree innode. This is mainly useful fordebugging purposes. Ifannotate_fields is true (by default),the returned string will show the names and the values for fields.Ifannotate_fields is false, the result string will be more compact byomitting unambiguous field names. Attributes such as linenumbers and column offsets are not dumped by default. If this is wanted,include_attributes can be set to true.

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

Ifshow_empty isFalse (the default), empty lists and fields that areNonewill be omitted from the output.

Changed in version 3.9:Added theindent option.

Changed in version 3.13:Added theshow_empty option.

>>>print(ast.dump(ast.parse("""\...async def f():...    await other_func()..."""),indent=4,show_empty=True))Module(    body=[        AsyncFunctionDef(            name='f',            args=arguments(                posonlyargs=[],                args=[],                kwonlyargs=[],                kw_defaults=[],                defaults=[]),            body=[                Expr(                    value=Await(                        value=Call(                            func=Name(id='other_func', ctx=Load()),                            args=[],                            keywords=[])))],            decorator_list=[],            type_params=[])],    type_ignores=[])

Compiler Flags

The following flags may be passed tocompile() in order to changeeffects on the compilation of a program:

ast.PyCF_ALLOW_TOP_LEVEL_AWAIT

Enables support for top-levelawait,asyncfor,asyncwithand async comprehensions.

Added in version 3.8.

ast.PyCF_ONLY_AST

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

ast.PyCF_OPTIMIZED_AST

The returned AST is optimized according to theoptimize argumentincompile() orast.parse().

Added in version 3.13.

ast.PyCF_TYPE_COMMENTS

Enables support forPEP 484 andPEP 526 style type comments(#type:<type>,#type:ignore<stuff>).

Added in version 3.8.

Command-Line Usage

Added in version 3.9.

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

python-mast[-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 themode argumentinparse().

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

Ifinfile is specified its contents are parsed to AST and dumpedto stdout. Otherwise, the content is read from stdin.

See also

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

ASTTokensannotates Python ASTs with the positions of tokens and text in the sourcecode that generated them. This is helpful for tools that make source codetransformations.

leoAst.pyunifies thetoken-based and parse-tree-based views of python programs by insertingtwo-way links between tokens and ast nodes.

LibCST parses code as a Concrete SyntaxTree that looks like an ast tree and keeps all formatting details. It’suseful for building automated refactoring (codemod) applications andlinters.

Parso is a Python parser that supportserror recovery and round-trip parsing for different Python versions (inmultiple Python versions). Parso is also able to list multiple syntax errorsin your Python file.