💾 Archived View for tris.fyi › pydoc › ast captured on 2023-01-29 at 03:00:19. Gemini links have been rewritten to link to archived content
⬅️ Previous capture (2022-07-16)
-=-=-=-=-=-=-
ast ~~~ 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 and allows modifications of it. An abstract syntax tree can be generated by passing `ast.PyCF_ONLY_AST` as a flag to the `compile()` builtin function or by using the `parse()` function from this module. The result will be a tree of objects whose classes all inherit from `ast.AST`. A modified abstract syntax tree can be compiled into a Python code object using the built-in `compile()` function. Additionally various helper functions are provided that make working with the trees simpler. The main intention of the helper functions and this module in general is to provide an easy to use interface for libraries that work tightly with the python syntax (template engines for example). :copyright: Copyright 2008 by Armin Ronacher. :license: Python License.
Add
And
AnnAssign(expr target, expr annotation, expr? value, int simple)
end_col_offset = None
end_lineno = None
value = None
Assert(expr test, expr? msg)
end_col_offset = None
end_lineno = None
msg = None
Assign(expr* targets, expr value, string? type_comment)
end_col_offset = None
end_lineno = None
type_comment = None
AsyncFor(expr target, expr iter, stmt* body, stmt* orelse, string? type_comment)
end_col_offset = None
end_lineno = None
type_comment = None
AsyncFunctionDef(identifier name, arguments args, stmt* body, expr* decorator_list, expr? returns, string? type_comment)
end_col_offset = None
end_lineno = None
returns = None
type_comment = None
AsyncWith(withitem* items, stmt* body, string? type_comment)
end_col_offset = None
end_lineno = None
type_comment = None
Attribute(expr value, identifier attr, expr_context ctx)
end_col_offset = None
end_lineno = None
AugAssign(expr target, operator op, expr value)
end_col_offset = None
end_lineno = None
Deprecated AST node class. Unused in Python 3.
Deprecated AST node class. Unused in Python 3.
Await(expr value)
end_col_offset = None
end_lineno = None
BinOp(expr left, operator op, expr right)
end_col_offset = None
end_lineno = None
BitAnd
BitOr
BitXor
BoolOp(boolop op, expr* values)
end_col_offset = None
end_lineno = None
Break
end_col_offset = None
end_lineno = None
Deprecated AST node class. Use ast.Constant instead
end_col_offset = None
end_lineno = None
kind = None
n = <property object at 0x7f75e39d1580> Deprecated. Use value instead.
s = <property object at 0x7f75e39d3290> Deprecated. Use value instead.
Call(expr func, expr* args, keyword* keywords)
end_col_offset = None
end_lineno = None
ClassDef(identifier name, expr* bases, keyword* keywords, stmt* body, expr* decorator_list)
end_col_offset = None
end_lineno = None
Compare(expr left, cmpop* ops, expr* comparators)
end_col_offset = None
end_lineno = None
Constant(constant value, string? kind)
end_col_offset = None
end_lineno = None
kind = None
n = <property object at 0x7f75e39d1580> Deprecated. Use value instead.
s = <property object at 0x7f75e39d3290> Deprecated. Use value instead.
Continue
end_col_offset = None
end_lineno = None
Del
Delete(expr* targets)
end_col_offset = None
end_lineno = None
Dict(expr* keys, expr* values)
end_col_offset = None
end_lineno = None
DictComp(expr key, expr value, comprehension* generators)
end_col_offset = None
end_lineno = None
Div
Deprecated AST node class. Use ast.Constant instead
end_col_offset = None
end_lineno = None
kind = None
n = <property object at 0x7f75e39d1580> Deprecated. Use value instead.
s = <property object at 0x7f75e39d3290> Deprecated. Use value instead.
Eq
ExceptHandler(expr? type, identifier? name, stmt* body)
end_col_offset = None
end_lineno = None
name = None
type = None
Expr(expr value)
end_col_offset = None
end_lineno = None
Expression(expr body)
Deprecated AST node class. Use ast.Tuple instead.
FloorDiv
For(expr target, expr iter, stmt* body, stmt* orelse, string? type_comment)
end_col_offset = None
end_lineno = None
type_comment = None
FormattedValue(expr value, int conversion, expr? format_spec)
end_col_offset = None
end_lineno = None
format_spec = None
FunctionDef(identifier name, arguments args, stmt* body, expr* decorator_list, expr? returns, string? type_comment)
end_col_offset = None
end_lineno = None
returns = None
type_comment = None
FunctionType(expr* argtypes, expr returns)
GeneratorExp(expr elt, comprehension* generators)
end_col_offset = None
end_lineno = None
Global(identifier* names)
end_col_offset = None
end_lineno = None
Gt
GtE
If(expr test, stmt* body, stmt* orelse)
end_col_offset = None
end_lineno = None
IfExp(expr test, expr body, expr orelse)
end_col_offset = None
end_lineno = None
Import(alias* names)
end_col_offset = None
end_lineno = None
ImportFrom(identifier? module, alias* names, int? level)
end_col_offset = None
end_lineno = None
level = None
module = None
In
Deprecated AST node class. Use the index value directly instead.
Enum where members are also (and must be) ints
name = <types.DynamicClassAttribute object at 0x7f75e3bec2e0> The name of the Enum member.
value = <types.DynamicClassAttribute object at 0x7f75e3bec2b0> The value of the Enum member.
Interactive(stmt* body)
Invert
Is
IsNot
JoinedStr(expr* values)
end_col_offset = None
end_lineno = None
LShift
Lambda(arguments args, expr body)
end_col_offset = None
end_lineno = None
List(expr* elts, expr_context ctx)
end_col_offset = None
end_lineno = None
ListComp(expr elt, comprehension* generators)
end_col_offset = None
end_lineno = None
Load
Lt
LtE
MatMult
Match(expr subject, match_case* cases)
end_col_offset = None
end_lineno = None
MatchAs(pattern? pattern, identifier? name)
name = None
pattern = None
MatchClass(expr cls, pattern* patterns, identifier* kwd_attrs, pattern* kwd_patterns)
MatchMapping(expr* keys, pattern* patterns, identifier? rest)
rest = None
MatchOr(pattern* patterns)
MatchSequence(pattern* patterns)
MatchSingleton(constant value)
MatchStar(identifier? name)
name = None
MatchValue(expr value)
Mod
Module(stmt* body, type_ignore* type_ignores)
Mult
Name(identifier id, expr_context ctx)
end_col_offset = None
end_lineno = None
Deprecated AST node class. Use ast.Constant instead
end_col_offset = None
end_lineno = None
kind = None
n = <property object at 0x7f75e39d1580> Deprecated. Use value instead.
s = <property object at 0x7f75e39d3290> Deprecated. Use value instead.
NamedExpr(expr target, expr value)
end_col_offset = None
end_lineno = None
A :class:`NodeVisitor` subclass that walks the abstract syntax tree and allows modification of nodes. The `NodeTransformer` will walk the AST and use the return value of the visitor methods to replace or remove the old node. If the return value of the visitor method is ``None``, the node will be removed from its location, otherwise it is replaced with the return value. The return value may be the original node in which case no replacement takes place. Here is an example transformer that rewrites all occurrences of name lookups (``foo``) to ``data['foo']``:: class RewriteName(NodeTransformer): def visit_Name(self, node): return Subscript( value=Name(id='data', ctx=Load()), slice=Constant(value=node.id), ctx=node.ctx ) Keep in mind that if the node you're operating on has child nodes you must either transform the child nodes yourself or call the :meth:`generic_visit` method for the node first. For nodes that were part of a collection of statements (that applies to all statement nodes), the visitor may also return a list of nodes rather than just a single node. Usually you use the transformer like this:: node = YourTransformer().visit(node)
generic_visit(self, node)
visit(self, node) Visit a node.
visit_Constant(self, node)
A node visitor base class that walks the abstract syntax tree and calls a visitor function for every node found. This function may return a value which is forwarded by the `visit` method. This class is meant to be subclassed, with the subclass adding visitor methods. Per default the visitor functions for the nodes are ``'visit_'`` + class name of the node. So a `TryFinally` node visit function would be `visit_TryFinally`. This behavior can be changed by overriding the `visit` method. If no visitor function exists for a node (return value `None`) the `generic_visit` visitor is used instead. Don't use the `NodeVisitor` if you want to apply changes to nodes during traversing. For this a special visitor exists (`NodeTransformer`) that allows modifications.
generic_visit(self, node) Called if no explicit visitor function exists for a node.
visit(self, node) Visit a node.
visit_Constant(self, node)
Nonlocal(identifier* names)
end_col_offset = None
end_lineno = None
Not
NotEq
NotIn
Deprecated AST node class. Use ast.Constant instead
end_col_offset = None
end_lineno = None
kind = None
n = <property object at 0x7f75e39d1580> Deprecated. Use value instead.
s = <property object at 0x7f75e39d3290> Deprecated. Use value instead.
Or
Deprecated AST node class. Unused in Python 3.
Pass
end_col_offset = None
end_lineno = None
Pow
RShift
Raise(expr? exc, expr? cause)
cause = None
end_col_offset = None
end_lineno = None
exc = None
Return(expr? value)
end_col_offset = None
end_lineno = None
value = None
Set(expr* elts)
end_col_offset = None
end_lineno = None
SetComp(expr elt, comprehension* generators)
end_col_offset = None
end_lineno = None
Slice(expr? lower, expr? upper, expr? step)
end_col_offset = None
end_lineno = None
lower = None
step = None
upper = None
Starred(expr value, expr_context ctx)
end_col_offset = None
end_lineno = None
Store
Deprecated AST node class. Use ast.Constant instead
end_col_offset = None
end_lineno = None
kind = None
n = <property object at 0x7f75e39d1580> Deprecated. Use value instead.
s = <property object at 0x7f75e39d3290> Deprecated. Use value instead.
Sub
Subscript(expr value, expr slice, expr_context ctx)
end_col_offset = None
end_lineno = None
Deprecated AST node class. Unused in Python 3.
Try(stmt* body, excepthandler* handlers, stmt* orelse, stmt* finalbody)
end_col_offset = None
end_lineno = None
Tuple(expr* elts, expr_context ctx)
dims = <property object at 0x7f75e32d6d40> Deprecated. Use elts instead.
end_col_offset = None
end_lineno = None
TypeIgnore(int lineno, string tag)
UAdd
USub
UnaryOp(unaryop op, expr operand)
end_col_offset = None
end_lineno = None
While(expr test, stmt* body, stmt* orelse)
end_col_offset = None
end_lineno = None
With(withitem* items, stmt* body, string? type_comment)
end_col_offset = None
end_lineno = None
type_comment = None
Yield(expr? value)
end_col_offset = None
end_lineno = None
value = None
YieldFrom(expr value)
end_col_offset = None
end_lineno = None
alias(identifier name, identifier? asname)
asname = None
end_col_offset = None
end_lineno = None
arg(identifier arg, expr? annotation, string? type_comment)
annotation = None
end_col_offset = None
end_lineno = None
type_comment = None
arguments(arg* posonlyargs, arg* args, arg? vararg, arg* kwonlyargs, expr* kw_defaults, arg? kwarg, expr* defaults)
kwarg = None
vararg = None
Instances are replaced with an appropriate value in Enum class suites.
value = <object object at 0x7f75e3c94340>
boolop = And | Or
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)
end_col_offset = None
end_lineno = None
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) | Await(expr value) | Yield(expr? value) | YieldFrom(expr value) | 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) | 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) | Slice(expr? lower, expr? upper, expr? step)
end_col_offset = None
end_lineno = None
expr_context = Load | Store | Del
keyword(identifier? arg, expr value)
arg = None
end_col_offset = None
end_lineno = None
match_case(pattern pattern, expr? guard, stmt* body)
guard = None
mod = Module(stmt* body, type_ignore* type_ignores) | Interactive(stmt* body) | Expression(expr body) | FunctionType(expr* argtypes, expr returns)
Context manager that does no additional processing. Used as a stand-in for a normal context manager, when a particular block of code is only sometimes used with a normal context manager: cm = optional_cm if condition else nullcontext() with cm: # Perform operation, using optional_cm if condition is True
operator = Add | Sub | Mult | MatMult | Div | Mod | Pow | LShift | RShift | BitOr | BitXor | BitAnd | FloorDiv
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) | MatchAs(pattern? pattern, identifier? name) | MatchOr(pattern* patterns)
Deprecated AST node class.
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) | AnnAssign(expr target, expr annotation, expr? value, int simple) | 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) | 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
end_col_offset = None
end_lineno = None
type_ignore = TypeIgnore(int lineno, string tag)
unaryop = Invert | Not | UAdd | USub
withitem(expr context_expr, expr? optional_vars)
optional_vars = None
contextmanager(func) @contextmanager decorator. Typical usage: @contextmanager def some_generator(<arguments>): <setup> try: yield <value> finally: <cleanup> This makes this: with some_generator(<arguments>) as <variable>: <body> equivalent to this: <setup> try: <variable> = <value> <body> finally: <cleanup>
copy_location(new_node, old_node) Copy source location (`lineno`, `col_offset`, `end_lineno`, and `end_col_offset` attributes) from *old_node* to *new_node* if possible, and return *new_node*.
dump(node, annotate_fields=True, include_attributes=False, *, indent=None) Return a formatted dump of the tree in node. This is mainly useful for debugging purposes. If annotate_fields is true (by default), the returned string will show the names and the values for fields. If annotate_fields is false, the result string will be more compact by omitting unambiguous field names. Attributes such as line numbers and column offsets are not dumped by default. If this is wanted, include_attributes can be set to true. If indent is a non-negative integer or string, then the tree will be pretty-printed with that indent level. None (the default) selects the single line representation.
fix_missing_locations(node) When you compile a node tree with compile(), the compiler expects lineno and col_offset attributes for every node that supports them. This is rather tedious to fill in for generated nodes, so this helper adds these attributes recursively where not already set, by setting them to the values of the parent node. It works recursively starting at *node*.
get_docstring(node, clean=True) Return the docstring for the given node or None if no docstring can be found. If the node provided does not have docstrings a TypeError will be raised. If *clean* is `True`, all tabs are expanded to spaces and any whitespace that can be uniformly removed from the second line onwards is removed.
get_source_segment(source, node, *, padded=False) Get source code segment of the *source* that generated *node*. If some location information (`lineno`, `end_lineno`, `col_offset`, or `end_col_offset`) is missing, return None. If *padded* is `True`, the first line of a multi-line statement will be padded with spaces to match its original position.
increment_lineno(node, n=1) Increment the line number and end line number of each node in the tree starting at *node* by *n*. This is useful to "move code" to a different location in a file.
iter_child_nodes(node) Yield all direct child nodes of *node*, that is, all fields that are nodes and all items of fields that are lists of nodes.
iter_fields(node) Yield a tuple of ``(fieldname, value)`` for each field in ``node._fields`` that is present on *node*.
literal_eval(node_or_string) Evaluate an expression node or a string containing only a Python expression. The string or node provided may only consist of the following Python literal structures: strings, bytes, numbers, tuples, lists, dicts, sets, booleans, and None. Caution: A complex expression can overflow the C stack and cause a crash.
main()
parse(source, filename='<unknown>', mode='exec', *, type_comments=False, feature_version=None) Parse the source into an AST node. Equivalent to compile(source, filename, mode, PyCF_ONLY_AST). Pass type_comments=True to get back type comments where the syntax allows.
unparse(ast_obj)
walk(node) Recursively yield all descendant nodes in the tree starting at *node* (including *node* itself), in no specified order. This is useful if you only want to modify nodes in place and don't care about the context.
PyCF_ALLOW_TOP_LEVEL_AWAIT = 8192
PyCF_ONLY_AST = 1024
PyCF_TYPE_COMMENTS = 4096