Debian Codegraph @

Doc/library/ast.rst

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