1:mod:`ast` --- Abstract Syntax Trees
2====================================
3
4.. module:: ast
5   :synopsis: Abstract Syntax Tree classes and manipulation.
6
7.. sectionauthor:: Martin v. Löwis <[email protected]>
8.. sectionauthor:: Georg Brandl <[email protected]>
9
10.. testsetup::
11
12    import ast
13
14**Source code:** :source:`Lib/ast.py`
15
16--------------
17
18The :mod:`ast` module helps Python applications to process trees of the Python
19abstract syntax grammar.  The abstract syntax itself might change with each
20Python release; this module helps to find out programmatically what the current
21grammar looks like.
22
23An abstract syntax tree can be generated by passing :data:`ast.PyCF_ONLY_AST` as
24a flag to the :func:`compile` built-in function, or using the :func:`parse`
25helper provided in this module.  The result will be a tree of objects whose
26classes all inherit from :class:`ast.AST`.  An abstract syntax tree can be
27compiled into a Python code object using the built-in :func:`compile` function.
28
29
30.. _abstract-grammar:
31
32Abstract Grammar
33----------------
34
35The abstract grammar is currently defined as follows:
36
37.. literalinclude:: ../../Parser/Python.asdl
38   :language: asdl
39
40
41Node classes
42------------
43
44.. class:: AST
45
46   This is the base of all AST node classes.  The actual node classes are
47   derived from the :file:`Parser/Python.asdl` file, which is reproduced
48   :ref:`above <abstract-grammar>`.  They are defined in the :mod:`_ast` C
49   module and re-exported in :mod:`ast`.
50
51   There is one class defined for each left-hand side symbol in the abstract
52   grammar (for example, :class:`ast.stmt` or :class:`ast.expr`).  In addition,
53   there is one class defined for each constructor on the right-hand side; these
54   classes inherit from the classes for the left-hand side trees.  For example,
55   :class:`ast.BinOp` inherits from :class:`ast.expr`.  For production rules
56   with alternatives (aka "sums"), the left-hand side class is abstract: only
57   instances of specific constructor nodes are ever created.
58
59   .. index:: single: ? (question mark); in AST grammar
60   .. index:: single: * (asterisk); in AST grammar
61
62   .. attribute:: _fields
63
64      Each concrete class has an attribute :attr:`_fields` which gives the names
65      of all child nodes.
66
67      Each instance of a concrete class has one attribute for each child node,
68      of the type as defined in the grammar.  For example, :class:`ast.BinOp`
69      instances have an attribute :attr:`left` of type :class:`ast.expr`.
70
71      If these attributes are marked as optional in the grammar (using a
72      question mark), the value might be ``None``.  If the attributes can have
73      zero-or-more values (marked with an asterisk), the values are represented
74      as Python lists.  All possible attributes must be present and have valid
75      values when compiling an AST with :func:`compile`.
76
77   .. attribute:: lineno
78                  col_offset
79                  end_lineno
80                  end_col_offset
81
82      Instances of :class:`ast.expr` and :class:`ast.stmt` subclasses have
83      :attr:`lineno`, :attr:`col_offset`, :attr:`end_lineno`, and
84      :attr:`end_col_offset` attributes.  The :attr:`lineno` and :attr:`end_lineno`
85      are the first and last line numbers of source text span (1-indexed so the
86      first line is line 1) and the :attr:`col_offset` and :attr:`end_col_offset`
87      are the corresponding UTF-8 byte offsets of the first and last tokens that
88      generated the node. The UTF-8 offset is recorded because the parser uses
89      UTF-8 internally.
90
91      Note that the end positions are not required by the compiler and are
92      therefore optional. The end offset is *after* the last symbol, for example
93      one can get the source segment of a one-line expression node using
94      ``source_line[node.col_offset : node.end_col_offset]``.
95
96   The constructor of a class :class:`ast.T` parses its arguments as follows:
97
98   * If there are positional arguments, there must be as many as there are items
99     in :attr:`T._fields`; they will be assigned as attributes of these names.
100   * If there are keyword arguments, they will set the attributes of the same
101     names to the given values.
102
103   For example, to create and populate an :class:`ast.UnaryOp` node, you could
104   use ::
105
106      node = ast.UnaryOp()
107      node.op = ast.USub()
108      node.operand = ast.Constant()
109      node.operand.value = 5
110      node.operand.lineno = 0
111      node.operand.col_offset = 0
112      node.lineno = 0
113      node.col_offset = 0
114
115   or the more compact ::
116
117      node = ast.UnaryOp(ast.USub(), ast.Constant(5, lineno=0, col_offset=0),
118                         lineno=0, col_offset=0)
119
120.. versionchanged:: 3.8
121
122   Class :class:`ast.Constant` is now used for all constants.
123
124.. versionchanged:: 3.9
125
126   Simple indices are represented by their value, extended slices are
127   represented as tuples.
128
129.. deprecated:: 3.8
130
131   Old classes :class:`ast.Num`, :class:`ast.Str`, :class:`ast.Bytes`,
132   :class:`ast.NameConstant` and :class:`ast.Ellipsis` are still available,
133   but they will be removed in future Python releases.  In the meantime,
134   instantiating them will return an instance of a different class.
135
136.. deprecated:: 3.9
137
138   Old classes :class:`ast.Index` and :class:`ast.ExtSlice` are still
139   available, but they will be removed in future Python releases.
140   In the meantime, instantiating them will return an instance of
141   a different class.
142
143.. note::
144    The descriptions of the specific node classes displayed here
145    were initially adapted from the fantastic `Green Tree
146    Snakes <https://greentreesnakes.readthedocs.io/en/latest/>`__ project and
147    all its contributors.
148
149Literals
150^^^^^^^^
151
152.. class:: Constant(value)
153
154   A constant value. The ``value`` attribute of the ``Constant`` literal contains the
155   Python object it represents. The values represented can be simple types
156   such as a number, string or ``None``, but also immutable container types
157   (tuples and frozensets) if all of their elements are constant.
158
159   .. doctest::
160
161        >>> print(ast.dump(ast.parse('123', mode='eval'), indent=4))
162        Expression(
163            body=Constant(value=123))
164
165
166.. class:: FormattedValue(value, conversion, format_spec)
167
168   Node representing a single formatting field in an f-string. If the string
169   contains a single formatting field and nothing else the node can be
170   isolated otherwise it appears in :class:`JoinedStr`.
171
172   * ``value`` is any expression node (such as a literal, a variable, or a
173     function call).
174   * ``conversion`` is an integer:
175
176     * -1: no formatting
177     * 115: ``!s`` string formatting
178     * 114: ``!r`` repr formatting
179     * 97: ``!a`` ascii formatting
180
181   * ``format_spec`` is a :class:`JoinedStr` node representing the formatting
182     of the value, or ``None`` if no format was specified. Both
183     ``conversion`` and ``format_spec`` can be set at the same time.
184
185
186.. class:: JoinedStr(values)
187
188   An f-string, comprising a series of :class:`FormattedValue` and :class:`Constant`
189   nodes.
190
191   .. doctest::
192
193        >>> print(ast.dump(ast.parse('f"sin({a}) is {sin(a):.3}"', mode='eval'), indent=4))
194        Expression(
195            body=JoinedStr(
196                values=[
197                    Constant(value='sin('),
198                    FormattedValue(
199                        value=Name(id='a', ctx=Load()),
200                        conversion=-1),
201                    Constant(value=') is '),
202                    FormattedValue(
203                        value=Call(
204                            func=Name(id='sin', ctx=Load()),
205                            args=[
206                                Name(id='a', ctx=Load())],
207                            keywords=[]),
208                        conversion=-1,
209                        format_spec=JoinedStr(
210                            values=[
211                                Constant(value='.3')]))]))
212
213
214.. class:: List(elts, ctx)
215           Tuple(elts, ctx)
216
217   A list or tuple. ``elts`` holds a list of nodes representing the elements.
218   ``ctx`` is :class:`Store` if the container is an assignment target (i.e.
219   ``(x,y)=something``), and :class:`Load` otherwise.
220
221   .. doctest::
222
223        >>> print(ast.dump(ast.parse('[1, 2, 3]', mode='eval'), indent=4))
224        Expression(
225            body=List(
226                elts=[
227                    Constant(value=1),
228                    Constant(value=2),
229                    Constant(value=3)],
230                ctx=Load()))
231        >>> print(ast.dump(ast.parse('(1, 2, 3)', mode='eval'), indent=4))
232        Expression(
233            body=Tuple(
234                elts=[
235                    Constant(value=1),
236                    Constant(value=2),
237                    Constant(value=3)],
238                ctx=Load()))
239
240
241.. class:: Set(elts)
242
243   A set. ``elts`` holds a list of nodes representing the set's elements.
244
245   .. doctest::
246
247        >>> print(ast.dump(ast.parse('{1, 2, 3}', mode='eval'), indent=4))
248        Expression(
249            body=Set(
250                elts=[
251                    Constant(value=1),
252                    Constant(value=2),
253                    Constant(value=3)]))
254
255
256.. class:: Dict(keys, values)
257
258   A dictionary. ``keys`` and ``values`` hold lists of nodes representing the
259   keys and the values respectively, in matching order (what would be returned
260   when calling :code:`dictionary.keys()` and :code:`dictionary.values()`).
261
262   When doing dictionary unpacking using dictionary literals the expression to be
263   expanded goes in the ``values`` list, with a ``None`` at the corresponding
264   position in ``keys``.
265
266   .. doctest::
267
268        >>> print(ast.dump(ast.parse('{"a":1, **d}', mode='eval'), indent=4))
269        Expression(
270            body=Dict(
271                keys=[
272                    Constant(value='a'),
273                    None],
274                values=[
275                    Constant(value=1),
276                    Name(id='d', ctx=Load())]))
277
278
279Variables
280^^^^^^^^^
281
282.. class:: Name(id, ctx)
283
284   A variable name. ``id`` holds the name as a string, and ``ctx`` is one of
285   the following types.
286
287
288.. class:: Load()
289           Store()
290           Del()
291
292   Variable references can be used to load the value of a variable, to assign
293   a new value to it, or to delete it. Variable references are given a context
294   to distinguish these cases.
295
296   .. doctest::
297
298        >>> print(ast.dump(ast.parse('a'), indent=4))
299        Module(
300            body=[
301                Expr(
302                    value=Name(id='a', ctx=Load()))],
303            type_ignores=[])
304
305        >>> print(ast.dump(ast.parse('a = 1'), indent=4))
306        Module(
307            body=[
308                Assign(
309                    targets=[
310                        Name(id='a', ctx=Store())],
311                    value=Constant(value=1))],
312            type_ignores=[])
313
314        >>> print(ast.dump(ast.parse('del a'), indent=4))
315        Module(
316            body=[
317                Delete(
318                    targets=[
319                        Name(id='a', ctx=Del())])],
320            type_ignores=[])
321
322
323.. class:: Starred(value, ctx)
324
325   A ``*var`` variable reference. ``value`` holds the variable, typically a
326   :class:`Name` node. This type must be used when building a :class:`Call`
327   node with ``*args``.
328
329   .. doctest::
330
331        >>> print(ast.dump(ast.parse('a, *b = it'), indent=4))
332        Module(
333            body=[
334                Assign(
335                    targets=[
336                        Tuple(
337                            elts=[
338                                Name(id='a', ctx=Store()),
339                                Starred(
340                                    value=Name(id='b', ctx=Store()),
341                                    ctx=Store())],
342                            ctx=Store())],
343                    value=Name(id='it', ctx=Load()))],
344            type_ignores=[])
345
346
347Expressions
348^^^^^^^^^^^
349
350.. class:: Expr(value)
351
352   When an expression, such as a function call, appears as a statement by itself
353   with its return value not used or stored, it is wrapped in this container.
354   ``value`` holds one of the other nodes in this section, a :class:`Constant`, a
355   :class:`Name`, a :class:`Lambda`, a :class:`Yield` or :class:`YieldFrom` node.
356
357   .. doctest::
358
359        >>> print(ast.dump(ast.parse('-a'), indent=4))
360        Module(
361            body=[
362                Expr(
363                    value=UnaryOp(
364                        op=USub(),
365                        operand=Name(id='a', ctx=Load())))],
366            type_ignores=[])
367
368
369.. class:: UnaryOp(op, operand)
370
371   A unary operation. ``op`` is the operator, and ``operand`` any expression
372   node.
373
374
375.. class:: UAdd
376           USub
377           Not
378           Invert
379
380   Unary operator tokens. :class:`Not` is the ``not`` keyword, :class:`Invert`
381   is the ``~`` operator.
382
383   .. doctest::
384
385        >>> print(ast.dump(ast.parse('not x', mode='eval'), indent=4))
386        Expression(
387            body=UnaryOp(
388                op=Not(),
389                operand=Name(id='x', ctx=Load())))
390
391
392.. class:: BinOp(left, op, right)
393
394   A binary operation (like addition or division). ``op`` is the operator, and
395   ``left`` and ``right`` are any expression nodes.
396
397   .. doctest::
398
399        >>> print(ast.dump(ast.parse('x + y', mode='eval'), indent=4))
400        Expression(
401            body=BinOp(
402                left=Name(id='x', ctx=Load()),
403                op=Add(),
404                right=Name(id='y', ctx=Load())))
405
406
407.. class:: Add
408           Sub
409           Mult
410           Div
411           FloorDiv
412           Mod
413           Pow
414           LShift
415           RShift
416           BitOr
417           BitXor
418           BitAnd
419           MatMult
420
421   Binary operator tokens.
422
423
424.. class:: BoolOp(op, values)
425
426   A boolean operation, 'or' or 'and'. ``op`` is :class:`Or` or :class:`And`.
427   ``values`` are the values involved. Consecutive operations with the same
428   operator, such as ``a or b or c``, are collapsed into one node with several
429   values.
430
431   This doesn't include ``not``, which is a :class:`UnaryOp`.
432
433   .. doctest::
434
435        >>> print(ast.dump(ast.parse('x or y', mode='eval'), indent=4))
436        Expression(
437            body=BoolOp(
438                op=Or(),
439                values=[
440                    Name(id='x', ctx=Load()),
441                    Name(id='y', ctx=Load())]))
442
443
444.. class:: And
445           Or
446
447   Boolean operator tokens.
448
449
450.. class:: Compare(left, ops, comparators)
451
452   A comparison of two or more values. ``left`` is the first value in the
453   comparison, ``ops`` the list of operators, and ``comparators`` the list
454   of values after the first element in the comparison.
455
456   .. doctest::
457
458        >>> print(ast.dump(ast.parse('1 <= a < 10', mode='eval'), indent=4))
459        Expression(
460            body=Compare(
461                left=Constant(value=1),
462                ops=[
463                    LtE(),
464                    Lt()],
465                comparators=[
466                    Name(id='a', ctx=Load()),
467                    Constant(value=10)]))
468
469
470.. class:: Eq
471           NotEq
472           Lt
473           LtE
474           Gt
475           GtE
476           Is
477           IsNot
478           In
479           NotIn
480
481   Comparison operator tokens.
482
483
484.. class:: Call(func, args, keywords)
485
486   A function call. ``func`` is the function, which will often be a
487   :class:`Name` or :class:`Attribute` object. Of the arguments:
488
489   * ``args`` holds a list of the arguments passed by position.
490   * ``keywords`` holds a list of :class:`keyword` objects representing
491     arguments passed by keyword.
492
493   When creating a ``Call`` node, ``args`` and ``keywords`` are required, but
494   they can be empty lists.
495
496   .. doctest::
497
498        >>> print(ast.dump(ast.parse('func(a, b=c, *d, **e)', mode='eval'), indent=4))
499        Expression(
500            body=Call(
501                func=Name(id='func', ctx=Load()),
502                args=[
503                    Name(id='a', ctx=Load()),
504                    Starred(
505                        value=Name(id='d', ctx=Load()),
506                        ctx=Load())],
507                keywords=[
508                    keyword(
509                        arg='b',
510                        value=Name(id='c', ctx=Load())),
511                    keyword(
512                        value=Name(id='e', ctx=Load()))]))
513
514
515.. class:: keyword(arg, value)
516
517   A keyword argument to a function call or class definition. ``arg`` is a raw
518   string of the parameter name, ``value`` is a node to pass in.
519
520
521.. class:: IfExp(test, body, orelse)
522
523   An expression such as ``a if b else c``. Each field holds a single node, so
524   in the following example, all three are :class:`Name` nodes.
525
526   .. doctest::
527
528        >>> print(ast.dump(ast.parse('a if b else c', mode='eval'), indent=4))
529        Expression(
530            body=IfExp(
531                test=Name(id='b', ctx=Load()),
532                body=Name(id='a', ctx=Load()),
533                orelse=Name(id='c', ctx=Load())))
534
535
536.. class:: Attribute(value, attr, ctx)
537
538   Attribute access, e.g. ``d.keys``. ``value`` is a node, typically a
539   :class:`Name`. ``attr`` is a bare string giving the name of the attribute,
540   and ``ctx`` is :class:`Load`, :class:`Store` or :class:`Del` according to how
541   the attribute is acted on.
542
543   .. doctest::
544
545        >>> print(ast.dump(ast.parse('snake.colour', mode='eval'), indent=4))
546        Expression(
547            body=Attribute(
548                value=Name(id='snake', ctx=Load()),
549                attr='colour',
550                ctx=Load()))
551
552
553.. class:: NamedExpr(target, value)
554
555    A named expression. This AST node is produced by the assignment expressions
556    operator (also known as the walrus operator). As opposed to the :class:`Assign`
557    node in which the first argument can be multiple nodes, in this case both
558    ``target`` and ``value`` must be single nodes.
559
560   .. doctest::
561
562        >>> print(ast.dump(ast.parse('(x := 4)', mode='eval'), indent=4))
563        Expression(
564            body=NamedExpr(
565                target=Name(id='x', ctx=Store()),
566                value=Constant(value=4)))
567
568
569Subscripting
570~~~~~~~~~~~~
571
572.. class:: Subscript(value, slice, ctx)
573
574   A subscript, such as ``l[1]``. ``value`` is the subscripted object
575   (usually sequence or mapping). ``slice`` is an index, slice or key.
576   It can be a :class:`Tuple` and contain a :class:`Slice`.
577   ``ctx`` is :class:`Load`, :class:`Store` or :class:`Del`
578   according to the action performed with the subscript.
579
580   .. doctest::
581
582        >>> print(ast.dump(ast.parse('l[1:2, 3]', mode='eval'), indent=4))
583        Expression(
584            body=Subscript(
585                value=Name(id='l', ctx=Load()),
586                slice=Tuple(
587                    elts=[
588                        Slice(
589                            lower=Constant(value=1),
590                            upper=Constant(value=2)),
591                        Constant(value=3)],
592                    ctx=Load()),
593                ctx=Load()))
594
595
596.. class:: Slice(lower, upper, step)
597
598   Regular slicing (on the form ``lower:upper`` or ``lower:upper:step``).
599   Can occur only inside the *slice* field of :class:`Subscript`, either
600   directly or as an element of :class:`Tuple`.
601
602   .. doctest::
603
604        >>> print(ast.dump(ast.parse('l[1:2]', mode='eval'), indent=4))
605        Expression(
606            body=Subscript(
607                value=Name(id='l', ctx=Load()),
608                slice=Slice(
609                    lower=Constant(value=1),
610                    upper=Constant(value=2)),
611                ctx=Load()))
612
613
614Comprehensions
615~~~~~~~~~~~~~~
616
617.. class:: ListComp(elt, generators)
618           SetComp(elt, generators)
619           GeneratorExp(elt, generators)
620           DictComp(key, value, generators)
621
622   List and set comprehensions, generator expressions, and dictionary
623   comprehensions. ``elt`` (or ``key`` and ``value``) is a single node
624   representing the part that will be evaluated for each item.
625
626   ``generators`` is a list of :class:`comprehension` nodes.
627
628   .. doctest::
629
630        >>> print(ast.dump(ast.parse('[x for x in numbers]', mode='eval'), indent=4))
631        Expression(
632            body=ListComp(
633                elt=Name(id='x', ctx=Load()),
634                generators=[
635                    comprehension(
636                        target=Name(id='x', ctx=Store()),
637                        iter=Name(id='numbers', ctx=Load()),
638                        ifs=[],
639                        is_async=0)]))
640        >>> print(ast.dump(ast.parse('{x: x**2 for x in numbers}', mode='eval'), indent=4))
641        Expression(
642            body=DictComp(
643                key=Name(id='x', ctx=Load()),
644                value=BinOp(
645                    left=Name(id='x', ctx=Load()),
646                    op=Pow(),
647                    right=Constant(value=2)),
648                generators=[
649                    comprehension(
650                        target=Name(id='x', ctx=Store()),
651                        iter=Name(id='numbers', ctx=Load()),
652                        ifs=[],
653                        is_async=0)]))
654        >>> print(ast.dump(ast.parse('{x for x in numbers}', mode='eval'), indent=4))
655        Expression(
656            body=SetComp(
657                elt=Name(id='x', ctx=Load()),
658                generators=[
659                    comprehension(
660                        target=Name(id='x', ctx=Store()),
661                        iter=Name(id='numbers', ctx=Load()),
662                        ifs=[],
663                        is_async=0)]))
664
665
666.. class:: comprehension(target, iter, ifs, is_async)
667
668   One ``for`` clause in a comprehension. ``target`` is the reference to use for
669   each element - typically a :class:`Name` or :class:`Tuple` node. ``iter``
670   is the object to iterate over. ``ifs`` is a list of test expressions: each
671   ``for`` clause can have multiple ``ifs``.
672
673   ``is_async`` indicates a comprehension is asynchronous (using an
674   ``async for`` instead of ``for``). The value is an integer (0 or 1).
675
676   .. doctest::
677
678        >>> print(ast.dump(ast.parse('[ord(c) for line in file for c in line]', mode='eval'),
679        ...                indent=4)) # Multiple comprehensions in one.
680        Expression(
681            body=ListComp(
682                elt=Call(
683                    func=Name(id='ord', ctx=Load()),
684                    args=[
685                        Name(id='c', ctx=Load())],
686                    keywords=[]),
687                generators=[
688                    comprehension(
689                        target=Name(id='line', ctx=Store()),
690                        iter=Name(id='file', ctx=Load()),
691                        ifs=[],
692                        is_async=0),
693                    comprehension(
694                        target=Name(id='c', ctx=Store()),
695                        iter=Name(id='line', ctx=Load()),
696                        ifs=[],
697                        is_async=0)]))
698
699        >>> print(ast.dump(ast.parse('(n**2 for n in it if n>5 if n<10)', mode='eval'),
700        ...                indent=4)) # generator comprehension
701        Expression(
702            body=GeneratorExp(
703                elt=BinOp(
704                    left=Name(id='n', ctx=Load()),
705                    op=Pow(),
706                    right=Constant(value=2)),
707                generators=[
708                    comprehension(
709                        target=Name(id='n', ctx=Store()),
710                        iter=Name(id='it', ctx=Load()),
711                        ifs=[
712                            Compare(
713                                left=Name(id='n', ctx=Load()),
714                                ops=[
715                                    Gt()],
716                                comparators=[
717                                    Constant(value=5)]),
718                            Compare(
719                                left=Name(id='n', ctx=Load()),
720                                ops=[
721                                    Lt()],
722                                comparators=[
723                                    Constant(value=10)])],
724                        is_async=0)]))
725
726        >>> print(ast.dump(ast.parse('[i async for i in soc]', mode='eval'),
727        ...                indent=4)) # Async comprehension
728        Expression(
729            body=ListComp(
730                elt=Name(id='i', ctx=Load()),
731                generators=[
732                    comprehension(
733                        target=Name(id='i', ctx=Store()),
734                        iter=Name(id='soc', ctx=Load()),
735                        ifs=[],
736                        is_async=1)]))
737
738Statements
739^^^^^^^^^^
740
741.. class:: Assign(targets, value, type_comment)
742
743   An assignment. ``targets`` is a list of nodes, and ``value`` is a single node.
744
745   Multiple nodes in ``targets`` represents assigning the same value to each.
746   Unpacking is represented by putting a :class:`Tuple` or :class:`List`
747   within ``targets``.
748
749   .. attribute:: type_comment
750
751       ``type_comment`` is an optional string with the type annotation as a comment.
752
753   .. doctest::
754
755        >>> print(ast.dump(ast.parse('a = b = 1'), indent=4)) # Multiple assignment
756        Module(
757            body=[
758                Assign(
759                    targets=[
760                        Name(id='a', ctx=Store()),
761                        Name(id='b', ctx=Store())],
762                    value=Constant(value=1))],
763            type_ignores=[])
764
765        >>> print(ast.dump(ast.parse('a,b = c'), indent=4)) # Unpacking
766        Module(
767            body=[
768                Assign(
769                    targets=[
770                        Tuple(
771                            elts=[
772                                Name(id='a', ctx=Store()),
773                                Name(id='b', ctx=Store())],
774                            ctx=Store())],
775                    value=Name(id='c', ctx=Load()))],
776            type_ignores=[])
777
778
779.. class:: AnnAssign(target, annotation, value, simple)
780
781   An assignment with a type annotation. ``target`` is a single node and can
782   be a :class:`Name`, a :class:`Attribute` or a :class:`Subscript`.
783   ``annotation`` is the annotation, such as a :class:`Constant` or :class:`Name`
784   node. ``value`` is a single optional node. ``simple`` is a boolean integer
785   set to True for a :class:`Name` node in ``target`` that do not appear in
786   between parenthesis and are hence pure names and not expressions.
787
788   .. doctest::
789
790        >>> print(ast.dump(ast.parse('c: int'), indent=4))
791        Module(
792            body=[
793                AnnAssign(
794                    target=Name(id='c', ctx=Store()),
795                    annotation=Name(id='int', ctx=Load()),
796                    simple=1)],
797            type_ignores=[])
798
799        >>> print(ast.dump(ast.parse('(a): int = 1'), indent=4)) # Annotation with parenthesis
800        Module(
801            body=[
802                AnnAssign(
803                    target=Name(id='a', ctx=Store()),
804                    annotation=Name(id='int', ctx=Load()),
805                    value=Constant(value=1),
806                    simple=0)],
807            type_ignores=[])
808
809        >>> print(ast.dump(ast.parse('a.b: int'), indent=4)) # Attribute annotation
810        Module(
811            body=[
812                AnnAssign(
813                    target=Attribute(
814                        value=Name(id='a', ctx=Load()),
815                        attr='b',
816                        ctx=Store()),
817                    annotation=Name(id='int', ctx=Load()),
818                    simple=0)],
819            type_ignores=[])
820
821        >>> print(ast.dump(ast.parse('a[1]: int'), indent=4)) # Subscript annotation
822        Module(
823            body=[
824                AnnAssign(
825                    target=Subscript(
826                        value=Name(id='a', ctx=Load()),
827                        slice=Constant(value=1),
828                        ctx=Store()),
829                    annotation=Name(id='int', ctx=Load()),
830                    simple=0)],
831            type_ignores=[])
832
833
834.. class:: AugAssign(target, op, value)
835
836   Augmented assignment, such as ``a += 1``. In the following example,
837   ``target`` is a :class:`Name` node for ``x`` (with the :class:`Store`
838   context), ``op`` is :class:`Add`, and ``value`` is a :class:`Constant` with
839   value for 1.
840
841   The ``target`` attribute cannot be of class :class:`Tuple` or :class:`List`,
842   unlike the targets of :class:`Assign`.
843
844   .. doctest::
845
846        >>> print(ast.dump(ast.parse('x += 2'), indent=4))
847        Module(
848            body=[
849                AugAssign(
850                    target=Name(id='x', ctx=Store()),
851                    op=Add(),
852                    value=Constant(value=2))],
853            type_ignores=[])
854
855
856.. class:: Raise(exc, cause)
857
858   A ``raise`` statement. ``exc`` is the exception object to be raised, normally a
859   :class:`Call` or :class:`Name`, or ``None`` for a standalone ``raise``.
860   ``cause`` is the optional part for ``y`` in ``raise x from y``.
861
862   .. doctest::
863
864        >>> print(ast.dump(ast.parse('raise x from y'), indent=4))
865        Module(
866            body=[
867                Raise(
868                    exc=Name(id='x', ctx=Load()),
869                    cause=Name(id='y', ctx=Load()))],
870            type_ignores=[])
871
872
873.. class:: Assert(test, msg)
874
875   An assertion. ``test`` holds the condition, such as a :class:`Compare` node.
876   ``msg`` holds the failure message.
877
878   .. doctest::
879
880        >>> print(ast.dump(ast.parse('assert x,y'), indent=4))
881        Module(
882            body=[
883                Assert(
884                    test=Name(id='x', ctx=Load()),
885                    msg=Name(id='y', ctx=Load()))],
886            type_ignores=[])
887
888
889.. class:: Delete(targets)
890
891   Represents a ``del`` statement. ``targets`` is a list of nodes, such as
892   :class:`Name`, :class:`Attribute` or :class:`Subscript` nodes.
893
894   .. doctest::
895
896        >>> print(ast.dump(ast.parse('del x,y,z'), indent=4))
897        Module(
898            body=[
899                Delete(
900                    targets=[
901                        Name(id='x', ctx=Del()),
902                        Name(id='y', ctx=Del()),
903                        Name(id='z', ctx=Del())])],
904            type_ignores=[])
905
906
907.. class:: Pass()
908
909   A ``pass`` statement.
910
911   .. doctest::
912
913        >>> print(ast.dump(ast.parse('pass'), indent=4))
914        Module(
915            body=[
916                Pass()],
917            type_ignores=[])
918
919
920Other statements which are only applicable inside functions or loops are
921described in other sections.
922
923Imports
924~~~~~~~
925
926.. class:: Import(names)
927
928   An import statement. ``names`` is a list of :class:`alias` nodes.
929
930   .. doctest::
931
932        >>> print(ast.dump(ast.parse('import x,y,z'), indent=4))
933        Module(
934            body=[
935                Import(
936                    names=[
937                        alias(name='x'),
938                        alias(name='y'),
939                        alias(name='z')])],
940            type_ignores=[])
941
942
943.. class:: ImportFrom(module, names, level)
944
945   Represents ``from x import y``. ``module`` is a raw string of the 'from' name,
946   without any leading dots, or ``None`` for statements such as ``from . import foo``.
947   ``level`` is an integer holding the level of the relative import (0 means
948   absolute import).
949
950   .. doctest::
951
952        >>> print(ast.dump(ast.parse('from y import x,y,z'), indent=4))
953        Module(
954            body=[
955                ImportFrom(
956                    module='y',
957                    names=[
958                        alias(name='x'),
959                        alias(name='y'),
960                        alias(name='z')],
961                    level=0)],
962            type_ignores=[])
963
964
965.. class:: alias(name, asname)
966
967   Both parameters are raw strings of the names. ``asname`` can be ``None`` if
968   the regular name is to be used.
969
970   .. doctest::
971
972        >>> print(ast.dump(ast.parse('from ..foo.bar import a as b, c'), indent=4))
973        Module(
974            body=[
975                ImportFrom(
976                    module='foo.bar',
977                    names=[
978                        alias(name='a', asname='b'),
979                        alias(name='c')],
980                    level=2)],
981            type_ignores=[])
982
983Control flow
984^^^^^^^^^^^^
985
986.. note::
987   Optional clauses such as ``else`` are stored as an empty list if they're
988   not present.
989
990.. class:: If(test, body, orelse)
991
992   An ``if`` statement. ``test`` holds a single node, such as a :class:`Compare`
993   node. ``body`` and ``orelse`` each hold a list of nodes.
994
995   ``elif`` clauses don't have a special representation in the AST, but rather
996   appear as extra :class:`If` nodes within the ``orelse`` section of the
997   previous one.
998
999   .. doctest::
1000
1001        >>> print(ast.dump(ast.parse("""
1002        ... if x:
1003        ...    ...
1004        ... elif y:
1005        ...    ...
1006        ... else:
1007        ...    ...
1008        ... """), indent=4))
1009        Module(
1010            body=[
1011                If(
1012                    test=Name(id='x', ctx=Load()),
1013                    body=[
1014                        Expr(
1015                            value=Constant(value=Ellipsis))],
1016                    orelse=[
1017                        If(
1018                            test=Name(id='y', ctx=Load()),
1019                            body=[
1020                                Expr(
1021                                    value=Constant(value=Ellipsis))],
1022                            orelse=[
1023                                Expr(
1024                                    value=Constant(value=Ellipsis))])])],
1025            type_ignores=[])
1026
1027
1028.. class:: For(target, iter, body, orelse, type_comment)
1029
1030   A ``for`` loop. ``target`` holds the variable(s) the loop assigns to, as a
1031   single :class:`Name`, :class:`Tuple` or :class:`List` node. ``iter`` holds
1032   the item to be looped over, again as a single node. ``body`` and ``orelse``
1033   contain lists of nodes to execute. Those in ``orelse`` are executed if the
1034   loop finishes normally, rather than via a ``break`` statement.
1035
1036   .. attribute:: type_comment
1037
1038       ``type_comment`` is an optional string with the type annotation as a comment.
1039
1040   .. doctest::
1041
1042        >>> print(ast.dump(ast.parse("""
1043        ... for x in y:
1044        ...     ...
1045        ... else:
1046        ...     ...
1047        ... """), indent=4))
1048        Module(
1049            body=[
1050                For(
1051                    target=Name(id='x', ctx=Store()),
1052                    iter=Name(id='y', ctx=Load()),
1053                    body=[
1054                        Expr(
1055                            value=Constant(value=Ellipsis))],
1056                    orelse=[
1057                        Expr(
1058                            value=Constant(value=Ellipsis))])],
1059            type_ignores=[])
1060
1061
1062.. class:: While(test, body, orelse)
1063
1064   A ``while`` loop. ``test`` holds the condition, such as a :class:`Compare`
1065   node.
1066
1067   .. doctest::
1068
1069        >> print(ast.dump(ast.parse("""
1070        ... while x:
1071        ...    ...
1072        ... else:
1073        ...    ...
1074        ... """), indent=4))
1075        Module(
1076            body=[
1077                While(
1078                    test=Name(id='x', ctx=Load()),
1079                    body=[
1080                        Expr(
1081                            value=Constant(value=Ellipsis))],
1082                    orelse=[
1083                        Expr(
1084                            value=Constant(value=Ellipsis))])],
1085            type_ignores=[])
1086
1087
1088.. class:: Break
1089           Continue
1090
1091   The ``break`` and ``continue`` statements.
1092
1093   .. doctest::
1094
1095        >>> print(ast.dump(ast.parse("""\
1096        ... for a in b:
1097        ...     if a > 5:
1098        ...         break
1099        ...     else:
1100        ...         continue
1101        ...
1102        ... """), indent=4))
1103        Module(
1104            body=[
1105                For(
1106                    target=Name(id='a', ctx=Store()),
1107                    iter=Name(id='b', ctx=Load()),
1108                    body=[
1109                        If(
1110                            test=Compare(
1111                                left=Name(id='a', ctx=Load()),
1112                                ops=[
1113                                    Gt()],
1114                                comparators=[
1115                                    Constant(value=5)]),
1116                            body=[
1117                                Break()],
1118                            orelse=[
1119                                Continue()])],
1120                    orelse=[])],
1121            type_ignores=[])
1122
1123
1124.. class:: Try(body, handlers, orelse, finalbody)
1125
1126   ``try`` blocks. All attributes are list of nodes to execute, except for
1127   ``handlers``, which is a list of :class:`ExceptHandler` nodes.
1128
1129   .. doctest::
1130
1131        >>> print(ast.dump(ast.parse("""
1132        ... try:
1133        ...    ...
1134        ... except Exception:
1135        ...    ...
1136        ... except OtherException as e:
1137        ...    ...
1138        ... else:
1139        ...    ...
1140        ... finally:
1141        ...    ...
1142        ... """), indent=4))
1143        Module(
1144            body=[
1145                Try(
1146                    body=[
1147                        Expr(
1148                            value=Constant(value=Ellipsis))],
1149                    handlers=[
1150                        ExceptHandler(
1151                            type=Name(id='Exception', ctx=Load()),
1152                            body=[
1153                                Expr(
1154                                    value=Constant(value=Ellipsis))]),
1155                        ExceptHandler(
1156                            type=Name(id='OtherException', ctx=Load()),
1157                            name='e',
1158                            body=[
1159                                Expr(
1160                                    value=Constant(value=Ellipsis))])],
1161                    orelse=[
1162                        Expr(
1163                            value=Constant(value=Ellipsis))],
1164                    finalbody=[
1165                        Expr(
1166                            value=Constant(value=Ellipsis))])],
1167            type_ignores=[])
1168
1169
1170.. class:: TryStar(body, handlers, orelse, finalbody)
1171
1172   ``try`` blocks which are followed by ``except*`` clauses. The attributes are the
1173   same as for :class:`Try` but the :class:`ExceptHandler` nodes in ``handlers``
1174   are interpreted as ``except*`` blocks rather then ``except``.
1175
1176   .. doctest::
1177
1178        >>> print(ast.dump(ast.parse("""
1179        ... try:
1180        ...    ...
1181        ... except* Exception:
1182        ...    ...
1183        ... """), indent=4))
1184        Module(
1185            body=[
1186                TryStar(
1187                    body=[
1188                        Expr(
1189                            value=Constant(value=Ellipsis))],
1190                    handlers=[
1191                        ExceptHandler(
1192                            type=Name(id='Exception', ctx=Load()),
1193                            body=[
1194                                Expr(
1195                                    value=Constant(value=Ellipsis))])],
1196                    orelse=[],
1197                    finalbody=[])],
1198            type_ignores=[])
1199
1200
1201.. class:: ExceptHandler(type, name, body)
1202
1203   A single ``except`` clause. ``type`` is the exception type it will match,
1204   typically a :class:`Name` node (or ``None`` for a catch-all ``except:`` clause).
1205   ``name`` is a raw string for the name to hold the exception, or ``None`` if
1206   the clause doesn't have ``as foo``. ``body`` is a list of nodes.
1207
1208   .. doctest::
1209
1210        >>> print(ast.dump(ast.parse("""\
1211        ... try:
1212        ...     a + 1
1213        ... except TypeError:
1214        ...     pass
1215        ... """), indent=4))
1216        Module(
1217            body=[
1218                Try(
1219                    body=[
1220                        Expr(
1221                            value=BinOp(
1222                                left=Name(id='a', ctx=Load()),
1223                                op=Add(),
1224                                right=Constant(value=1)))],
1225                    handlers=[
1226                        ExceptHandler(
1227                            type=Name(id='TypeError', ctx=Load()),
1228                            body=[
1229                                Pass()])],
1230                    orelse=[],
1231                    finalbody=[])],
1232            type_ignores=[])
1233
1234
1235.. class:: With(items, body, type_comment)
1236
1237   A ``with`` block. ``items`` is a list of :class:`withitem` nodes representing
1238   the context managers, and ``body`` is the indented block inside the context.
1239
1240   .. attribute:: type_comment
1241
1242       ``type_comment`` is an optional string with the type annotation as a comment.
1243
1244
1245.. class:: withitem(context_expr, optional_vars)
1246
1247   A single context manager in a ``with`` block. ``context_expr`` is the context
1248   manager, often a :class:`Call` node. ``optional_vars`` is a :class:`Name`,
1249   :class:`Tuple` or :class:`List` for the ``as foo`` part, or ``None`` if that
1250   isn't used.
1251
1252   .. doctest::
1253
1254        >>> print(ast.dump(ast.parse("""\
1255        ... with a as b, c as d:
1256        ...    something(b, d)
1257        ... """), indent=4))
1258        Module(
1259            body=[
1260                With(
1261                    items=[
1262                        withitem(
1263                            context_expr=Name(id='a', ctx=Load()),
1264                            optional_vars=Name(id='b', ctx=Store())),
1265                        withitem(
1266                            context_expr=Name(id='c', ctx=Load()),
1267                            optional_vars=Name(id='d', ctx=Store()))],
1268                    body=[
1269                        Expr(
1270                            value=Call(
1271                                func=Name(id='something', ctx=Load()),
1272                                args=[
1273                                    Name(id='b', ctx=Load()),
1274                                    Name(id='d', ctx=Load())],
1275                                keywords=[]))])],
1276            type_ignores=[])
1277
1278
1279Pattern matching
1280^^^^^^^^^^^^^^^^
1281
1282
1283.. class:: Match(subject, cases)
1284
1285   A ``match`` statement. ``subject`` holds the subject of the match (the object
1286   that is being matched against the cases) and ``cases`` contains an iterable of
1287   :class:`match_case` nodes with the different cases.
1288
1289.. class:: match_case(pattern, guard, body)
1290
1291   A single case pattern in a ``match`` statement. ``pattern`` contains the
1292   match pattern that the subject will be matched against. Note that the
1293   :class:`AST` nodes produced for patterns differ from those produced for
1294   expressions, even when they share the same syntax.
1295
1296   The ``guard`` attribute contains an expression that will be evaluated if
1297   the pattern matches the subject.
1298
1299   ``body`` contains a list of nodes to execute if the pattern matches and
1300   the result of evaluating the guard expression is true.
1301
1302   .. doctest::
1303
1304        >>> print(ast.dump(ast.parse("""
1305        ... match x:
1306        ...     case [x] if x>0:
1307        ...         ...
1308        ...     case tuple():
1309        ...         ...
1310        ... """), indent=4))
1311        Module(
1312            body=[
1313                Match(
1314                    subject=Name(id='x', ctx=Load()),
1315                    cases=[
1316                        match_case(
1317                            pattern=MatchSequence(
1318                                patterns=[
1319                                    MatchAs(name='x')]),
1320                            guard=Compare(
1321                                left=Name(id='x', ctx=Load()),
1322                                ops=[
1323                                    Gt()],
1324                                comparators=[
1325                                    Constant(value=0)]),
1326                            body=[
1327                                Expr(
1328                                    value=Constant(value=Ellipsis))]),
1329                        match_case(
1330                            pattern=MatchClass(
1331                                cls=Name(id='tuple', ctx=Load()),
1332                                patterns=[],
1333                                kwd_attrs=[],
1334                                kwd_patterns=[]),
1335                            body=[
1336                                Expr(
1337                                    value=Constant(value=Ellipsis))])])],
1338            type_ignores=[])
1339
1340.. class:: MatchValue(value)
1341
1342   A match literal or value pattern that compares by equality. ``value`` is
1343   an expression node. Permitted value nodes are restricted as described in
1344   the match statement documentation. This pattern succeeds if the match
1345   subject is equal to the evaluated value.
1346
1347   .. doctest::
1348
1349        >>> print(ast.dump(ast.parse("""
1350        ... match x:
1351        ...     case "Relevant":
1352        ...         ...
1353        ... """), indent=4))
1354        Module(
1355            body=[
1356                Match(
1357                    subject=Name(id='x', ctx=Load()),
1358                    cases=[
1359                        match_case(
1360                            pattern=MatchValue(
1361                                value=Constant(value='Relevant')),
1362                            body=[
1363                                Expr(
1364                                    value=Constant(value=Ellipsis))])])],
1365            type_ignores=[])
1366
1367.. class:: MatchSingleton(value)
1368
1369   A match literal pattern that compares by identity. ``value`` is the
1370   singleton to be compared against: ``None``, ``True``, or ``False``. This
1371   pattern succeeds if the match subject is the given constant.
1372
1373   .. doctest::
1374
1375        >>> print(ast.dump(ast.parse("""
1376        ... match x:
1377        ...     case None:
1378        ...         ...
1379        ... """), indent=4))
1380        Module(
1381            body=[
1382                Match(
1383                    subject=Name(id='x', ctx=Load()),
1384                    cases=[
1385                        match_case(
1386                            pattern=MatchSingleton(value=None),
1387                            body=[
1388                                Expr(
1389                                    value=Constant(value=Ellipsis))])])],
1390            type_ignores=[])
1391
1392.. class:: MatchSequence(patterns)
1393
1394   A match sequence pattern. ``patterns`` contains the patterns to be matched
1395   against the subject elements if the subject is a sequence. Matches a variable
1396   length sequence if one of the subpatterns is a ``MatchStar`` node, otherwise
1397   matches a fixed length sequence.
1398
1399   .. doctest::
1400
1401        >>> print(ast.dump(ast.parse("""
1402        ... match x:
1403        ...     case [1, 2]:
1404        ...         ...
1405        ... """), indent=4))
1406        Module(
1407            body=[
1408                Match(
1409                    subject=Name(id='x', ctx=Load()),
1410                    cases=[
1411                        match_case(
1412                            pattern=MatchSequence(
1413                                patterns=[
1414                                    MatchValue(
1415                                        value=Constant(value=1)),
1416                                    MatchValue(
1417                                        value=Constant(value=2))]),
1418                            body=[
1419                                Expr(
1420                                    value=Constant(value=Ellipsis))])])],
1421            type_ignores=[])
1422
1423.. class:: MatchStar(name)
1424
1425   Matches the rest of the sequence in a variable length match sequence pattern.
1426   If ``name`` is not ``None``, a list containing the remaining sequence
1427   elements is bound to that name if the overall sequence pattern is successful.
1428
1429   .. doctest::
1430
1431        >>> print(ast.dump(ast.parse("""
1432        ... match x:
1433        ...     case [1, 2, *rest]:
1434        ...         ...
1435        ...     case [*_]:
1436        ...         ...
1437        ... """), indent=4))
1438        Module(
1439            body=[
1440                Match(
1441                    subject=Name(id='x', ctx=Load()),
1442                    cases=[
1443                        match_case(
1444                            pattern=MatchSequence(
1445                                patterns=[
1446                                    MatchValue(
1447                                        value=Constant(value=1)),
1448                                    MatchValue(
1449                                        value=Constant(value=2)),
1450                                    MatchStar(name='rest')]),
1451                            body=[
1452                                Expr(
1453                                    value=Constant(value=Ellipsis))]),
1454                        match_case(
1455                            pattern=MatchSequence(
1456                                patterns=[
1457                                    MatchStar()]),
1458                            body=[
1459                                Expr(
1460                                    value=Constant(value=Ellipsis))])])],
1461            type_ignores=[])
1462
1463.. class:: MatchMapping(keys, patterns, rest)
1464
1465   A match mapping pattern. ``keys`` is a sequence of expression nodes.
1466   ``patterns`` is a corresponding sequence of pattern nodes. ``rest`` is an
1467   optional name that can be specified to capture the remaining mapping elements.
1468   Permitted key expressions are restricted as described in the match statement
1469   documentation.
1470
1471   This pattern succeeds if the subject is a mapping, all evaluated key
1472   expressions are present in the mapping, and the value corresponding to each
1473   key matches the corresponding subpattern. If ``rest`` is not ``None``, a dict
1474   containing the remaining mapping elements is bound to that name if the overall
1475   mapping pattern is successful.
1476
1477   .. doctest::
1478
1479        >>> print(ast.dump(ast.parse("""
1480        ... match x:
1481        ...     case {1: _, 2: _}:
1482        ...         ...
1483        ...     case {**rest}:
1484        ...         ...
1485        ... """), indent=4))
1486        Module(
1487            body=[
1488                Match(
1489                    subject=Name(id='x', ctx=Load()),
1490                    cases=[
1491                        match_case(
1492                            pattern=MatchMapping(
1493                                keys=[
1494                                    Constant(value=1),
1495                                    Constant(value=2)],
1496                                patterns=[
1497                                    MatchAs(),
1498                                    MatchAs()]),
1499                            body=[
1500                                Expr(
1501                                    value=Constant(value=Ellipsis))]),
1502                        match_case(
1503                            pattern=MatchMapping(keys=[], patterns=[], rest='rest'),
1504                            body=[
1505                                Expr(
1506                                    value=Constant(value=Ellipsis))])])],
1507            type_ignores=[])
1508
1509.. class:: MatchClass(cls, patterns, kwd_attrs, kwd_patterns)
1510
1511   A match class pattern. ``cls`` is an expression giving the nominal class to
1512   be matched. ``patterns`` is a sequence of pattern nodes to be matched against
1513   the class defined sequence of pattern matching attributes. ``kwd_attrs`` is a
1514   sequence of additional attributes to be matched (specified as keyword arguments
1515   in the class pattern), ``kwd_patterns`` are the corresponding patterns
1516   (specified as keyword values in the class pattern).
1517
1518   This pattern succeeds if the subject is an instance of the nominated class,
1519   all positional patterns match the corresponding class-defined attributes, and
1520   any specified keyword attributes match their corresponding pattern.
1521
1522   Note: classes may define a property that returns self in order to match a
1523   pattern node against the instance being matched. Several builtin types are
1524   also matched that way, as described in the match statement documentation.
1525
1526   .. doctest::
1527
1528        >>> print(ast.dump(ast.parse("""
1529        ... match x:
1530        ...     case Point2D(0, 0):
1531        ...         ...
1532        ...     case Point3D(x=0, y=0, z=0):
1533        ...         ...
1534        ... """), indent=4))
1535        Module(
1536            body=[
1537                Match(
1538                    subject=Name(id='x', ctx=Load()),
1539                    cases=[
1540                        match_case(
1541                            pattern=MatchClass(
1542                                cls=Name(id='Point2D', ctx=Load()),
1543                                patterns=[
1544                                    MatchValue(
1545                                        value=Constant(value=0)),
1546                                    MatchValue(
1547                                        value=Constant(value=0))],
1548                                kwd_attrs=[],
1549                                kwd_patterns=[]),
1550                            body=[
1551                                Expr(
1552                                    value=Constant(value=Ellipsis))]),
1553                        match_case(
1554                            pattern=MatchClass(
1555                                cls=Name(id='Point3D', ctx=Load()),
1556                                patterns=[],
1557                                kwd_attrs=[
1558                                    'x',
1559                                    'y',
1560                                    'z'],
1561                                kwd_patterns=[
1562                                    MatchValue(
1563                                        value=Constant(value=0)),
1564                                    MatchValue(
1565                                        value=Constant(value=0)),
1566                                    MatchValue(
1567                                        value=Constant(value=0))]),
1568                            body=[
1569                                Expr(
1570                                    value=Constant(value=Ellipsis))])])],
1571            type_ignores=[])
1572
1573.. class:: MatchAs(pattern, name)
1574
1575   A match "as-pattern", capture pattern or wildcard pattern. ``pattern``
1576   contains the match pattern that the subject will be matched against.
1577   If the pattern is ``None``, the node represents a capture pattern (i.e a
1578   bare name) and will always succeed.
1579
1580   The ``name`` attribute contains the name that will be bound if the pattern
1581   is successful. If ``name`` is ``None``, ``pattern`` must also be ``None``
1582   and the node represents the wildcard pattern.
1583
1584   .. doctest::
1585
1586        >>> print(ast.dump(ast.parse("""
1587        ... match x:
1588        ...     case [x] as y:
1589        ...         ...
1590        ...     case _:
1591        ...         ...
1592        ... """), indent=4))
1593        Module(
1594            body=[
1595                Match(
1596                    subject=Name(id='x', ctx=Load()),
1597                    cases=[
1598                        match_case(
1599                            pattern=MatchAs(
1600                                pattern=MatchSequence(
1601                                    patterns=[
1602                                        MatchAs(name='x')]),
1603                                name='y'),
1604                            body=[
1605                                Expr(
1606                                    value=Constant(value=Ellipsis))]),
1607                        match_case(
1608                            pattern=MatchAs(),
1609                            body=[
1610                                Expr(
1611                                    value=Constant(value=Ellipsis))])])],
1612            type_ignores=[])
1613
1614.. class:: MatchOr(patterns)
1615
1616   A match "or-pattern". An or-pattern matches each of its subpatterns in turn
1617   to the subject, until one succeeds. The or-pattern is then deemed to
1618   succeed. If none of the subpatterns succeed the or-pattern fails. The
1619   ``patterns`` attribute contains a list of match pattern nodes that will be
1620   matched against the subject.
1621
1622   .. doctest::
1623
1624        >>> print(ast.dump(ast.parse("""
1625        ... match x:
1626        ...     case [x] | (y):
1627        ...         ...
1628        ... """), indent=4))
1629        Module(
1630            body=[
1631                Match(
1632                    subject=Name(id='x', ctx=Load()),
1633                    cases=[
1634                        match_case(
1635                            pattern=MatchOr(
1636                                patterns=[
1637                                    MatchSequence(
1638                                        patterns=[
1639                                            MatchAs(name='x')]),
1640                                    MatchAs(name='y')]),
1641                            body=[
1642                                Expr(
1643                                    value=Constant(value=Ellipsis))])])],
1644            type_ignores=[])
1645
1646
1647Function and class definitions
1648^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1649
1650.. class:: FunctionDef(name, args, body, decorator_list, returns, type_comment)
1651
1652   A function definition.
1653
1654   * ``name`` is a raw string of the function name.
1655   * ``args`` is an :class:`arguments` node.
1656   * ``body`` is the list of nodes inside the function.
1657   * ``decorator_list`` is the list of decorators to be applied, stored outermost
1658     first (i.e. the first in the list will be applied last).
1659   * ``returns`` is the return annotation.
1660
1661   .. attribute:: type_comment
1662
1663       ``type_comment`` is an optional string with the type annotation as a comment.
1664
1665
1666.. class:: Lambda(args, body)
1667
1668   ``lambda`` is a minimal function definition that can be used inside an
1669   expression. Unlike :class:`FunctionDef`, ``body`` holds a single node.
1670
1671   .. doctest::
1672
1673        >>> print(ast.dump(ast.parse('lambda x,y: ...'), indent=4))
1674        Module(
1675            body=[
1676                Expr(
1677                    value=Lambda(
1678                        args=arguments(
1679                            posonlyargs=[],
1680                            args=[
1681                                arg(arg='x'),
1682                                arg(arg='y')],
1683                            kwonlyargs=[],
1684                            kw_defaults=[],
1685                            defaults=[]),
1686                        body=Constant(value=Ellipsis)))],
1687            type_ignores=[])
1688
1689
1690.. class:: arguments(posonlyargs, args, vararg, kwonlyargs, kw_defaults, kwarg, defaults)
1691
1692   The arguments for a function.
1693
1694   * ``posonlyargs``, ``args`` and ``kwonlyargs`` are lists of :class:`arg` nodes.
1695   * ``vararg`` and ``kwarg`` are single :class:`arg` nodes, referring to the
1696     ``*args, **kwargs`` parameters.
1697   * ``kw_defaults`` is a list of default values for keyword-only arguments. If
1698     one is ``None``, the corresponding argument is required.
1699   * ``defaults`` is a list of default values for arguments that can be passed
1700     positionally. If there are fewer defaults, they correspond to the last n
1701     arguments.
1702
1703
1704.. class:: arg(arg, annotation, type_comment)
1705
1706   A single argument in a list. ``arg`` is a raw string of the argument
1707   name, ``annotation`` is its annotation, such as a :class:`Str` or
1708   :class:`Name` node.
1709
1710   .. attribute:: type_comment
1711
1712       ``type_comment`` is an optional string with the type annotation as a comment
1713
1714   .. doctest::
1715
1716        >>> print(ast.dump(ast.parse("""\
1717        ... @decorator1
1718        ... @decorator2
1719        ... def f(a: 'annotation', b=1, c=2, *d, e, f=3, **g) -> 'return annotation':
1720        ...     pass
1721        ... """), indent=4))
1722        Module(
1723            body=[
1724                FunctionDef(
1725                    name='f',
1726                    args=arguments(
1727                        posonlyargs=[],
1728                        args=[
1729                            arg(
1730                                arg='a',
1731                                annotation=Constant(value='annotation')),
1732                            arg(arg='b'),
1733                            arg(arg='c')],
1734                        vararg=arg(arg='d'),
1735                        kwonlyargs=[
1736                            arg(arg='e'),
1737                            arg(arg='f')],
1738                        kw_defaults=[
1739                            None,
1740                            Constant(value=3)],
1741                        kwarg=arg(arg='g'),
1742                        defaults=[
1743                            Constant(value=1),
1744                            Constant(value=2)]),
1745                    body=[
1746                        Pass()],
1747                    decorator_list=[
1748                        Name(id='decorator1', ctx=Load()),
1749                        Name(id='decorator2', ctx=Load())],
1750                    returns=Constant(value='return annotation'))],
1751            type_ignores=[])
1752
1753
1754.. class:: Return(value)
1755
1756   A ``return`` statement.
1757
1758   .. doctest::
1759
1760        >>> print(ast.dump(ast.parse('return 4'), indent=4))
1761        Module(
1762            body=[
1763                Return(
1764                    value=Constant(value=4))],
1765            type_ignores=[])
1766
1767
1768.. class:: Yield(value)
1769           YieldFrom(value)
1770
1771   A ``yield`` or ``yield from`` expression. Because these are expressions, they
1772   must be wrapped in a :class:`Expr` node if the value sent back is not used.
1773
1774   .. doctest::
1775
1776        >>> print(ast.dump(ast.parse('yield x'), indent=4))
1777        Module(
1778            body=[
1779                Expr(
1780                    value=Yield(
1781                        value=Name(id='x', ctx=Load())))],
1782            type_ignores=[])
1783
1784        >>> print(ast.dump(ast.parse('yield from x'), indent=4))
1785        Module(
1786            body=[
1787                Expr(
1788                    value=YieldFrom(
1789                        value=Name(id='x', ctx=Load())))],
1790            type_ignores=[])
1791
1792
1793.. class:: Global(names)
1794           Nonlocal(names)
1795
1796   ``global`` and ``nonlocal`` statements. ``names`` is a list of raw strings.
1797
1798   .. doctest::
1799
1800        >>> print(ast.dump(ast.parse('global x,y,z'), indent=4))
1801        Module(
1802            body=[
1803                Global(
1804                    names=[
1805                        'x',
1806                        'y',
1807                        'z'])],
1808            type_ignores=[])
1809
1810        >>> print(ast.dump(ast.parse('nonlocal x,y,z'), indent=4))
1811        Module(
1812            body=[
1813                Nonlocal(
1814                    names=[
1815                        'x',
1816                        'y',
1817                        'z'])],
1818            type_ignores=[])
1819
1820
1821.. class:: ClassDef(name, bases, keywords, body, decorator_list)
1822
1823   A class definition.
1824
1825   * ``name`` is a raw string for the class name
1826   * ``bases`` is a list of nodes for explicitly specified base classes.
1827   * ``keywords`` is a list of :class:`keyword` nodes, principally for 'metaclass'.
1828     Other keywords will be passed to the metaclass, as per `PEP-3115
1829     <https://peps.python.org/pep-3115/>`_.
1830   * ``body`` is a list of nodes representing the code within the class
1831     definition.
1832   * ``decorator_list`` is a list of nodes, as in :class:`FunctionDef`.
1833
1834   .. doctest::
1835
1836        >>> print(ast.dump(ast.parse("""\
1837        ... @decorator1
1838        ... @decorator2
1839        ... class Foo(base1, base2, metaclass=meta):
1840        ...     pass
1841        ... """), indent=4))
1842        Module(
1843            body=[
1844                ClassDef(
1845                    name='Foo',
1846                    bases=[
1847                        Name(id='base1', ctx=Load()),
1848                        Name(id='base2', ctx=Load())],
1849                    keywords=[
1850                        keyword(
1851                            arg='metaclass',
1852                            value=Name(id='meta', ctx=Load()))],
1853                    body=[
1854                        Pass()],
1855                    decorator_list=[
1856                        Name(id='decorator1', ctx=Load()),
1857                        Name(id='decorator2', ctx=Load())])],
1858            type_ignores=[])
1859
1860Async and await
1861^^^^^^^^^^^^^^^
1862
1863.. class:: AsyncFunctionDef(name, args, body, decorator_list, returns, type_comment)
1864
1865   An ``async def`` function definition. Has the same fields as
1866   :class:`FunctionDef`.
1867
1868
1869.. class:: Await(value)
1870
1871   An ``await`` expression. ``value`` is what it waits for.
1872   Only valid in the body of an :class:`AsyncFunctionDef`.
1873
1874.. doctest::
1875
1876    >>> print(ast.dump(ast.parse("""\
1877    ... async def f():
1878    ...     await other_func()
1879    ... """), indent=4))
1880    Module(
1881        body=[
1882            AsyncFunctionDef(
1883                name='f',
1884                args=arguments(
1885                    posonlyargs=[],
1886                    args=[],
1887                    kwonlyargs=[],
1888                    kw_defaults=[],
1889                    defaults=[]),
1890                body=[
1891                    Expr(
1892                        value=Await(
1893                            value=Call(
1894                                func=Name(id='other_func', ctx=Load()),
1895                                args=[],
1896                                keywords=[])))],
1897                decorator_list=[])],
1898        type_ignores=[])
1899
1900
1901.. class:: AsyncFor(target, iter, body, orelse, type_comment)
1902           AsyncWith(items, body, type_comment)
1903
1904   ``async for`` loops and ``async with`` context managers. They have the same
1905   fields as :class:`For` and :class:`With`, respectively. Only valid in the
1906   body of an :class:`AsyncFunctionDef`.
1907
1908.. note::
1909   When a string is parsed by :func:`ast.parse`, operator nodes (subclasses
1910   of :class:`ast.operator`, :class:`ast.unaryop`, :class:`ast.cmpop`,
1911   :class:`ast.boolop` and :class:`ast.expr_context`) on the returned tree
1912   will be singletons. Changes to one will be reflected in all other
1913   occurrences of the same value (e.g. :class:`ast.Add`).
1914
1915
1916:mod:`ast` Helpers
1917------------------
1918
1919Apart from the node classes, the :mod:`ast` module defines these utility functions
1920and classes for traversing abstract syntax trees:
1921
1922.. function:: parse(source, filename='<unknown>', mode='exec', *, type_comments=False, feature_version=None)
1923
1924   Parse the source into an AST node.  Equivalent to ``compile(source,
1925   filename, mode, ast.PyCF_ONLY_AST)``.
1926
1927   If ``type_comments=True`` is given, the parser is modified to check
1928   and return type comments as specified by :pep:`484` and :pep:`526`.
1929   This is equivalent to adding :data:`ast.PyCF_TYPE_COMMENTS` to the
1930   flags passed to :func:`compile()`.  This will report syntax errors
1931   for misplaced type comments.  Without this flag, type comments will
1932   be ignored, and the ``type_comment`` field on selected AST nodes
1933   will always be ``None``.  In addition, the locations of ``# type:
1934   ignore`` comments will be returned as the ``type_ignores``
1935   attribute of :class:`Module` (otherwise it is always an empty list).
1936
1937   In addition, if ``mode`` is ``'func_type'``, the input syntax is
1938   modified to correspond to :pep:`484` "signature type comments",
1939   e.g. ``(str, int) -> List[str]``.
1940
1941   Also, setting ``feature_version`` to a tuple ``(major, minor)``
1942   will attempt to parse using that Python version's grammar.
1943   Currently ``major`` must equal to ``3``.  For example, setting
1944   ``feature_version=(3, 4)`` will allow the use of ``async`` and
1945   ``await`` as variable names.  The lowest supported version is
1946   ``(3, 4)``; the highest is ``sys.version_info[0:2]``.
1947
1948   If source contains a null character ('\0'), :exc:`ValueError` is raised.
1949
1950   .. warning::
1951      Note that successfully parsing source code into an AST object doesn't
1952      guarantee that the source code provided is valid Python code that can
1953      be executed as the compilation step can raise further :exc:`SyntaxError`
1954      exceptions. For instance, the source ``return 42`` generates a valid
1955      AST node for a return statement, but it cannot be compiled alone (it needs
1956      to be inside a function node).
1957
1958      In particular, :func:`ast.parse` won't do any scoping checks, which the
1959      compilation step does.
1960
1961   .. warning::
1962      It is possible to crash the Python interpreter with a
1963      sufficiently large/complex string due to stack depth limitations
1964      in Python's AST compiler.
1965
1966   .. versionchanged:: 3.8
1967      Added ``type_comments``, ``mode='func_type'`` and ``feature_version``.
1968
1969
1970.. function:: unparse(ast_obj)
1971
1972   Unparse an :class:`ast.AST` object and generate a string with code
1973   that would produce an equivalent :class:`ast.AST` object if parsed
1974   back with :func:`ast.parse`.
1975
1976   .. warning::
1977      The produced code string will not necessarily be equal to the original
1978      code that generated the :class:`ast.AST` object (without any compiler
1979      optimizations, such as constant tuples/frozensets).
1980
1981   .. warning::
1982      Trying to unparse a highly complex expression would result with
1983      :exc:`RecursionError`.
1984
1985   .. versionadded:: 3.9
1986
1987
1988.. function:: literal_eval(node_or_string)
1989
1990   Evaluate an expression node or a string containing only a Python literal or
1991   container display.  The string or node provided may only consist of the
1992   following Python literal structures: strings, bytes, numbers, tuples, lists,
1993   dicts, sets, booleans, ``None`` and ``Ellipsis``.
1994
1995   This can be used for evaluating strings containing Python values without the
1996   need to parse the values oneself.  It is not capable of evaluating
1997   arbitrarily complex expressions, for example involving operators or
1998   indexing.
1999
2000   This function had been documented as "safe" in the past without defining
2001   what that meant. That was misleading. This is specifically designed not to
2002   execute Python code, unlike the more general :func:`eval`. There is no
2003   namespace, no name lookups, or ability to call out. But it is not free from
2004   attack: A relatively small input can lead to memory exhaustion or to C stack
2005   exhaustion, crashing the process. There is also the possibility for
2006   excessive CPU consumption denial of service on some inputs. Calling it on
2007   untrusted data is thus not recommended.
2008
2009   .. warning::
2010      It is possible to crash the Python interpreter due to stack depth
2011      limitations in Python's AST compiler.
2012
2013      It can raise :exc:`ValueError`, :exc:`TypeError`, :exc:`SyntaxError`,
2014      :exc:`MemoryError` and :exc:`RecursionError` depending on the malformed
2015      input.
2016
2017   .. versionchanged:: 3.2
2018      Now allows bytes and set literals.
2019
2020   .. versionchanged:: 3.9
2021      Now supports creating empty sets with ``'set()'``.
2022
2023   .. versionchanged:: 3.10
2024      For string inputs, leading spaces and tabs are now stripped.
2025
2026
2027.. function:: get_docstring(node, clean=True)
2028
2029   Return the docstring of the given *node* (which must be a
2030   :class:`FunctionDef`, :class:`AsyncFunctionDef`, :class:`ClassDef`,
2031   or :class:`Module` node), or ``None`` if it has no docstring.
2032   If *clean* is true, clean up the docstring's indentation with
2033   :func:`inspect.cleandoc`.
2034
2035   .. versionchanged:: 3.5
2036      :class:`AsyncFunctionDef` is now supported.
2037
2038
2039.. function:: get_source_segment(source, node, *, padded=False)
2040
2041   Get source code segment of the *source* that generated *node*.
2042   If some location information (:attr:`lineno`, :attr:`end_lineno`,
2043   :attr:`col_offset`, or :attr:`end_col_offset`) is missing, return ``None``.
2044
2045   If *padded* is ``True``, the first line of a multi-line statement will
2046   be padded with spaces to match its original position.
2047
2048   .. versionadded:: 3.8
2049
2050
2051.. function:: fix_missing_locations(node)
2052
2053   When you compile a node tree with :func:`compile`, the compiler expects
2054   :attr:`lineno` and :attr:`col_offset` attributes for every node that supports
2055   them.  This is rather tedious to fill in for generated nodes, so this helper
2056   adds these attributes recursively where not already set, by setting them to
2057   the values of the parent node.  It works recursively starting at *node*.
2058
2059
2060.. function:: increment_lineno(node, n=1)
2061
2062   Increment the line number and end line number of each node in the tree
2063   starting at *node* by *n*. This is useful to "move code" to a different
2064   location in a file.
2065
2066
2067.. function:: copy_location(new_node, old_node)
2068
2069   Copy source location (:attr:`lineno`, :attr:`col_offset`, :attr:`end_lineno`,
2070   and :attr:`end_col_offset`) from *old_node* to *new_node* if possible,
2071   and return *new_node*.
2072
2073
2074.. function:: iter_fields(node)
2075
2076   Yield a tuple of ``(fieldname, value)`` for each field in ``node._fields``
2077   that is present on *node*.
2078
2079
2080.. function:: iter_child_nodes(node)
2081
2082   Yield all direct child nodes of *node*, that is, all fields that are nodes
2083   and all items of fields that are lists of nodes.
2084
2085
2086.. function:: walk(node)
2087
2088   Recursively yield all descendant nodes in the tree starting at *node*
2089   (including *node* itself), in no specified order.  This is useful if you only
2090   want to modify nodes in place and don't care about the context.
2091
2092
2093.. class:: NodeVisitor()
2094
2095   A node visitor base class that walks the abstract syntax tree and calls a
2096   visitor function for every node found.  This function may return a value
2097   which is forwarded by the :meth:`visit` method.
2098
2099   This class is meant to be subclassed, with the subclass adding visitor
2100   methods.
2101
2102   .. method:: visit(node)
2103
2104      Visit a node.  The default implementation calls the method called
2105      :samp:`self.visit_{classname}` where *classname* is the name of the node
2106      class, or :meth:`generic_visit` if that method doesn't exist.
2107
2108   .. method:: generic_visit(node)
2109
2110      This visitor calls :meth:`visit` on all children of the node.
2111
2112      Note that child nodes of nodes that have a custom visitor method won't be
2113      visited unless the visitor calls :meth:`generic_visit` or visits them
2114      itself.
2115
2116   Don't use the :class:`NodeVisitor` if you want to apply changes to nodes
2117   during traversal.  For this a special visitor exists
2118   (:class:`NodeTransformer`) that allows modifications.
2119
2120   .. deprecated:: 3.8
2121
2122      Methods :meth:`visit_Num`, :meth:`visit_Str`, :meth:`visit_Bytes`,
2123      :meth:`visit_NameConstant` and :meth:`visit_Ellipsis` are deprecated
2124      now and will not be called in future Python versions.  Add the
2125      :meth:`visit_Constant` method to handle all constant nodes.
2126
2127
2128.. class:: NodeTransformer()
2129
2130   A :class:`NodeVisitor` subclass that walks the abstract syntax tree and
2131   allows modification of nodes.
2132
2133   The :class:`NodeTransformer` will walk the AST and use the return value of
2134   the visitor methods to replace or remove the old node.  If the return value
2135   of the visitor method is ``None``, the node will be removed from its
2136   location, otherwise it is replaced with the return value.  The return value
2137   may be the original node in which case no replacement takes place.
2138
2139   Here is an example transformer that rewrites all occurrences of name lookups
2140   (``foo``) to ``data['foo']``::
2141
2142      class RewriteName(NodeTransformer):
2143
2144          def visit_Name(self, node):
2145              return Subscript(
2146                  value=Name(id='data', ctx=Load()),
2147                  slice=Constant(value=node.id),
2148                  ctx=node.ctx
2149              )
2150
2151   Keep in mind that if the node you're operating on has child nodes you must
2152   either transform the child nodes yourself or call the :meth:`generic_visit`
2153   method for the node first.
2154
2155   For nodes that were part of a collection of statements (that applies to all
2156   statement nodes), the visitor may also return a list of nodes rather than
2157   just a single node.
2158
2159   If :class:`NodeTransformer` introduces new nodes (that weren't part of
2160   original tree) without giving them location information (such as
2161   :attr:`lineno`), :func:`fix_missing_locations` should be called with
2162   the new sub-tree to recalculate the location information::
2163
2164      tree = ast.parse('foo', mode='eval')
2165      new_tree = fix_missing_locations(RewriteName().visit(tree))
2166
2167   Usually you use the transformer like this::
2168
2169      node = YourTransformer().visit(node)
2170
2171
2172.. function:: dump(node, annotate_fields=True, include_attributes=False, *, indent=None)
2173
2174   Return a formatted dump of the tree in *node*.  This is mainly useful for
2175   debugging purposes.  If *annotate_fields* is true (by default),
2176   the returned string will show the names and the values for fields.
2177   If *annotate_fields* is false, the result string will be more compact by
2178   omitting unambiguous field names.  Attributes such as line
2179   numbers and column offsets are not dumped by default.  If this is wanted,
2180   *include_attributes* can be set to true.
2181
2182   If *indent* is a non-negative integer or string, then the tree will be
2183   pretty-printed with that indent level.  An indent level
2184   of 0, negative, or ``""`` will only insert newlines.  ``None`` (the default)
2185   selects the single line representation. Using a positive integer indent
2186   indents that many spaces per level.  If *indent* is a string (such as ``"\t"``),
2187   that string is used to indent each level.
2188
2189   .. versionchanged:: 3.9
2190      Added the *indent* option.
2191
2192
2193.. _ast-compiler-flags:
2194
2195Compiler Flags
2196--------------
2197
2198The following flags may be passed to :func:`compile` in order to change
2199effects on the compilation of a program:
2200
2201.. data:: PyCF_ALLOW_TOP_LEVEL_AWAIT
2202
2203   Enables support for top-level ``await``, ``async for``, ``async with``
2204   and async comprehensions.
2205
2206   .. versionadded:: 3.8
2207
2208.. data:: PyCF_ONLY_AST
2209
2210   Generates and returns an abstract syntax tree instead of returning a
2211   compiled code object.
2212
2213.. data:: PyCF_TYPE_COMMENTS
2214
2215   Enables support for :pep:`484` and :pep:`526` style type comments
2216   (``# type: <type>``, ``# type: ignore <stuff>``).
2217
2218   .. versionadded:: 3.8
2219
2220
2221.. _ast-cli:
2222
2223Command-Line Usage
2224------------------
2225
2226.. versionadded:: 3.9
2227
2228The :mod:`ast` module can be executed as a script from the command line.
2229It is as simple as:
2230
2231.. code-block:: sh
2232
2233   python -m ast [-m <mode>] [-a] [infile]
2234
2235The following options are accepted:
2236
2237.. program:: ast
2238
2239.. cmdoption:: -h, --help
2240
2241   Show the help message and exit.
2242
2243.. cmdoption:: -m <mode>
2244               --mode <mode>
2245
2246   Specify what kind of code must be compiled, like the *mode* argument
2247   in :func:`parse`.
2248
2249.. cmdoption:: --no-type-comments
2250
2251   Don't parse type comments.
2252
2253.. cmdoption:: -a, --include-attributes
2254
2255   Include attributes such as line numbers and column offsets.
2256
2257.. cmdoption:: -i <indent>
2258               --indent <indent>
2259
2260   Indentation of nodes in AST (number of spaces).
2261
2262If :file:`infile` is specified its contents are parsed to AST and dumped
2263to stdout.  Otherwise, the content is read from stdin.
2264
2265
2266.. seealso::
2267
2268    `Green Tree Snakes <https://greentreesnakes.readthedocs.io/>`_, an external
2269    documentation resource, has good details on working with Python ASTs.
2270
2271    `ASTTokens <https://asttokens.readthedocs.io/en/latest/user-guide.html>`_
2272    annotates Python ASTs with the positions of tokens and text in the source
2273    code that generated them. This is helpful for tools that make source code
2274    transformations.
2275
2276    `leoAst.py <https://leoeditor.com/appendices.html#leoast-py>`_ unifies the
2277    token-based and parse-tree-based views of python programs by inserting
2278    two-way links between tokens and ast nodes.
2279
2280    `LibCST <https://libcst.readthedocs.io/>`_ parses code as a Concrete Syntax
2281    Tree that looks like an ast tree and keeps all formatting details. It's
2282    useful for building automated refactoring (codemod) applications and
2283    linters.
2284
2285    `Parso <https://parso.readthedocs.io>`_ is a Python parser that supports
2286    error recovery and round-trip parsing for different Python versions (in
2287    multiple Python versions). Parso is also able to list multiple syntax errors
2288    in your python file.
2289