ast
— Árboles de sintaxis abstracta¶
Código fuente: Lib/ast.py
El módulo ast
ayuda a las aplicaciones de Python a procesar árboles de la gramática de sintaxis abstracta de Python. La sintaxis abstracta en sí misma puede cambiar con cada versión de Python; Este módulo ayuda a descubrir mediante programación cómo se ve la gramática actual.
Se puede generar un árbol de sintaxis abstracta pasando ast.PyCF_ONLY_AST
como un indicador de la función incorporada compile()
, o usando el ayudante parse()
provisto en este módulo. El resultado será un árbol de objetos cuyas clases todas heredan de ast.AST
. Se puede compilar un árbol de sintaxis abstracta en un objeto de código Python utilizando la función incorporada compile()
.
Gramática abstracta¶
La gramática abstracta se define actualmente de la siguiente manera:
-- 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)
| AsyncFunctionDef(identifier name, arguments args,
stmt* body, expr* decorator_list, expr? returns,
string? type_comment)
| ClassDef(identifier name,
expr* bases,
keyword* keywords,
stmt* body,
expr* decorator_list)
| Return(expr? value)
| Delete(expr* targets)
| Assign(expr* targets, expr value, string? type_comment)
| 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)
| Raise(expr? exc, expr? cause)
| Try(stmt* body, excepthandler* handlers, stmt* orelse, stmt* finalbody)
| Assert(expr test, expr? msg)
| Import(alias* names)
| ImportFrom(identifier? module, alias* names, int? level)
| Global(identifier* names)
| Nonlocal(identifier* names)
| Expr(expr value)
| Pass | Break | Continue
-- 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)
| JoinedStr(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)
withitem = (expr context_expr, expr? optional_vars)
type_ignore = TypeIgnore(int lineno, string tag)
}
Clases Nodo¶
-
class
ast.
AST
¶ Esta es la base de todas las clases de nodo AST. Las clases de nodo reales se derivan del archivo
Parser/Python.asdl
, que se reproduce abajo. Se definen en el módulo_ast
C y se reexportan enast
.Hay una clase definida para cada símbolo del lado izquierdo en la gramática abstracta (por ejemplo,
ast.stmt
oast.expr
). Además, hay una clase definida para cada constructor en el lado derecho; estas clases heredan de las clases para los árboles del lado izquierdo. Por ejemplo,ast.BinOp
hereda deast.expr
. Para las reglas de producción con alternativas (también conocidas como «sumas»), la clase del lado izquierdo es abstracta: solo se crean instancias de nodos de constructor específicos.-
_fields
¶ Cada clase concreta tiene un atributo
_fields
que proporciona los nombres de todos los nodos secundarios.Cada instancia de una clase concreta tiene un atributo para cada nodo secundario, del tipo definido en la gramática. Por ejemplo, las instancias
ast.BinOp
tienen un atributoleft
de tipoast.expr
.Si estos atributos están marcados como opcionales en la gramática (usando un signo de interrogación), el valor podría ser
None
. Si los atributos pueden tener cero o más valores (marcados con un asterisco), los valores se representan como listas de Python. Todos los atributos posibles deben estar presentes y tener valores válidos al compilar un AST concompile()
.
-
lineno
¶ -
col_offset
¶ -
end_lineno
¶ -
end_col_offset
¶ Instances of
ast.expr
andast.stmt
subclasses havelineno
,col_offset
,end_lineno
, andend_col_offset
attributes. Thelineno
andend_lineno
are the first and last line numbers of the source text span (1-indexed so the first line is line 1), and thecol_offset
andend_col_offset
are the corresponding UTF-8 byte offsets of the first and last tokens that generated the node. The UTF-8 offset is recorded because the parser uses UTF-8 internally.Tenga en cuenta que el compilador no requiere las posiciones finales y, por lo tanto, son opcionales. El desplazamiento final es después del último símbolo, por ejemplo, uno puede obtener el segmento fuente de un nodo de expresión de una línea usando
source_line[node.col_offset: node.end_col_offset]
.
El constructor de una clase
ast.T
analiza sus argumentos de la siguiente manera:Si hay argumentos posicionales, debe haber tantos como elementos en
T._fields
; serán asignados como atributos de estos nombres.Si hay argumentos de palabras clave, establecerán los atributos de los mismos nombres a los valores dados.
Por ejemplo, para crear y completar un nodo
ast.UnaryOp
, puede usarnode = ast.UnaryOp() node.op = ast.USub() node.operand = ast.Constant() node.operand.value = 5 node.operand.lineno = 0 node.operand.col_offset = 0 node.lineno = 0 node.col_offset = 0
o la más compacta
node = ast.UnaryOp(ast.USub(), ast.Constant(5, lineno=0, col_offset=0), lineno=0, col_offset=0)
-
Distinto en la versión 3.8: La clase ast.Constant
ahora se usa para todas las constantes.
Distinto en la versión 3.9: Simple indices are represented by their value, extended slices are represented as tuples.
Obsoleto desde la versión 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.
Obsoleto desde la versión 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.
Nota
The descriptions of the specific node classes displayed here were initially adapted from the fantastic Green Tree Snakes project and all its contributors.
Literals¶
-
class
ast.
Constant
(value)¶ A constant value. The
value
attribute of theConstant
literal contains the Python object it represents. The values represented can be simple types such 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))
-
class
ast.
FormattedValue
(value, conversion, format_spec)¶ Node representing a single formatting field in an f-string. If the string contains a single formatting field and nothing else the node can be isolated otherwise it appears in
JoinedStr
.value
is any expression node (such as a literal, a variable, or a function call).conversion
is an integer:-1: no formatting
115:
!s
string formatting114:
!r
repr formatting97:
!a
ascii formatting
format_spec
is aJoinedStr
node representing the formatting of the value, orNone
if no format was specified. Bothconversion
andformat_spec
can be set at the same time.
-
class
ast.
JoinedStr
(values)¶ An f-string, comprising a series of
FormattedValue
andConstant
nodes.>>> 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())], keywords=[]), conversion=-1, format_spec=JoinedStr( values=[ Constant(value='.3')]))]))
-
class
ast.
List
(elts, ctx)¶ -
class
ast.
Tuple
(elts, ctx)¶ A list or tuple.
elts
holds a list of nodes representing the elements.ctx
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()))
-
class
ast.
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)]))
-
class
ast.
Dict
(keys, values)¶ A dictionary.
keys
andvalues
hold 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
values
list, with aNone
at 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.
id
holds the name as a string, andctx
is one of the following types.
-
class
ast.
Load
¶ -
class
ast.
Store
¶ -
class
ast.
Del
¶ Variable references can be used to load the value of a variable, to assign a new value to it, or to delete it. Variable references are given a context to distinguish these cases.
>>> print(ast.dump(ast.parse('a'), indent=4)) Module( body=[ Expr( value=Name(id='a', ctx=Load()))], type_ignores=[]) >>> print(ast.dump(ast.parse('a = 1'), indent=4)) Module( body=[ Assign( targets=[ Name(id='a', ctx=Store())], value=Constant(value=1))], type_ignores=[]) >>> print(ast.dump(ast.parse('del a'), indent=4)) Module( body=[ Delete( targets=[ Name(id='a', ctx=Del())])], type_ignores=[])
-
class
ast.
Starred
(value, ctx)¶ A
*var
variable reference.value
holds the variable, typically aName
node. This type must be used when building aCall
node 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()))], type_ignores=[])
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.
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())))], type_ignores=[])
-
class
ast.
UnaryOp
(op, operand)¶ A unary operation.
op
is the operator, andoperand
any expression node.
-
class
ast.
UAdd
¶ -
class
ast.
USub
¶ -
class
ast.
Not
¶ -
class
ast.
Invert
¶ Unary operator tokens.
Not
is thenot
keyword,Invert
is 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).
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())))
-
class
ast.
Add
¶ -
class
ast.
Sub
¶ -
class
ast.
Mult
¶ -
class
ast.
Div
¶ -
class
ast.
FloorDiv
¶ -
class
ast.
Mod
¶ -
class
ast.
Pow
¶ -
class
ast.
LShift
¶ -
class
ast.
RShift
¶ -
class
ast.
BitOr
¶ -
class
ast.
BitXor
¶ -
class
ast.
BitAnd
¶ -
class
ast.
MatMult
¶ Binary operator tokens.
-
class
ast.
BoolOp
(op, values)¶ A boolean operation, “or” or “and”.
op
isOr
orAnd
.values
are 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.
left
is the first value in the comparison,ops
the list of operators, andcomparators
the 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, starargs, kwargs)¶ 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 representing arguments passed by keyword.
When creating a
Call
node,args
andkeywords
are required, but they can be empty lists.starargs
andkwargs
are optional.>>> 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.
arg
is a raw string of the parameter name,value
is a node to pass in.
-
class
ast.
IfExp
(test, body, orelse)¶ An expression such as
a if b else c
. Each field holds a single node, so in the following example, all three 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())))
-
class
ast.
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 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
Assign
node 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)))
Subscripting¶
-
class
ast.
Subscript
(value, slice, ctx)¶ A subscript, such as
l[1]
.value
is the subscripted object (usually sequence or mapping).slice
is an index, slice or key. It can be aTuple
and contain aSlice
.ctx
isLoad
,Store
orDel
according 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:upper
orlower: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
(orkey
andvalue
) is a single node representing 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()), ifs=[], 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()), ifs=[], 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()), ifs=[], is_async=0)]))
-
class
ast.
comprehension
(target, iter, ifs, is_async)¶ One
for
clause in a comprehension.target
is the reference to use for each element - typically aName
orTuple
node.iter
is 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 anasync for
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())], keywords=[]), generators=[ comprehension( target=Name(id='line', ctx=Store()), iter=Name(id='file', ctx=Load()), ifs=[], is_async=0), comprehension( target=Name(id='c', ctx=Store()), iter=Name(id='line', ctx=Load()), ifs=[], 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()), ifs=[], is_async=1)]))
Statements¶
-
class
ast.
Assign
(targets, value, type_comment)¶ An assignment.
targets
is a list of nodes, andvalue
is a single node.Multiple nodes in
targets
represents assigning the same value to each. Unpacking is represented by putting aTuple
orList
withintargets
.-
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 assignment Module( body=[ Assign( targets=[ Name(id='a', ctx=Store()), Name(id='b', ctx=Store())], value=Constant(value=1))], type_ignores=[]) >>> 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()))], type_ignores=[])
-
-
class
ast.
AnnAssign
(target, annotation, value, simple)¶ An assignment with a type annotation.
target
is a single node and can be aName
, aAttribute
or aSubscript
.annotation
is the annotation, such as aConstant
orName
node.value
is a single optional node.simple
is a boolean integer set to True for aName
node intarget
that do not appear in between parenthesis and are hence pure names and not expressions.>>> 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)], type_ignores=[]) >>> 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)], type_ignores=[]) >>> 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)], type_ignores=[]) >>> 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)], type_ignores=[])
-
class
ast.
AugAssign
(target, op, value)¶ Augmented assignment, such as
a += 1
. In the following example,target
is aName
node forx
(with theStore
context),op
isAdd
, andvalue
is aConstant
with value for 1.The
target
attribute connot 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))], type_ignores=[])
-
class
ast.
Raise
(exc, cause)¶ A
raise
statement.exc
is the exception object to be raised, normally aCall
orName
, orNone
for a standaloneraise
.cause
is the optional part fory
inraise 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()))], type_ignores=[])
-
class
ast.
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()))], type_ignores=[])
-
class
ast.
Delete
(targets)¶ Represents a
del
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())])], type_ignores=[])
-
class
ast.
Pass
¶ A
pass
statement.>>> print(ast.dump(ast.parse('pass'), indent=4)) Module( body=[ Pass()], type_ignores=[])
Other statements which are only applicable inside functions or loops are described in other sections.
Imports¶
-
class
ast.
Import
(names)¶ An import statement.
names
is a list 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')])], type_ignores=[])
-
class
ast.
ImportFrom
(module, names, level)¶ Represents
from x import y
.module
is a raw string of the “from” name, without any leading dots, orNone
for statements such asfrom . import foo
.level
is 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)], type_ignores=[])
-
class
ast.
alias
(name, asname)¶ Both parameters are raw strings of the names.
asname
can beNone
if 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)], type_ignores=[])
Control flow¶
Nota
Optional clauses such as else
are stored as an empty list if they’re
not present.
-
class
ast.
If
(test, body, orelse)¶ An
if
statement.test
holds a single node, such as aCompare
node.body
andorelse
each hold a list of nodes.elif
clauses don’t have a special representation in the AST, but rather appear as extraIf
nodes within theorelse
section 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))])])], type_ignores=[])
-
class
ast.
For
(target, iter, body, orelse, type_comment)¶ A
for
loop.target
holds the variable(s) the loop assigns to, as a singleName
,Tuple
orList
node.iter
holds the item to be looped over, again as a single node.body
andorelse
contain lists of nodes to execute. Those inorelse
are executed if the loop finishes normally, rather than via 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))])], type_ignores=[])
-
-
class
ast.
While
(test, body, orelse)¶ A
while
loop.test
holds the condition, such as aCompare
node.>> 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))])], type_ignores=[])
-
class
ast.
Break
¶ -
class
ast.
Continue
¶ The
break
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()])], orelse=[])], type_ignores=[])
-
class
ast.
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))])], type_ignores=[])
-
class
ast.
ExceptHandler
(type, name, body)¶ A single
except
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
if the clause doesn’t haveas foo
.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()])], orelse=[], finalbody=[])], type_ignores=[])
-
class
ast.
With
(items, body, type_comment)¶ A
with
block.items
is a list ofwithitem
nodes representing the 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.
-
-
class
ast.
withitem
(context_expr, optional_vars)¶ A single context manager in a
with
block.context_expr
is the context manager, often aCall
node.optional_vars
is aName
,Tuple
orList
for theas foo
part, orNone
if 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())], keywords=[]))])], type_ignores=[])
Function and class definitions¶
-
class
ast.
FunctionDef
(name, args, body, decorator_list, returns, type_comment)¶ A function definition.
name
is a raw string of the function name.args
is anarguments
node.body
is the list of nodes inside the function.decorator_list
is the list of decorators to be applied, stored outermost first (i.e. the first in the list will be applied last).returns
is the return annotation.
-
type_comment
¶ type_comment
is an optional string with the type annotation as a comment.
-
class
ast.
Lambda
(args, body)¶ lambda
is a minimal function definition that can be used inside an expression. UnlikeFunctionDef
,body
holds a single node.>>> print(ast.dump(ast.parse('lambda x,y: ...'), indent=4)) Module( body=[ Expr( value=Lambda( args=arguments( posonlyargs=[], args=[ arg(arg='x'), arg(arg='y')], kwonlyargs=[], kw_defaults=[], defaults=[]), body=Constant(value=Ellipsis)))], type_ignores=[])
-
class
ast.
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. If one isNone
, the corresponding argument is required.defaults
is a list of default values for arguments that can be passed positionally. If there are fewer defaults, they correspond to the last n arguments.
-
class
ast.
arg
(arg, annotation, type_comment)¶ A single argument in a list.
arg
is a raw string of the argument name,annotation
is its annotation, such as aStr
orName
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( posonlyargs=[], 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'))], type_ignores=[])
-
-
class
ast.
Return
(value)¶ A
return
statement.>>> print(ast.dump(ast.parse('return 4'), indent=4)) Module( body=[ Return( value=Constant(value=4))], type_ignores=[])
-
class
ast.
Yield
(value)¶ -
class
ast.
YieldFrom
(value)¶ A
yield
oryield from
expression. Because these are expressions, they must be wrapped in aExpr
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())))], type_ignores=[]) >>> print(ast.dump(ast.parse('yield from x'), indent=4)) Module( body=[ Expr( value=YieldFrom( value=Name(id='x', ctx=Load())))], type_ignores=[])
-
class
ast.
Global
(names)¶ -
class
ast.
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'])], type_ignores=[]) >>> print(ast.dump(ast.parse('nonlocal x,y,z'), indent=4)) Module( body=[ Nonlocal( names=[ 'x', 'y', 'z'])], type_ignores=[])
-
class
ast.
ClassDef
(name, bases, keywords, starargs, kwargs, body, decorator_list)¶ A class definition.
name
is a raw string for the class namebases
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 per PEP-3115.starargs
andkwargs
are each a single node, as in a function call. starargs will be expanded to join the list of base classes, and kwargs will be passed to the metaclass.body
is a list of nodes representing the code within the class definition.decorator_list
is a list of nodes, as inFunctionDef
.
>>> 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())])], type_ignores=[])
Async and await¶
-
class
ast.
AsyncFunctionDef
(name, args, body, decorator_list, returns, type_comment)¶ An
async def
function definition. Has the same fields asFunctionDef
.
-
class
ast.
Await
(value)¶ An
await
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(
posonlyargs=[],
args=[],
kwonlyargs=[],
kw_defaults=[],
defaults=[]),
body=[
Expr(
value=Await(
value=Call(
func=Name(id='other_func', ctx=Load()),
args=[],
keywords=[])))],
decorator_list=[])],
type_ignores=[])
-
class
ast.
AsyncFor
(target, iter, body, orelse, type_comment)¶ -
class
ast.
AsyncWith
(items, body, type_comment)¶ async for
loops andasync with
context managers. They have the same fields asFor
andWith
, respectively. Only valid in the body of anAsyncFunctionDef
.
Nota
When a string is parsed by ast.parse()
, operator nodes (subclasses
of ast.operator
, ast.unaryop
, ast.cmpop
,
ast.boolop
and ast.expr_context
) on the returned tree
will be singletons. Changes to one will be reflected in all other
occurrences of the same value (e.g. ast.Add
).
Ayudantes de ast
¶
Además de las clases de nodo, el módulo ast
define estas funciones y clases de utilidad para atravesar árboles de sintaxis abstracta:
-
ast.
parse
(source, filename='<unknown>', mode='exec', *, type_comments=False, feature_version=None)¶ Analiza la fuente en un nodo AST. Equivalente a
compile(source, filename, mode, ast.PyCF_ONLY_AST)
.Si se proporciona
type_comments=True
, el analizador se modifica para verificar y retornar los comentarios de tipo según lo especificado por PEP 484 y PEP 526. Esto es equivalente a agregarast.PyCF_TYPE_COMMENTS
a los flags pasados acompile()
. Esto informará errores de sintaxis para comentarios de tipo fuera de lugar. Sin este flag, los comentarios de tipo se ignorarán y el campotype_comment
en los nodos AST seleccionados siempre seráNone
. Además, las ubicaciones de los comentarios# type: ignore
se retornarán como el atributotype_ignores
deModule
(de lo contrario, siempre es una lista vacía).Además, si
modo
es'func_type'
, la sintaxis de entrada se modifica para corresponder a PEP 484 «comentarios de tipo de firma», por ejemplo(str, int) -> List[str]
.Además, establece
feature_version
en una tupla(major, minor)
intentará analizar usando la gramática de esa versión de Python. Actualmentemajor
debe ser igual a3
. Por ejemplo, establecefeature_version=(3, 4)
permitirá el uso deasync
yawait
como nombres de variables. La versión más baja admitida es(3, 4)
; la más alto essys.version_info[0:2]
.If source contains a null character (“0”),
ValueError
is raised.Advertencia
Note that successfully parsing source code into an AST object doesn’t guarantee that the source code provided is valid Python code that can be executed as the compilation step can raise further
SyntaxError
exceptions. For instance, the sourcereturn 42
generates a valid AST node for a return statement, but it cannot be compiled alone (it needs to be inside a function node).In particular,
ast.parse()
won’t do any scoping checks, which the compilation step does.Advertencia
Es posible bloquear el intérprete de Python con una cadena de caracteres suficientemente grande/compleja debido a las limitaciones de profundidad de pila en el compilador AST de Python.
Distinto en la versión 3.8: Se agregaron
type_comments
,mode='func_type'
yfeature_version
.
-
ast.
unparse
(ast_obj)¶ Unparse an
ast.AST
object and generate a string with code that would produce an equivalentast.AST
object if parsed back withast.parse()
.Advertencia
The produced code string will not necessarily be equal to the original code that generated the
ast.AST
object (without any compiler optimizations, such as constant tuples/frozensets).Advertencia
Trying to unparse a highly complex expression would result with
RecursionError
.Nuevo en la versión 3.9.
-
ast.
literal_eval
(node_or_string)¶ Evaluate an expression node or a string containing only a Python literal or container display. The string or node provided may only consist of the following Python literal structures: strings, bytes, numbers, tuples, lists, dicts, sets, booleans, and
None
.This can be used for evaluating strings containing Python values without the need to parse the values oneself. It is not capable of evaluating arbitrarily complex expressions, for example involving operators or indexing.
This function had been documented as «safe» in the past without defining what that meant. That was misleading. This is specifically designed not to execute Python code, unlike the more general
eval()
. There is no namespace, no name lookups, or ability to call out. But it is not free from attack: A relatively small input can lead to memory exhaustion or to C stack exhaustion, crashing the process. There is also the possibility for excessive CPU consumption denial of service on some inputs. Calling it on untrusted data is thus not recommended.Advertencia
It is possible to crash the Python interpreter due to stack depth limitations in Python’s AST compiler.
Distinto en la versión 3.2: Ahora permite bytes y establece literales.
Distinto en la versión 3.9: Now supports creating empty sets with
'set()'
.
-
ast.
get_docstring
(node, clean=True)¶ Retorna la cadena de caracteres de documentación del node dado (que debe ser un nodo
FunctionDef
,AsyncFunctionDef
,ClassDef
, oModule
), oNone
si no tiene docstring. Si clean es verdadero, limpia la sangría del docstring coninspect.cleandoc()
.Distinto en la versión 3.5:
AsyncFunctionDef
ahora está soportada.
-
ast.
get_source_segment
(source, node, *, padded=False)¶ Obtenga el segmento de código fuente del source que generó node. Si falta información de ubicación (
lineno
,end_lineno
,col_offset
, oend_col_offset
), retornaNone
.Si padded es
True
, la primera línea de una declaración de varias líneas se rellenará con espacios para que coincidan con su posición original.Nuevo en la versión 3.8.
-
ast.
fix_missing_locations
(node)¶ Cuando compila un árbol de nodos con
compile()
, el compilador espera los atributoslineno
ycol_offset
para cada nodo que los soporta. Es bastante tedioso completar los nodos generados, por lo que este ayudante agrega estos atributos de forma recursiva donde aún no están establecidos, configurándolos en los valores del nodo principal. Funciona de forma recursiva comenzando en node.
-
ast.
increment_lineno
(node, n=1)¶ Incremente el número de línea y el número de línea final de cada nodo en el árbol comenzando en node por n. Esto es útil para «mover código» a una ubicación diferente en un archivo.
-
ast.
copy_location
(new_node, old_node)¶ Copia la ubicación de origen (
lineno
,col_offset
,end_lineno
, yend_col_offset
) de old_node a new_node si es posible, y retorna new_node.
-
ast.
iter_fields
(node)¶ Produce (yield) una tupla de
(fieldname, value)
para cada campo ennode._fields
que está presente en node.
-
ast.
iter_child_nodes
(node)¶ Cede todos los nodos secundarios directos de node, es decir, todos los campos que son nodos y todos los elementos de campos que son listas de nodos.
-
ast.
walk
(node)¶ Recursivamente produce todos los nodos descendientes en el árbol comenzando en node (incluido node en sí mismo), en ningún orden especificado. Esto es útil si solo desea modificar los nodos en su lugar y no le importa el contexto.
-
class
ast.
NodeVisitor
¶ Una clase base de visitante de nodo que recorre el árbol de sintaxis abstracta y llama a una función de visitante para cada nodo encontrado. Esta función puede retornar un valor que se reenvía mediante el método
visit()
.Esta clase está destinada a ser subclase, con la subclase agregando métodos de visitante.
-
visit
(node)¶ Visita un nodo. La implementación predeterminada llama al método llamado
self.visit_classname
donde classname es el nombre de la clase de nodo, ogeneric_visit()
si ese método no existe.
-
generic_visit
(node)¶ Este visitante llama
visit()
en todos los hijos del nodo.Tenga en cuenta que los nodos secundarios de los nodos que tienen un método de visitante personalizado no se visitarán a menos que el visitante llame
generic_visit()
o los visite a sí mismo.
No use
NodeVisitor
si desea aplicar cambios a los nodos durante el recorrido. Para esto existe un visitante especial (NodeTransformer
) que permite modificaciones.Obsoleto desde la versión 3.8: Los métodos
visit_Num()
,visit_Str()
,visit_Bytes()
,visit_NameConstant()
yvisit_Ellipsis()
están en desuso ahora y no serán llamados en futuras versiones de Python. Agregue el métodovisit_Constant()
para manejar todos los nodos constantes.-
-
class
ast.
NodeTransformer
¶ Una subclase de
NodeVisitor
que recorre el árbol de sintaxis abstracta y permite la modificación de nodos.La clase
NodeTransformer
recorrerá el AST y usará el valor de retorno de los métodos del visitante para reemplazar o eliminar el nodo anterior. Si el valor de retorno del método de visitante esNone
, el nodo se eliminará de su ubicación; de lo contrario, se reemplazará con el valor de retorno. El valor de retorno puede ser el nodo original, en cuyo caso no se realiza ningún reemplazo.Aquí hay un transformador de ejemplo que reescribe todas las apariciones de búsquedas de nombres (
foo
) endata['foo']
:class RewriteName(NodeTransformer): def visit_Name(self, node): return Subscript( value=Name(id='data', ctx=Load()), slice=Constant(value=node.id), ctx=node.ctx )
Tenga en cuenta que si el nodo en el que está operando tiene nodos secundarios, debe transformar los nodos secundarios usted mismo o llamar primero al método
generic_visit()
para el nodo.Para los nodos que formaban parte de una colección de declaraciones (que se aplica a todos los nodos de declaración), el visitante también puede retornar una lista de nodos en lugar de solo un nodo.
Si
NodeTransformer
introduce nuevos nodos (que no eran parte del árbol original) sin darles información de ubicación (comolineno
),fix_missing_locations()
debería llamarse con el nuevo sub-árbol para recalcular la información de ubicacióntree = ast.parse('foo', mode='eval') new_tree = fix_missing_locations(RewriteName().visit(tree))
Usualmente usas el transformador así:
node = YourTransformer().visit(node)
-
ast.
dump
(node, annotate_fields=True, include_attributes=False, *, indent=None)¶ Retorna un volcado formateado del árbol en node. Esto es principalmente útil para propósitos de depuración. Si annotate_fields es verdadero (por defecto), la cadena de caracteres retornada mostrará los nombres y los valores de los campos. Si annotate_fields es falso, la cadena de resultados será más compacta omitiendo nombres de campo no ambiguos. Los atributos como los números de línea y las compensaciones de columna no se vuelcan de forma predeterminada. Si esto se desea, include_attributes se puede establecer en verdadero.
If indent is a non-negative integer or string, then the tree will be pretty-printed with that indent level. An indent level of 0, negative, or
""
will only insert newlines.None
(the default) selects the single line representation. Using a positive integer indent indents that many spaces per level. If indent is a string (such as"\t"
), that string is used to indent each level.Distinto en la versión 3.9: Added the indent option.
Compiler Flags¶
The following flags may be passed to compile()
in order to change
effects on the compilation of a program:
-
ast.
PyCF_ALLOW_TOP_LEVEL_AWAIT
¶ Enables support for top-level
await
,async for
,async with
and async comprehensions.Nuevo en la versión 3.8.
-
ast.
PyCF_ONLY_AST
¶ Generates and returns an abstract syntax tree instead of returning a compiled code object.
Command-Line Usage¶
Nuevo en la versión 3.9.
The ast
module can be executed as a script from the command line.
It is as simple as:
python -m ast [-m <mode>] [-a] [infile]
The following options are accepted:
-
-h
,
--help
¶
Show the help message and exit.
-
-m
<mode>
¶ -
--mode
<mode>
¶ Specify what kind of code must be compiled, like the mode argument in
parse()
.
-
--no-type-comments
¶
Don’t parse type comments.
-
-a
,
--include-attributes
¶
Include attributes such as line numbers and column offsets.
If infile
is specified its contents are parsed to AST and dumped
to stdout. Otherwise, the content is read from stdin.
Ver también
Green Tree Snakes, un recurso de documentación externo, tiene buenos detalles sobre cómo trabajar con Python AST.
ASTTokens annotates Python ASTs with the positions of tokens and text in the source code that generated them. This is helpful for tools that make source code transformations.
leoAst.py unifies the token-based and parse-tree-based views of python programs by inserting two-way links between tokens and ast nodes.
LibCST parses code as a Concrete Syntax Tree that looks like an ast tree and keeps all formatting details. It’s useful for building automated refactoring (codemod) applications and linters.
Parso is a Python parser that supports error recovery and round-trip parsing for different Python versions (in multiple Python versions). Parso is also able to list multiple syntax errors in your python file.