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