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