💾 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

View Raw

More Information

⬅️ Previous capture (2022-07-16)

🚧 View Differences

-=-=-=-=-=-=-

Back to module index

Go to module by name

ast


    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.

Classes

AST

Add

Add

And

And

AnnAssign

AnnAssign(expr target, expr annotation, expr? value, int simple)
end_col_offset = None
end_lineno = None
value = None

Assert

Assert(expr test, expr? msg)
end_col_offset = None
end_lineno = None
msg = None

Assign

Assign(expr* targets, expr value, string? type_comment)
end_col_offset = None
end_lineno = None
type_comment = None

AsyncFor

AsyncFor(expr target, expr iter, stmt* body, stmt* orelse, string? type_comment)
end_col_offset = None
end_lineno = None
type_comment = None

AsyncFunctionDef

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

AsyncWith(withitem* items, stmt* body, string? type_comment)
end_col_offset = None
end_lineno = None
type_comment = None

Attribute

Attribute(expr value, identifier attr, expr_context ctx)
end_col_offset = None
end_lineno = None

AugAssign

AugAssign(expr target, operator op, expr value)
end_col_offset = None
end_lineno = None

AugLoad

Deprecated AST node class.  Unused in Python 3.

AugStore

Deprecated AST node class.  Unused in Python 3.

Await

Await(expr value)
end_col_offset = None
end_lineno = None

BinOp

BinOp(expr left, operator op, expr right)
end_col_offset = None
end_lineno = None

BitAnd

BitAnd

BitOr

BitOr

BitXor

BitXor

BoolOp

BoolOp(boolop op, expr* values)
end_col_offset = None
end_lineno = None

Break

Break
end_col_offset = None
end_lineno = None

Bytes

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

Call(expr func, expr* args, keyword* keywords)
end_col_offset = None
end_lineno = None

ClassDef

ClassDef(identifier name, expr* bases, keyword* keywords, stmt* body, expr* decorator_list)
end_col_offset = None
end_lineno = None

Compare

Compare(expr left, cmpop* ops, expr* comparators)
end_col_offset = None
end_lineno = None

Constant

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

Continue
end_col_offset = None
end_lineno = None

Del

Del

Delete

Delete(expr* targets)
end_col_offset = None
end_lineno = None

Dict

Dict(expr* keys, expr* values)
end_col_offset = None
end_lineno = None

DictComp

DictComp(expr key, expr value, comprehension* generators)
end_col_offset = None
end_lineno = None

Div

Div

Ellipsis

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

Eq

ExceptHandler

ExceptHandler(expr? type, identifier? name, stmt* body)
end_col_offset = None
end_lineno = None
name = None
type = None

Expr

Expr(expr value)
end_col_offset = None
end_lineno = None

Expression

Expression(expr body)

ExtSlice

Deprecated AST node class. Use ast.Tuple instead.

FloorDiv

FloorDiv

For

For(expr target, expr iter, stmt* body, stmt* orelse, string? type_comment)
end_col_offset = None
end_lineno = None
type_comment = None

FormattedValue

FormattedValue(expr value, int conversion, expr? format_spec)
end_col_offset = None
end_lineno = None
format_spec = None

FunctionDef

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

FunctionType(expr* argtypes, expr returns)

GeneratorExp

GeneratorExp(expr elt, comprehension* generators)
end_col_offset = None
end_lineno = None

Global

Global(identifier* names)
end_col_offset = None
end_lineno = None

Gt

Gt

GtE

GtE

If

If(expr test, stmt* body, stmt* orelse)
end_col_offset = None
end_lineno = None

IfExp

IfExp(expr test, expr body, expr orelse)
end_col_offset = None
end_lineno = None

Import

Import(alias* names)
end_col_offset = None
end_lineno = None

ImportFrom

ImportFrom(identifier? module, alias* names, int? level)
end_col_offset = None
end_lineno = None
level = None
module = None

In

In

Index

Deprecated AST node class. Use the index value directly instead.

IntEnum

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

Interactive(stmt* body)

Invert

Invert

Is

Is

IsNot

IsNot

JoinedStr

JoinedStr(expr* values)
end_col_offset = None
end_lineno = None

LShift

LShift

Lambda

Lambda(arguments args, expr body)
end_col_offset = None
end_lineno = None

List

List(expr* elts, expr_context ctx)
end_col_offset = None
end_lineno = None

ListComp

ListComp(expr elt, comprehension* generators)
end_col_offset = None
end_lineno = None

Load

Load

Lt

Lt

LtE

LtE

MatMult

MatMult

Match

Match(expr subject, match_case* cases)
end_col_offset = None
end_lineno = None

MatchAs

MatchAs(pattern? pattern, identifier? name)
name = None
pattern = None

MatchClass

MatchClass(expr cls, pattern* patterns, identifier* kwd_attrs, pattern* kwd_patterns)

MatchMapping

MatchMapping(expr* keys, pattern* patterns, identifier? rest)
rest = None

MatchOr

MatchOr(pattern* patterns)

MatchSequence

MatchSequence(pattern* patterns)

MatchSingleton

MatchSingleton(constant value)

MatchStar

MatchStar(identifier? name)
name = None

MatchValue

MatchValue(expr value)

Mod

Mod

Module

Module(stmt* body, type_ignore* type_ignores)

Mult

Mult

Name

Name(identifier id, expr_context ctx)
end_col_offset = None
end_lineno = None

NameConstant

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

NamedExpr(expr target, expr value)
end_col_offset = None
end_lineno = None

NodeTransformer


    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)

NodeVisitor


    A node visitor base class that walks the abstract syntax tree and calls a
    visitor function for every node found.  This function may return a value
    which is forwarded by the `visit` 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

Nonlocal(identifier* names)
end_col_offset = None
end_lineno = None

Not

Not

NotEq

NotEq

NotIn

NotIn

Num

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

Or

Param

Deprecated AST node class.  Unused in Python 3.

Pass

Pass
end_col_offset = None
end_lineno = None

Pow

Pow

RShift

RShift

Raise

Raise(expr? exc, expr? cause)
cause = None
end_col_offset = None
end_lineno = None
exc = None

Return

Return(expr? value)
end_col_offset = None
end_lineno = None
value = None

Set

Set(expr* elts)
end_col_offset = None
end_lineno = None

SetComp

SetComp(expr elt, comprehension* generators)
end_col_offset = None
end_lineno = None

Slice

Slice(expr? lower, expr? upper, expr? step)
end_col_offset = None
end_lineno = None
lower = None
step = None
upper = None

Starred

Starred(expr value, expr_context ctx)
end_col_offset = None
end_lineno = None

Store

Store

Str

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

Sub

Subscript

Subscript(expr value, expr slice, expr_context ctx)
end_col_offset = None
end_lineno = None

Suite

Deprecated AST node class.  Unused in Python 3.

Try

Try(stmt* body, excepthandler* handlers, stmt* orelse, stmt* finalbody)
end_col_offset = None
end_lineno = None

Tuple

Tuple(expr* elts, expr_context ctx)
dims = <property object at 0x7f75e32d6d40>
  Deprecated. Use elts instead.
end_col_offset = None
end_lineno = None

TypeIgnore

TypeIgnore(int lineno, string tag)

UAdd

UAdd

USub

USub

UnaryOp

UnaryOp(unaryop op, expr operand)
end_col_offset = None
end_lineno = None

While

While(expr test, stmt* body, stmt* orelse)
end_col_offset = None
end_lineno = None

With

With(withitem* items, stmt* body, string? type_comment)
end_col_offset = None
end_lineno = None
type_comment = None

Yield

Yield(expr? value)
end_col_offset = None
end_lineno = None
value = None

YieldFrom

YieldFrom(expr value)
end_col_offset = None
end_lineno = None

alias

alias(identifier name, identifier? asname)
asname = None
end_col_offset = None
end_lineno = None

arg

arg(identifier arg, expr? annotation, string? type_comment)
annotation = None
end_col_offset = None
end_lineno = None
type_comment = None

arguments

arguments(arg* posonlyargs, arg* args, arg? vararg, arg* kwonlyargs, expr* kw_defaults, arg? kwarg, expr* defaults)
kwarg = None
vararg = None

auto


    Instances are replaced with an appropriate value in Enum class suites.
    
value = <object object at 0x7f75e3c94340>

boolop

boolop = And | Or

cmpop

cmpop = Eq | NotEq | Lt | LtE | Gt | GtE | Is | IsNot | In | NotIn

comprehension

comprehension(expr target, expr iter, expr* ifs, int is_async)

excepthandler

excepthandler = ExceptHandler(expr? type, identifier? name, stmt* body)
end_col_offset = None
end_lineno = None

expr

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

expr_context = Load | Store | Del

keyword

keyword(identifier? arg, expr value)
arg = None
end_col_offset = None
end_lineno = None

match_case

match_case(pattern pattern, expr? guard, stmt* body)
guard = None

mod

mod = Module(stmt* body, type_ignore* type_ignores)
    | Interactive(stmt* body)
    | Expression(expr body)
    | FunctionType(expr* argtypes, expr returns)

nullcontext

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

operator = Add | Sub | Mult | MatMult | Div | Mod | Pow | LShift | RShift | BitOr | BitXor | BitAnd | FloorDiv

pattern

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)

slice

Deprecated AST node class.

stmt

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

type_ignore = TypeIgnore(int lineno, string tag)

unaryop

unaryop = Invert | Not | UAdd | USub

withitem

withitem(expr context_expr, expr? optional_vars)
optional_vars = None

Functions

contextmanager

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

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

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

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

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

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

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

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

iter_fields(node)


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

literal_eval

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

main()

parse

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

unparse(ast_obj)

walk

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.
    

Other members

PyCF_ALLOW_TOP_LEVEL_AWAIT = 8192
PyCF_ONLY_AST = 1024
PyCF_TYPE_COMMENTS = 4096

Modules

sys