ast — Abstract syntax trees¶
Source code: Lib/ast.py
The ast 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 as
a flag to the compile() built-in function, or using the parse()
helper provided in this module. The result will be a tree of objects whose
classes all inherit from ast.AST. An abstract syntax tree can be
compiled into a Python code object using the built-in compile() function.
Abstract grammar¶
The abstract grammar is currently defined as follows:
-- ASDL's 4 builtin types are:
-- identifier, int, string, constant
module Python
{
mod = Module(stmt* body, type_ignore* type_ignores)
| Interactive(stmt* body)
| Expression(expr body)
| FunctionType(expr* argtypes, expr returns)
stmt = FunctionDef(identifier name, arguments args,
stmt* body, expr* decorator_list, expr? returns,
string? type_comment, type_param* type_params)
| AsyncFunctionDef(identifier name, arguments args,
stmt* body, expr* decorator_list, expr? returns,
string? type_comment, type_param* type_params)
| ClassDef(identifier name,
expr* bases,
keyword* keywords,
stmt* body,
expr* decorator_list,
type_param* type_params)
| Return(expr? value)
| Delete(expr* targets)
| Assign(expr* targets, expr value, string? type_comment)
| TypeAlias(expr name, type_param* type_params, expr value)
| AugAssign(expr target, operator op, expr value)
-- 'simple' indicates that we annotate simple name without parens
| AnnAssign(expr target, expr annotation, expr? value, int simple)
-- use 'orelse' because else is a keyword in target languages
| For(expr target, expr iter, stmt* body, stmt* orelse, string? type_comment)
| AsyncFor(expr target, expr iter, stmt* body, stmt* orelse, string? type_comment)
| While(expr test, stmt* body, stmt* orelse)
| If(expr test, stmt* body, stmt* orelse)
| With(withitem* items, stmt* body, string? type_comment)
| AsyncWith(withitem* items, stmt* body, string? type_comment)
| Match(expr subject, 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(expr test, expr? msg)
| Import(alias* names)
| ImportFrom(identifier? module, alias* names, int? level)
| Global(identifier* names)
| Nonlocal(identifier* names)
| Expr(expr value)
| Pass | Break | Continue
-- col_offset is the byte offset in the utf8 string the parser uses
attributes (int lineno, int col_offset, int? end_lineno, int? end_col_offset)
-- BoolOp() can use left & right?
expr = BoolOp(boolop op, expr* values)
| NamedExpr(expr target, expr value)
| BinOp(expr left, operator op, expr right)
| UnaryOp(unaryop op, expr operand)
| Lambda(arguments args, expr body)
| IfExp(expr test, expr body, expr orelse)
| Dict(expr?* keys, expr* values)
| Set(expr* elts)
| ListComp(expr elt, comprehension* generators)
| SetComp(expr elt, comprehension* generators)
| DictComp(expr key, expr value, comprehension* generators)
| GeneratorExp(expr elt, comprehension* generators)
-- the grammar constrains where yield expressions can occur
| Await(expr value)
| Yield(expr? value)
| YieldFrom(expr value)
-- need sequences for compare to distinguish between
-- x < 4 < 3 and (x < 4) < 3
| Compare(expr left, cmpop* ops, expr* comparators)
| Call(expr func, expr* args, keyword* keywords)
| FormattedValue(expr value, int conversion, expr? format_spec)
| Interpolation(expr value, constant str, int conversion, expr? format_spec)
| JoinedStr(expr* values)
| TemplateStr(expr* values)
| Constant(constant value, string? kind)
-- the following expression can appear in assignment context
| Attribute(expr value, identifier attr, expr_context ctx)
| Subscript(expr value, expr slice, expr_context ctx)
| Starred(expr value, expr_context ctx)
| Name(identifier id, expr_context ctx)
| List(expr* elts, expr_context ctx)
| Tuple(expr* elts, expr_context ctx)
-- can appear only in Subscript
| Slice(expr? lower, expr? upper, expr? step)
-- col_offset is the byte offset in the utf8 string the parser uses
attributes (int lineno, int col_offset, int? end_lineno, int? end_col_offset)
expr_context = Load | Store | Del
boolop = And | Or
operator = Add | Sub | Mult | MatMult | Div | Mod | Pow | LShift
| RShift | BitOr | BitXor | BitAnd | FloorDiv
unaryop = Invert | Not | UAdd | USub
cmpop = Eq | NotEq | Lt | LtE | Gt | GtE | Is | IsNot | In | NotIn
comprehension = (expr target, expr iter, expr* ifs, int is_async)
excepthandler = ExceptHandler(expr? type, identifier? name, stmt* body)
attributes (int lineno, int col_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 = (identifier arg, expr? annotation, string? type_comment)
attributes (int lineno, int col_offset, int? end_lineno, int? end_col_offset)
-- keyword arguments supplied to call (NULL identifier for **kwargs)
keyword = (identifier? arg, expr value)
attributes (int lineno, int col_offset, int? end_lineno, int? end_col_offset)
-- import name with optional 'as' alias.
alias = (identifier name, identifier? asname)
attributes (int lineno, int col_offset, int? end_lineno, int? end_col_offset)
withitem = (expr context_expr, expr? optional_vars)
match_case = (pattern pattern, expr? guard, stmt* body)
pattern = MatchValue(expr value)
| MatchSingleton(constant value)
| MatchSequence(pattern* patterns)
| MatchMapping(expr* keys, pattern* patterns, identifier? rest)
| MatchClass(expr cls, 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 (int lineno, int col_offset, int end_lineno, int end_col_offset)
type_ignore = TypeIgnore(int lineno, string tag)
type_param = TypeVar(identifier name, expr? bound, expr? default_value)
| ParamSpec(identifier name, expr? default_value)
| TypeVarTuple(identifier name, expr? default_value)
attributes (int lineno, int col_offset, int end_lineno, int end_col_offset)
}
Node classes¶
- class ast.AST¶
This is the base of all AST node classes. The actual node classes are derived from the
Parser/Python.asdlfile, which is reproduced above. They are defined in the_astC module and re-exported inast.There is one class defined for each left-hand side symbol in the abstract grammar (for example,
ast.stmtorast.expr). 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.BinOpinherits fromast.expr. For production rules with alternatives (aka “sums”), the left-hand side class is abstract: only instances of specific constructor nodes are ever created.- _fields¶
Each concrete class has an attribute
_fieldswhich 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.BinOpinstances have an attributeleftof typeast.expr.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 withcompile().
- _field_types¶
The
_field_typesattribute on each concrete class is a dictionary mapping 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 of
ast.exprandast.stmtsubclasses havelineno,col_offset,end_lineno, andend_col_offsetattributes. Thelinenoandend_linenoare the first and last line numbers of source text span (1-indexed so the first line is line 1) and thecol_offsetandend_col_offsetare 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.Tparses its arguments as follows:If there are positional arguments, there must be as many as there are items in
T._fields; 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.UnaryOpnode, you could usenode = 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 typeast.expr_contextis omitted, it defaults toLoad(). If any other field is omitted, aDeprecationWarningis raised and the AST node will not have this field. In Python 3.15, this condition will raise an error.
Changed in version 3.8: Class ast.Constant is now used for all constants.
Changed in version 3.9: Simple indices are represented by their value, extended slices are represented as tuples.
Changed in version 3.14: The __repr__() output of AST nodes includes
the values of the node fields.
Deprecated since version 3.8: Old classes ast.Num, ast.Str, ast.Bytes,
ast.NameConstant and ast.Ellipsis are still available,
but they will be removed in future Python releases. In the meantime,
instantiating them will return an instance of a different class.
Deprecated since version 3.9: Old classes ast.Index and ast.ExtSlice are still
available, but they will be removed in future Python releases.
In the meantime, instantiating them will return an instance of
a different class.
Deprecated since version 3.13, will be removed in version 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
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¶
- class ast.Module(body, type_ignores)¶
A Python module, as with file input. Node type generated by
ast.parse()in the default"exec"mode.bodyis alistof the module’s Statements.type_ignoresis alistof 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))])
- class ast.Expression(body)¶
A single Python expression input. Node type generated by
ast.parse()when mode is"eval".bodyis a single node, one of the expression types.>>> print(ast.dump(ast.parse('123', mode='eval'), indent=4)) Expression( body=Constant(value=123))
- class ast.Interactive(body)¶
A single interactive input, like in Interactive Mode. Node type generated by
ast.parse()when mode is"single".bodyis alistof statement 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))])
- class ast.FunctionType(argtypes, returns)¶
A representation of an old-style type comments for functions, as Python versions prior to 3.5 didn’t support PEP 484 annotations. Node type generated by
ast.parse()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
argtypesis alistof expression nodes.returnsis a single expression 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¶
- class ast.Constant(value)¶
A constant value. The
valueattribute of theConstantliteral contains the Python object it represents. The values represented can be instances ofstr,bytes,int,float,complex, andbool, and the constantsNoneandEllipsis.>>> print(ast.dump(ast.parse('123', mode='eval'), indent=4)) Expression( body=Constant(value=123))
- class ast.FormattedValue(value, conversion, format_spec)¶
Node representing a single formatting field in an f-string. If the string contains a single formatting field and nothing else the node can be isolated otherwise it appears in
JoinedStr.valueis any expression node (such as a literal, a variable, or a function call).conversionis an integer:format_specis aJoinedStrnode representing the formatting of the value, orNoneif no format was specified. Bothconversionandformat_speccan be set at the same time.
- class ast.JoinedStr(values)¶
An f-string, comprising a series of
FormattedValueandConstantnodes.>>> 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')]))]))
- class ast.TemplateStr(values, /)¶
Added in version 3.14.
Node representing a template string literal, comprising a series of
InterpolationandConstantnodes. These nodes may be any order, and do not need to be interleaved.>>> 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', ctx=Load()), str='name', conversion=-1), Constant(value=' finished '), Interpolation( value=Name(id='place', ctx=Load()), str='place', conversion=-1, format_spec=JoinedStr( values=[ Constant(value='ordinal')]))]))
- class ast.Interpolation(value, str, conversion, format_spec=None)¶
Added in version 3.14.
Node representing a single interpolation field in a template string literal.
valueis any expression node (such as a literal, a variable, or a function call). This has the same meaning asFormattedValue.value.stris a constant containing the text of the interpolation expression.If
stris set toNone, thenvalueis used to generate code when callingast.unparse(). This no longer guarantees that the generated code is identical to the original and is intended for code generation.conversionis an integer:-1: no conversion
97 (
ord('a')):!aASCIIconversion114 (
ord('r')):!rrepr()conversion115 (
ord('s')):!sstringconversion
This has the same meaning as
FormattedValue.conversion.format_specis aJoinedStrnode representing the formatting of the value, orNoneif no format was specified. Bothconversionandformat_speccan be set at the same time. This has the same meaning asFormattedValue.format_spec.
- class ast.List(elts, ctx)¶
- class ast.Tuple(elts, ctx)¶
A list or tuple.
eltsholds a list of nodes representing the elements.ctxisStoreif the container is an assignment target (i.e.(x,y)=something), andLoadotherwise.>>> 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()))
- class ast.Set(elts)¶
A set.
eltsholds 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)]))
- class ast.Dict(keys, values)¶
A dictionary.
keysandvalueshold lists of nodes representing the keys and the values respectively, in matching order (what would be returned when callingdictionary.keys()anddictionary.values()).When doing dictionary unpacking using dictionary literals the expression to be expanded goes in the
valueslist, with aNoneat the corresponding position 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¶
- class ast.Name(id, ctx)¶
A variable name.
idholds the name as a string, andctxis one of the following types.
- class ast.Load¶
- class ast.Store¶
- class ast.Del¶
Variable references can be used to load the value of a variable, to assign a new value to it, or to delete it. Variable references are given a context to distinguish these cases.
>>> 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())])])
- class ast.Starred(value, ctx)¶
A
*varvariable reference.valueholds the variable, typically aNamenode. 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¶
- class ast.Expr(value)¶
When an expression, such as a function call, appears as a statement by itself with its return value not used or stored, it is wrapped in this container.
valueholds one of the other nodes in this section, aConstant, aName, aLambda, aYieldorYieldFromnode.>>> print(ast.dump(ast.parse('-a'), indent=4)) Module( body=[ Expr( value=UnaryOp( op=USub(), operand=Name(id='a', ctx=Load())))])
- class ast.UnaryOp(op, operand)¶
A unary operation.
opis the operator, andoperandany expression node.
- class ast.UAdd¶
- class ast.USub¶
- class ast.Not¶
- class ast.Invert¶
Unary operator tokens.
Notis thenotkeyword,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())))
- class ast.BinOp(left, op, right)¶
A binary operation (like addition or division).
opis the operator, andleftandrightare 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())))
- class ast.Add¶
- class ast.Sub¶
- class ast.Mult¶
- class ast.Div¶
- class ast.FloorDiv¶
- class ast.Mod¶
- class ast.Pow¶
- class ast.LShift¶
- class ast.RShift¶
- class ast.BitOr¶
- class ast.BitXor¶
- class ast.BitAnd¶
- class ast.MatMult¶
Binary operator tokens.
- class ast.BoolOp(op, values)¶
A boolean operation, ‘or’ or ‘and’.
opisOrorAnd.valuesare the values involved. Consecutive operations with the same operator, such asa or b or c, are collapsed into one node with several values.This doesn’t include
not, 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())]))
- class ast.Compare(left, ops, comparators)¶
A comparison of two or more values.
leftis the first value in the comparison,opsthe list of operators, andcomparatorsthe list of 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)]))
- class ast.Eq¶
- class ast.NotEq¶
- class ast.Lt¶
- class ast.LtE¶
- class ast.Gt¶
- class ast.GtE¶
- class ast.Is¶
- class ast.IsNot¶
- class ast.In¶
- class ast.NotIn¶
Comparison operator tokens.
- class ast.Call(func, args, keywords)¶
A function call.
funcis the function, which will often be aNameorAttributeobject. Of the arguments:argsholds a list of the arguments passed by position.keywordsholds a list ofkeywordobjects representing arguments passed by keyword.
The
argsandkeywordsarguments 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()))]))
- class ast.keyword(arg, value)¶
A keyword argument to a function call or class definition.
argis a raw string of the parameter name,valueis a node to pass in.
- class ast.IfExp(test, body, orelse)¶
An expression such as
a if b else c. Each field holds a single node, so in the following example, all three areNamenodes.>>> 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())))
- class ast.Attribute(value, attr, ctx)¶
Attribute access, e.g.
d.keys.valueis a node, typically aName.attris a bare string giving the name of the attribute, andctxisLoad,StoreorDelaccording to how the 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()))
- class ast.NamedExpr(target, value)¶
A named expression. This AST node is produced by the assignment expressions operator (also known as the walrus operator). As opposed to the
Assignnode in which the first argument can be multiple nodes, in this case bothtargetandvaluemust 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¶
- class ast.Subscript(value, slice, ctx)¶
A subscript, such as
l[1].valueis the subscripted object (usually sequence or mapping).sliceis an index, slice or key. It can be aTupleand contain aSlice.ctxisLoad,StoreorDelaccording 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()))
- class ast.Slice(lower, upper, step)¶
Regular slicing (on the form
lower:upperorlower:upper:step). Can occur only inside the slice field ofSubscript, either directly 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¶
- class ast.ListComp(elt, generators)¶
- class ast.SetComp(elt, generators)¶
- class ast.GeneratorExp(elt, generators)¶
- class ast.DictComp(key, value, generators)¶
List and set comprehensions, generator expressions, and dictionary comprehensions.
elt(orkeyandvalue) is a single node representing the part that will be evaluated for each item.generatorsis a list ofcomprehensionnodes.>>> 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)]))
- class ast.comprehension(target, iter, ifs, is_async)¶
One
forclause in a comprehension.targetis the reference to use for each element - typically aNameorTuplenode.iteris the object to iterate over.ifsis a list of test expressions: eachforclause can have multipleifs.is_asyncindicates a comprehension is asynchronous (using anasync forinstead 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 comprehension Expression( 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 comprehension Expression( 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¶
- class ast.Assign(targets, value, type_comment)¶
An assignment.
targetsis a list of nodes, andvalueis a single node.Multiple nodes in
targetsrepresents assigning the same value to each. Unpacking is represented by putting aTupleorListwithintargets.- type_comment¶
type_commentis an optional string with the type annotation as a comment.
>>> 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', ctx=Load()))])
- class ast.AnnAssign(target, annotation, value, simple)¶
An assignment with a type annotation.
targetis a single node and can be aName, anAttributeor aSubscript.annotationis the annotation, such as aConstantorNamenode.valueis a single optional node.simpleis always either 0 (indicating a “complex” target) or 1 (indicating a “simple” target). A “simple” target consists solely of aNamenode that does not appear between parentheses; all other targets are considered complex. Only simple targets appear in the__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 parenthesis Module( 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 annotation Module( 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 annotation Module( body=[ AnnAssign( target=Subscript( value=Name(id='a', ctx=Load()), slice=Constant(value=1), ctx=Store()), annotation=Name(id='int', ctx=Load()), simple=0)])
- class ast.AugAssign(target, op, value)¶
Augmented assignment, such as
a += 1. In the following example,targetis aNamenode forx(with theStorecontext),opisAdd, andvalueis aConstantwith value for 1.The
targetattribute cannot be of classTupleorList, 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))])
- class ast.Raise(exc, cause)¶
A
raisestatement.excis the exception object to be raised, normally aCallorName, orNonefor a standaloneraise.causeis the optional part foryinraise x from y.>>> 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()))])
- class ast.Assert(test, msg)¶
An assertion.
testholds the condition, such as aComparenode.msgholds 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()))])
- class ast.Delete(targets)¶
Represents a
delstatement.targetsis a list of nodes, such asName,AttributeorSubscriptnodes.>>> 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())])])
- class ast.Pass¶
A
passstatement.>>> print(ast.dump(ast.parse('pass'), indent=4)) Module( body=[ Pass()])
- class ast.TypeAlias(name, type_params, value)¶
A type alias created through the
typestatement.nameis the name of the alias,type_paramsis a list of type parameters, andvalueis the value of the type 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 are described in other sections.
Imports¶
- class ast.Import(names)¶
An import statement.
namesis a list ofaliasnodes.>>> print(ast.dump(ast.parse('import x,y,z'), indent=4)) Module( body=[ Import( names=[ alias(name='x'), alias(name='y'), alias(name='z')])])
- class ast.ImportFrom(module, names, level)¶
Represents
from x import y.moduleis a raw string of the ‘from’ name, without any leading dots, orNonefor statements such asfrom . import foo.levelis an integer holding the level of the relative import (0 means absolute 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)])
- class ast.alias(name, asname)¶
Both parameters are raw strings of the names.
asnamecan beNoneif the 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 as else are stored as an empty list if they’re
not present.
- class ast.If(test, body, orelse)¶
An
ifstatement.testholds a single node, such as aComparenode.bodyandorelseeach hold a list of nodes.elifclauses don’t have a special representation in the AST, but rather appear as extraIfnodes within theorelsesection of the previous 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))])])])
- class ast.For(target, iter, body, orelse, type_comment)¶
A
forloop.targetholds the variable(s) the loop assigns to, as a singleName,Tuple,List,AttributeorSubscriptnode.iterholds the item to be looped over, again as a single node.bodyandorelsecontain lists of nodes to execute. Those inorelseare executed if the loop finishes normally, rather than via abreakstatement.- type_comment¶
type_commentis 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))])])
- class ast.While(test, body, orelse)¶
A
whileloop.testholds 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))])])
- class ast.Break¶
- class ast.Continue¶
The
breakandcontinuestatements.>>> 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()])])])
- class ast.Try(body, handlers, orelse, finalbody)¶
tryblocks. All attributes are list of nodes to execute, except forhandlers, which is a list ofExceptHandlernodes.>>> 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))])])
- class ast.TryStar(body, handlers, orelse, finalbody)¶
tryblocks which are followed byexcept*clauses. The attributes are the same as forTrybut theExceptHandlernodes 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.
- class ast.ExceptHandler(type, name, body)¶
A single
exceptclause.typeis the exception type it will match, typically aNamenode (orNonefor a catch-allexcept:clause).nameis a raw string for the name to hold the exception, orNoneif the clause doesn’t haveas foo.bodyis 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()])])])
- class ast.With(items, body, type_comment)¶
A
withblock.itemsis a list ofwithitemnodes representing the context managers, andbodyis the indented block inside the context.- type_comment¶
type_commentis an optional string with the type annotation as a comment.
- class ast.withitem(context_expr, optional_vars)¶
A single context manager in a
withblock.context_expris the context manager, often aCallnode.optional_varsis aName,TupleorListfor theas foopart, orNoneif that isn’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¶
- class ast.Match(subject, cases)¶
A
matchstatement.subjectholds the subject of the match (the object that is being matched against the cases) andcasescontains an iterable ofmatch_casenodes with the different cases.Added in version 3.10.
- class ast.match_case(pattern, guard, body)¶
A single case pattern in a
matchstatement.patterncontains the match pattern that the subject will be matched against. Note that theASTnodes produced for patterns differ from those produced for expressions, even when they share the same syntax.The
guardattribute contains an expression that will be evaluated if the pattern matches the subject.bodycontains a list of nodes to execute if the pattern matches and the 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.
- class ast.MatchValue(value)¶
A match literal or value pattern that compares by equality.
valueis 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.>>> 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.
- class ast.MatchSingleton(value)¶
A match literal pattern that compares by identity.
valueis the singleton to be compared against:None,True, orFalse. This pattern 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.
- class ast.MatchSequence(patterns)¶
A match sequence pattern.
patternscontains 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 aMatchStarnode, otherwise matches 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.
- class ast.MatchStar(name)¶
Matches the rest of the sequence in a variable length match sequence pattern. If
nameis notNone, a list containing the remaining sequence elements 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.
- class ast.MatchMapping(keys, patterns, rest)¶
A match mapping pattern.
keysis a sequence of expression nodes.patternsis a corresponding sequence of pattern nodes.restis 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
restis notNone, a dict containing the remaining mapping elements is bound to that name if the overall mapping 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.
- class ast.MatchClass(cls, patterns, kwd_attrs, kwd_patterns)¶
A match class pattern.
clsis an expression giving the nominal class to be matched.patternsis a sequence of pattern nodes to be matched against the class defined sequence of pattern matching attributes.kwd_attrsis a sequence of additional attributes to be matched (specified as keyword arguments in the class pattern),kwd_patternsare 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.
>>> 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.
- class ast.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 a bare name) and will always succeed.The
nameattribute contains the name that will be bound if the pattern is successful. IfnameisNone,patternmust 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.
- class ast.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
patternsattribute contains a list of match pattern nodes that will be matched 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¶
- class ast.TypeIgnore(lineno, tag)¶
A
# type: ignorecomment located at lineno. 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
TypeIgnorenodes are not generated when the type_comments parameter is set toFalse(default). Seeast.parse()for more details.Added in version 3.8.
Type parameters¶
Type parameters can exist on classes, functions, and type aliases.
- class ast.TypeVar(name, bound, default_value)¶
A
typing.TypeVar.nameis the name of the type variable.boundis the bound or constraints, if any. Ifboundis aTuple, it represents constraints; otherwise it represents the bound.default_valueis the default value; if theTypeVarhas no default, this attribute 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 the default_value parameter.
- class ast.ParamSpec(name, default_value)¶
A
typing.ParamSpec.nameis the name of the parameter specification.default_valueis the default value; if theParamSpechas 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 the default_value parameter.
- class ast.TypeVarTuple(name, default_value)¶
A
typing.TypeVarTuple.nameis the name of the type variable tuple.default_valueis the default value; if theTypeVarTuplehas no default, 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 the default_value parameter.
Function and class definitions¶
- class ast.FunctionDef(name, args, body, decorator_list, returns, type_comment, type_params)¶
A function definition.
nameis a raw string of the function name.argsis an