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 <martin@v.loewis.de> 8.. sectionauthor:: Georg Brandl <georg@python.org> 9 10.. testsetup:: 11 12 import ast 13 14**Source code:** :source:`Lib/ast.py` 15 16-------------- 17 18The :mod:`ast` module helps Python applications to process trees of the Python 19abstract syntax grammar. The abstract syntax itself might change with each 20Python release; this module helps to find out programmatically what the current 21grammar looks like. 22 23An abstract syntax tree can be generated by passing :data:`ast.PyCF_ONLY_AST` as 24a flag to the :func:`compile` built-in function, or using the :func:`parse` 25helper provided in this module. The result will be a tree of objects whose 26classes all inherit from :class:`ast.AST`. An abstract syntax tree can be 27compiled into a Python code object using the built-in :func:`compile` function. 28 29 30.. _abstract-grammar: 31 32Abstract Grammar 33---------------- 34 35The abstract grammar is currently defined as follows: 36 37.. literalinclude:: ../../Parser/Python.asdl 38 :language: asdl 39 40 41Node classes 42------------ 43 44.. class:: AST 45 46 This is the base of all AST node classes. The actual node classes are 47 derived from the :file:`Parser/Python.asdl` file, which is reproduced 48 :ref:`above <abstract-grammar>`. They are defined in the :mod:`!_ast` C 49 module and re-exported in :mod:`ast`. 50 51 There is one class defined for each left-hand side symbol in the abstract 52 grammar (for example, :class:`ast.stmt` or :class:`ast.expr`). In addition, 53 there is one class defined for each constructor on the right-hand side; these 54 classes inherit from the classes for the left-hand side trees. For example, 55 :class:`ast.BinOp` inherits from :class:`ast.expr`. For production rules 56 with alternatives (aka "sums"), the left-hand side class is abstract: only 57 instances of specific constructor nodes are ever created. 58 59 .. index:: single: ? (question mark); in AST grammar 60 .. index:: single: * (asterisk); in AST grammar 61 62 .. attribute:: _fields 63 64 Each concrete class has an attribute :attr:`!_fields` which gives the names 65 of all child nodes. 66 67 Each instance of a concrete class has one attribute for each child node, 68 of the type as defined in the grammar. For example, :class:`ast.BinOp` 69 instances have an attribute :attr:`left` of type :class:`ast.expr`. 70 71 If these attributes are marked as optional in the grammar (using a 72 question mark), the value might be ``None``. If the attributes can have 73 zero-or-more values (marked with an asterisk), the values are represented 74 as Python lists. All possible attributes must be present and have valid 75 values when compiling an AST with :func:`compile`. 76 77 .. attribute:: _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 168Root 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 260Literals 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 simple types 267 such as a number, string or ``None``, but also immutable container types 268 (tuples and frozensets) if all of their elements are constant. 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 389Variables 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 455Expressions 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 676Subscripting 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 721Comprehensions 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 850Statements 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 1043Other statements which are only applicable inside functions or loops are 1044described in other sections. 1045 1046Imports 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 1103Control 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 1387Pattern 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.. _ast-type-params: 1760 1761Type parameters 1762^^^^^^^^^^^^^^^ 1763 1764:ref:`Type parameters <type-params>` can exist on classes, functions, and type 1765aliases. 1766 1767.. class:: TypeVar(name, bound, default_value) 1768 1769 A :class:`typing.TypeVar`. ``name`` is the name of the type variable. 1770 ``bound`` is the bound or constraints, if any. If ``bound`` is a :class:`Tuple`, 1771 it represents constraints; otherwise it represents the bound. ``default_value`` 1772 is the default value; if the :class:`!TypeVar` has no default, this 1773 attribute will be set to ``None``. 1774 1775 .. doctest:: 1776 1777 >>> print(ast.dump(ast.parse("type Alias[T: int = bool] = list[T]"), indent=4)) 1778 Module( 1779 body=[ 1780 TypeAlias( 1781 name=Name(id='Alias', ctx=Store()), 1782 type_params=[ 1783 TypeVar( 1784 name='T', 1785 bound=Name(id='int', ctx=Load()), 1786 default_value=Name(id='bool', ctx=Load()))], 1787 value=Subscript( 1788 value=Name(id='list', ctx=Load()), 1789 slice=Name(id='T', ctx=Load()), 1790 ctx=Load()))]) 1791 1792 .. versionadded:: 3.12 1793 1794 .. versionchanged:: 3.13 1795 Added the *default_value* parameter. 1796 1797.. class:: ParamSpec(name, default_value) 1798 1799 A :class:`typing.ParamSpec`. ``name`` is the name of the parameter specification. 1800 ``default_value`` is the default value; if the :class:`!ParamSpec` has no default, 1801 this attribute will be set to ``None``. 1802 1803 .. doctest:: 1804 1805 >>> print(ast.dump(ast.parse("type Alias[**P = (int, str)] = Callable[P, int]"), indent=4)) 1806 Module( 1807 body=[ 1808 TypeAlias( 1809 name=Name(id='Alias', ctx=Store()), 1810 type_params=[ 1811 ParamSpec( 1812 name='P', 1813 default_value=Tuple( 1814 elts=[ 1815 Name(id='int', ctx=Load()), 1816 Name(id='str', ctx=Load())], 1817 ctx=Load()))], 1818 value=Subscript( 1819 value=Name(id='Callable', ctx=Load()), 1820 slice=Tuple( 1821 elts=[ 1822 Name(id='P', ctx=Load()), 1823 Name(id='int', ctx=Load())], 1824 ctx=Load()), 1825 ctx=Load()))]) 1826 1827 .. versionadded:: 3.12 1828 1829 .. versionchanged:: 3.13 1830 Added the *default_value* parameter. 1831 1832.. class:: TypeVarTuple(name, default_value) 1833 1834 A :class:`typing.TypeVarTuple`. ``name`` is the name of the type variable tuple. 1835 ``default_value`` is the default value; if the :class:`!TypeVarTuple` has no 1836 default, this attribute will be set to ``None``. 1837 1838 .. doctest:: 1839 1840 >>> print(ast.dump(ast.parse("type Alias[*Ts = ()] = tuple[*Ts]"), indent=4)) 1841 Module( 1842 body=[ 1843 TypeAlias( 1844 name=Name(id='Alias', ctx=Store()), 1845 type_params=[ 1846 TypeVarTuple( 1847 name='Ts', 1848 default_value=Tuple(ctx=Load()))], 1849 value=Subscript( 1850 value=Name(id='tuple', ctx=Load()), 1851 slice=Tuple( 1852 elts=[ 1853 Starred( 1854 value=Name(id='Ts', ctx=Load()), 1855 ctx=Load())], 1856 ctx=Load()), 1857 ctx=Load()))]) 1858 1859 .. versionadded:: 3.12 1860 1861 .. versionchanged:: 3.13 1862 Added the *default_value* parameter. 1863 1864Function and class definitions 1865^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 1866 1867.. class:: FunctionDef(name, args, body, decorator_list, returns, type_comment, type_params) 1868 1869 A function definition. 1870 1871 * ``name`` is a raw string of the function name. 1872 * ``args`` is an :class:`arguments` node. 1873 * ``body`` is the list of nodes inside the function. 1874 * ``decorator_list`` is the list of decorators to be applied, stored outermost 1875 first (i.e. the first in the list will be applied last). 1876 * ``returns`` is the return annotation. 1877 * ``type_params`` is a list of :ref:`type parameters <ast-type-params>`. 1878 1879 .. attribute:: type_comment 1880 1881 ``type_comment`` is an optional string with the type annotation as a comment. 1882 1883 .. versionchanged:: 3.12 1884 Added ``type_params``. 1885 1886 1887.. class:: Lambda(args, body) 1888 1889 ``lambda`` is a minimal function definition that can be used inside an 1890 expression. Unlike :class:`FunctionDef`, ``body`` holds a single node. 1891 1892 .. doctest:: 1893 1894 >>> print(ast.dump(ast.parse('lambda x,y: ...'), indent=4)) 1895 Module( 1896 body=[ 1897 Expr( 1898 value=Lambda( 1899 args=arguments( 1900 args=[ 1901 arg(arg='x'), 1902 arg(arg='y')]), 1903 body=Constant(value=Ellipsis)))]) 1904 1905 1906.. class:: arguments(posonlyargs, args, vararg, kwonlyargs, kw_defaults, kwarg, defaults) 1907 1908 The arguments for a function. 1909 1910 * ``posonlyargs``, ``args`` and ``kwonlyargs`` are lists of :class:`arg` nodes. 1911 * ``vararg`` and ``kwarg`` are single :class:`arg` nodes, referring to the 1912 ``*args, **kwargs`` parameters. 1913 * ``kw_defaults`` is a list of default values for keyword-only arguments. If 1914 one is ``None``, the corresponding argument is required. 1915 * ``defaults`` is a list of default values for arguments that can be passed 1916 positionally. If there are fewer defaults, they correspond to the last n 1917 arguments. 1918 1919 1920.. class:: arg(arg, annotation, type_comment) 1921 1922 A single argument in a list. ``arg`` is a raw string of the argument 1923 name; ``annotation`` is its annotation, such as a :class:`Name` node. 1924 1925 .. attribute:: type_comment 1926 1927 ``type_comment`` is an optional string with the type annotation as a comment 1928 1929 .. doctest:: 1930 1931 >>> print(ast.dump(ast.parse("""\ 1932 ... @decorator1 1933 ... @decorator2 1934 ... def f(a: 'annotation', b=1, c=2, *d, e, f=3, **g) -> 'return annotation': 1935 ... pass 1936 ... """), indent=4)) 1937 Module( 1938 body=[ 1939 FunctionDef( 1940 name='f', 1941 args=arguments( 1942 args=[ 1943 arg( 1944 arg='a', 1945 annotation=Constant(value='annotation')), 1946 arg(arg='b'), 1947 arg(arg='c')], 1948 vararg=arg(arg='d'), 1949 kwonlyargs=[ 1950 arg(arg='e'), 1951 arg(arg='f')], 1952 kw_defaults=[ 1953 None, 1954 Constant(value=3)], 1955 kwarg=arg(arg='g'), 1956 defaults=[ 1957 Constant(value=1), 1958 Constant(value=2)]), 1959 body=[ 1960 Pass()], 1961 decorator_list=[ 1962 Name(id='decorator1', ctx=Load()), 1963 Name(id='decorator2', ctx=Load())], 1964 returns=Constant(value='return annotation'))]) 1965 1966 1967.. class:: Return(value) 1968 1969 A ``return`` statement. 1970 1971 .. doctest:: 1972 1973 >>> print(ast.dump(ast.parse('return 4'), indent=4)) 1974 Module( 1975 body=[ 1976 Return( 1977 value=Constant(value=4))]) 1978 1979 1980.. class:: Yield(value) 1981 YieldFrom(value) 1982 1983 A ``yield`` or ``yield from`` expression. Because these are expressions, they 1984 must be wrapped in an :class:`Expr` node if the value sent back is not used. 1985 1986 .. doctest:: 1987 1988 >>> print(ast.dump(ast.parse('yield x'), indent=4)) 1989 Module( 1990 body=[ 1991 Expr( 1992 value=Yield( 1993 value=Name(id='x', ctx=Load())))]) 1994 1995 >>> print(ast.dump(ast.parse('yield from x'), indent=4)) 1996 Module( 1997 body=[ 1998 Expr( 1999 value=YieldFrom( 2000 value=Name(id='x', ctx=Load())))]) 2001 2002 2003.. class:: Global(names) 2004 Nonlocal(names) 2005 2006 ``global`` and ``nonlocal`` statements. ``names`` is a list of raw strings. 2007 2008 .. doctest:: 2009 2010 >>> print(ast.dump(ast.parse('global x,y,z'), indent=4)) 2011 Module( 2012 body=[ 2013 Global( 2014 names=[ 2015 'x', 2016 'y', 2017 'z'])]) 2018 2019 >>> print(ast.dump(ast.parse('nonlocal x,y,z'), indent=4)) 2020 Module( 2021 body=[ 2022 Nonlocal( 2023 names=[ 2024 'x', 2025 'y', 2026 'z'])]) 2027 2028 2029.. class:: ClassDef(name, bases, keywords, body, decorator_list, type_params) 2030 2031 A class definition. 2032 2033 * ``name`` is a raw string for the class name 2034 * ``bases`` is a list of nodes for explicitly specified base classes. 2035 * ``keywords`` is a list of :class:`.keyword` nodes, principally for 'metaclass'. 2036 Other keywords will be passed to the metaclass, as per :pep:`3115`. 2037 * ``body`` is a list of nodes representing the code within the class 2038 definition. 2039 * ``decorator_list`` is a list of nodes, as in :class:`FunctionDef`. 2040 * ``type_params`` is a list of :ref:`type parameters <ast-type-params>`. 2041 2042 .. doctest:: 2043 2044 >>> print(ast.dump(ast.parse("""\ 2045 ... @decorator1 2046 ... @decorator2 2047 ... class Foo(base1, base2, metaclass=meta): 2048 ... pass 2049 ... """), indent=4)) 2050 Module( 2051 body=[ 2052 ClassDef( 2053 name='Foo', 2054 bases=[ 2055 Name(id='base1', ctx=Load()), 2056 Name(id='base2', ctx=Load())], 2057 keywords=[ 2058 keyword( 2059 arg='metaclass', 2060 value=Name(id='meta', ctx=Load()))], 2061 body=[ 2062 Pass()], 2063 decorator_list=[ 2064 Name(id='decorator1', ctx=Load()), 2065 Name(id='decorator2', ctx=Load())])]) 2066 2067 .. versionchanged:: 3.12 2068 Added ``type_params``. 2069 2070Async and await 2071^^^^^^^^^^^^^^^ 2072 2073.. class:: AsyncFunctionDef(name, args, body, decorator_list, returns, type_comment, type_params) 2074 2075 An ``async def`` function definition. Has the same fields as 2076 :class:`FunctionDef`. 2077 2078 .. versionchanged:: 3.12 2079 Added ``type_params``. 2080 2081 2082.. class:: Await(value) 2083 2084 An ``await`` expression. ``value`` is what it waits for. 2085 Only valid in the body of an :class:`AsyncFunctionDef`. 2086 2087.. doctest:: 2088 2089 >>> print(ast.dump(ast.parse("""\ 2090 ... async def f(): 2091 ... await other_func() 2092 ... """), indent=4)) 2093 Module( 2094 body=[ 2095 AsyncFunctionDef( 2096 name='f', 2097 args=arguments(), 2098 body=[ 2099 Expr( 2100 value=Await( 2101 value=Call( 2102 func=Name(id='other_func', ctx=Load()))))])]) 2103 2104 2105.. class:: AsyncFor(target, iter, body, orelse, type_comment) 2106 AsyncWith(items, body, type_comment) 2107 2108 ``async for`` loops and ``async with`` context managers. They have the same 2109 fields as :class:`For` and :class:`With`, respectively. Only valid in the 2110 body of an :class:`AsyncFunctionDef`. 2111 2112.. note:: 2113 When a string is parsed by :func:`ast.parse`, operator nodes (subclasses 2114 of :class:`ast.operator`, :class:`ast.unaryop`, :class:`ast.cmpop`, 2115 :class:`ast.boolop` and :class:`ast.expr_context`) on the returned tree 2116 will be singletons. Changes to one will be reflected in all other 2117 occurrences of the same value (e.g. :class:`ast.Add`). 2118 2119 2120:mod:`ast` Helpers 2121------------------ 2122 2123Apart from the node classes, the :mod:`ast` module defines these utility functions 2124and classes for traversing abstract syntax trees: 2125 2126.. function:: parse(source, filename='<unknown>', mode='exec', *, type_comments=False, feature_version=None, optimize=-1) 2127 2128 Parse the source into an AST node. Equivalent to ``compile(source, 2129 filename, mode, flags=FLAGS_VALUE, optimize=optimize)``, 2130 where ``FLAGS_VALUE`` is ``ast.PyCF_ONLY_AST`` if ``optimize <= 0`` 2131 and ``ast.PyCF_OPTIMIZED_AST`` otherwise. 2132 2133 If ``type_comments=True`` is given, the parser is modified to check 2134 and return type comments as specified by :pep:`484` and :pep:`526`. 2135 This is equivalent to adding :data:`ast.PyCF_TYPE_COMMENTS` to the 2136 flags passed to :func:`compile`. This will report syntax errors 2137 for misplaced type comments. Without this flag, type comments will 2138 be ignored, and the ``type_comment`` field on selected AST nodes 2139 will always be ``None``. In addition, the locations of ``# type: 2140 ignore`` comments will be returned as the ``type_ignores`` 2141 attribute of :class:`Module` (otherwise it is always an empty list). 2142 2143 In addition, if ``mode`` is ``'func_type'``, the input syntax is 2144 modified to correspond to :pep:`484` "signature type comments", 2145 e.g. ``(str, int) -> List[str]``. 2146 2147 Setting ``feature_version`` to a tuple ``(major, minor)`` will result in 2148 a "best-effort" attempt to parse using that Python version's grammar. 2149 For example, setting ``feature_version=(3, 9)`` will attempt to disallow 2150 parsing of :keyword:`match` statements. 2151 Currently ``major`` must equal to ``3``. The lowest supported version is 2152 ``(3, 7)`` (and this may increase in future Python versions); 2153 the highest is ``sys.version_info[0:2]``. "Best-effort" attempt means there 2154 is no guarantee that the parse (or success of the parse) is the same as 2155 when run on the Python version corresponding to ``feature_version``. 2156 2157 If source contains a null character (``\0``), :exc:`ValueError` is raised. 2158 2159 .. warning:: 2160 Note that successfully parsing source code into an AST object doesn't 2161 guarantee that the source code provided is valid Python code that can 2162 be executed as the compilation step can raise further :exc:`SyntaxError` 2163 exceptions. For instance, the source ``return 42`` generates a valid 2164 AST node for a return statement, but it cannot be compiled alone (it needs 2165 to be inside a function node). 2166 2167 In particular, :func:`ast.parse` won't do any scoping checks, which the 2168 compilation step does. 2169 2170 .. warning:: 2171 It is possible to crash the Python interpreter with a 2172 sufficiently large/complex string due to stack depth limitations 2173 in Python's AST compiler. 2174 2175 .. versionchanged:: 3.8 2176 Added ``type_comments``, ``mode='func_type'`` and ``feature_version``. 2177 2178 .. versionchanged:: 3.13 2179 The minimum supported version for ``feature_version`` is now ``(3, 7)``. 2180 The ``optimize`` argument was added. 2181 2182 2183.. function:: unparse(ast_obj) 2184 2185 Unparse an :class:`ast.AST` object and generate a string with code 2186 that would produce an equivalent :class:`ast.AST` object if parsed 2187 back with :func:`ast.parse`. 2188 2189 .. warning:: 2190 The produced code string will not necessarily be equal to the original 2191 code that generated the :class:`ast.AST` object (without any compiler 2192 optimizations, such as constant tuples/frozensets). 2193 2194 .. warning:: 2195 Trying to unparse a highly complex expression would result with 2196 :exc:`RecursionError`. 2197 2198 .. versionadded:: 3.9 2199 2200 2201.. function:: literal_eval(node_or_string) 2202 2203 Evaluate an expression node or a string containing only a Python literal or 2204 container display. The string or node provided may only consist of the 2205 following Python literal structures: strings, bytes, numbers, tuples, lists, 2206 dicts, sets, booleans, ``None`` and ``Ellipsis``. 2207 2208 This can be used for evaluating strings containing Python values without the 2209 need to parse the values oneself. It is not capable of evaluating 2210 arbitrarily complex expressions, for example involving operators or 2211 indexing. 2212 2213 This function had been documented as "safe" in the past without defining 2214 what that meant. That was misleading. This is specifically designed not to 2215 execute Python code, unlike the more general :func:`eval`. There is no 2216 namespace, no name lookups, or ability to call out. But it is not free from 2217 attack: A relatively small input can lead to memory exhaustion or to C stack 2218 exhaustion, crashing the process. There is also the possibility for 2219 excessive CPU consumption denial of service on some inputs. Calling it on 2220 untrusted data is thus not recommended. 2221 2222 .. warning:: 2223 It is possible to crash the Python interpreter due to stack depth 2224 limitations in Python's AST compiler. 2225 2226 It can raise :exc:`ValueError`, :exc:`TypeError`, :exc:`SyntaxError`, 2227 :exc:`MemoryError` and :exc:`RecursionError` depending on the malformed 2228 input. 2229 2230 .. versionchanged:: 3.2 2231 Now allows bytes and set literals. 2232 2233 .. versionchanged:: 3.9 2234 Now supports creating empty sets with ``'set()'``. 2235 2236 .. versionchanged:: 3.10 2237 For string inputs, leading spaces and tabs are now stripped. 2238 2239 2240.. function:: get_docstring(node, clean=True) 2241 2242 Return the docstring of the given *node* (which must be a 2243 :class:`FunctionDef`, :class:`AsyncFunctionDef`, :class:`ClassDef`, 2244 or :class:`Module` node), or ``None`` if it has no docstring. 2245 If *clean* is true, clean up the docstring's indentation with 2246 :func:`inspect.cleandoc`. 2247 2248 .. versionchanged:: 3.5 2249 :class:`AsyncFunctionDef` is now supported. 2250 2251 2252.. function:: get_source_segment(source, node, *, padded=False) 2253 2254 Get source code segment of the *source* that generated *node*. 2255 If some location information (:attr:`~ast.AST.lineno`, :attr:`~ast.AST.end_lineno`, 2256 :attr:`~ast.AST.col_offset`, or :attr:`~ast.AST.end_col_offset`) is missing, return ``None``. 2257 2258 If *padded* is ``True``, the first line of a multi-line statement will 2259 be padded with spaces to match its original position. 2260 2261 .. versionadded:: 3.8 2262 2263 2264.. function:: fix_missing_locations(node) 2265 2266 When you compile a node tree with :func:`compile`, the compiler expects 2267 :attr:`~ast.AST.lineno` and :attr:`~ast.AST.col_offset` attributes for every node that supports 2268 them. This is rather tedious to fill in for generated nodes, so this helper 2269 adds these attributes recursively where not already set, by setting them to 2270 the values of the parent node. It works recursively starting at *node*. 2271 2272 2273.. function:: increment_lineno(node, n=1) 2274 2275 Increment the line number and end line number of each node in the tree 2276 starting at *node* by *n*. This is useful to "move code" to a different 2277 location in a file. 2278 2279 2280.. function:: copy_location(new_node, old_node) 2281 2282 Copy source location (:attr:`~ast.AST.lineno`, :attr:`~ast.AST.col_offset`, :attr:`~ast.AST.end_lineno`, 2283 and :attr:`~ast.AST.end_col_offset`) from *old_node* to *new_node* if possible, 2284 and return *new_node*. 2285 2286 2287.. function:: iter_fields(node) 2288 2289 Yield a tuple of ``(fieldname, value)`` for each field in ``node._fields`` 2290 that is present on *node*. 2291 2292 2293.. function:: iter_child_nodes(node) 2294 2295 Yield all direct child nodes of *node*, that is, all fields that are nodes 2296 and all items of fields that are lists of nodes. 2297 2298 2299.. function:: walk(node) 2300 2301 Recursively yield all descendant nodes in the tree starting at *node* 2302 (including *node* itself), in no specified order. This is useful if you only 2303 want to modify nodes in place and don't care about the context. 2304 2305 2306.. class:: NodeVisitor() 2307 2308 A node visitor base class that walks the abstract syntax tree and calls a 2309 visitor function for every node found. This function may return a value 2310 which is forwarded by the :meth:`visit` method. 2311 2312 This class is meant to be subclassed, with the subclass adding visitor 2313 methods. 2314 2315 .. method:: visit(node) 2316 2317 Visit a node. The default implementation calls the method called 2318 :samp:`self.visit_{classname}` where *classname* is the name of the node 2319 class, or :meth:`generic_visit` if that method doesn't exist. 2320 2321 .. method:: generic_visit(node) 2322 2323 This visitor calls :meth:`visit` on all children of the node. 2324 2325 Note that child nodes of nodes that have a custom visitor method won't be 2326 visited unless the visitor calls :meth:`generic_visit` or visits them 2327 itself. 2328 2329 .. method:: visit_Constant(node) 2330 2331 Handles all constant nodes. 2332 2333 Don't use the :class:`NodeVisitor` if you want to apply changes to nodes 2334 during traversal. For this a special visitor exists 2335 (:class:`NodeTransformer`) that allows modifications. 2336 2337 .. deprecated:: 3.8 2338 2339 Methods :meth:`!visit_Num`, :meth:`!visit_Str`, :meth:`!visit_Bytes`, 2340 :meth:`!visit_NameConstant` and :meth:`!visit_Ellipsis` are deprecated 2341 now and will not be called in future Python versions. Add the 2342 :meth:`visit_Constant` method to handle all constant nodes. 2343 2344 2345.. class:: NodeTransformer() 2346 2347 A :class:`NodeVisitor` subclass that walks the abstract syntax tree and 2348 allows modification of nodes. 2349 2350 The :class:`NodeTransformer` will walk the AST and use the return value of 2351 the visitor methods to replace or remove the old node. If the return value 2352 of the visitor method is ``None``, the node will be removed from its 2353 location, otherwise it is replaced with the return value. The return value 2354 may be the original node in which case no replacement takes place. 2355 2356 Here is an example transformer that rewrites all occurrences of name lookups 2357 (``foo``) to ``data['foo']``:: 2358 2359 class RewriteName(NodeTransformer): 2360 2361 def visit_Name(self, node): 2362 return Subscript( 2363 value=Name(id='data', ctx=Load()), 2364 slice=Constant(value=node.id), 2365 ctx=node.ctx 2366 ) 2367 2368 Keep in mind that if the node you're operating on has child nodes you must 2369 either transform the child nodes yourself or call the :meth:`~ast.NodeVisitor.generic_visit` 2370 method for the node first. 2371 2372 For nodes that were part of a collection of statements (that applies to all 2373 statement nodes), the visitor may also return a list of nodes rather than 2374 just a single node. 2375 2376 If :class:`NodeTransformer` introduces new nodes (that weren't part of 2377 original tree) without giving them location information (such as 2378 :attr:`~ast.AST.lineno`), :func:`fix_missing_locations` should be called with 2379 the new sub-tree to recalculate the location information:: 2380 2381 tree = ast.parse('foo', mode='eval') 2382 new_tree = fix_missing_locations(RewriteName().visit(tree)) 2383 2384 Usually you use the transformer like this:: 2385 2386 node = YourTransformer().visit(node) 2387 2388 2389.. function:: dump(node, annotate_fields=True, include_attributes=False, *, indent=None, show_empty=False) 2390 2391 Return a formatted dump of the tree in *node*. This is mainly useful for 2392 debugging purposes. If *annotate_fields* is true (by default), 2393 the returned string will show the names and the values for fields. 2394 If *annotate_fields* is false, the result string will be more compact by 2395 omitting unambiguous field names. Attributes such as line 2396 numbers and column offsets are not dumped by default. If this is wanted, 2397 *include_attributes* can be set to true. 2398 2399 If *indent* is a non-negative integer or string, then the tree will be 2400 pretty-printed with that indent level. An indent level 2401 of 0, negative, or ``""`` will only insert newlines. ``None`` (the default) 2402 selects the single line representation. Using a positive integer indent 2403 indents that many spaces per level. If *indent* is a string (such as ``"\t"``), 2404 that string is used to indent each level. 2405 2406 If *show_empty* is ``False`` (the default), empty lists and fields that are ``None`` 2407 will be omitted from the output. 2408 2409 .. versionchanged:: 3.9 2410 Added the *indent* option. 2411 2412 .. versionchanged:: 3.13 2413 Added the *show_empty* option. 2414 2415 .. doctest:: 2416 2417 >>> print(ast.dump(ast.parse("""\ 2418 ... async def f(): 2419 ... await other_func() 2420 ... """), indent=4, show_empty=True)) 2421 Module( 2422 body=[ 2423 AsyncFunctionDef( 2424 name='f', 2425 args=arguments( 2426 posonlyargs=[], 2427 args=[], 2428 kwonlyargs=[], 2429 kw_defaults=[], 2430 defaults=[]), 2431 body=[ 2432 Expr( 2433 value=Await( 2434 value=Call( 2435 func=Name(id='other_func', ctx=Load()), 2436 args=[], 2437 keywords=[])))], 2438 decorator_list=[], 2439 type_params=[])], 2440 type_ignores=[]) 2441 2442 2443.. _ast-compiler-flags: 2444 2445Compiler Flags 2446-------------- 2447 2448The following flags may be passed to :func:`compile` in order to change 2449effects on the compilation of a program: 2450 2451.. data:: PyCF_ALLOW_TOP_LEVEL_AWAIT 2452 2453 Enables support for top-level ``await``, ``async for``, ``async with`` 2454 and async comprehensions. 2455 2456 .. versionadded:: 3.8 2457 2458.. data:: PyCF_ONLY_AST 2459 2460 Generates and returns an abstract syntax tree instead of returning a 2461 compiled code object. 2462 2463.. data:: PyCF_OPTIMIZED_AST 2464 2465 The returned AST is optimized according to the *optimize* argument 2466 in :func:`compile` or :func:`ast.parse`. 2467 2468 .. versionadded:: 3.13 2469 2470.. data:: PyCF_TYPE_COMMENTS 2471 2472 Enables support for :pep:`484` and :pep:`526` style type comments 2473 (``# type: <type>``, ``# type: ignore <stuff>``). 2474 2475 .. versionadded:: 3.8 2476 2477 2478.. _ast-cli: 2479 2480Command-Line Usage 2481------------------ 2482 2483.. versionadded:: 3.9 2484 2485The :mod:`ast` module can be executed as a script from the command line. 2486It is as simple as: 2487 2488.. code-block:: sh 2489 2490 python -m ast [-m <mode>] [-a] [infile] 2491 2492The following options are accepted: 2493 2494.. program:: ast 2495 2496.. option:: -h, --help 2497 2498 Show the help message and exit. 2499 2500.. option:: -m <mode> 2501 --mode <mode> 2502 2503 Specify what kind of code must be compiled, like the *mode* argument 2504 in :func:`parse`. 2505 2506.. option:: --no-type-comments 2507 2508 Don't parse type comments. 2509 2510.. option:: -a, --include-attributes 2511 2512 Include attributes such as line numbers and column offsets. 2513 2514.. option:: -i <indent> 2515 --indent <indent> 2516 2517 Indentation of nodes in AST (number of spaces). 2518 2519If :file:`infile` is specified its contents are parsed to AST and dumped 2520to stdout. Otherwise, the content is read from stdin. 2521 2522 2523.. seealso:: 2524 2525 `Green Tree Snakes <https://greentreesnakes.readthedocs.io/>`_, an external 2526 documentation resource, has good details on working with Python ASTs. 2527 2528 `ASTTokens <https://asttokens.readthedocs.io/en/latest/user-guide.html>`_ 2529 annotates Python ASTs with the positions of tokens and text in the source 2530 code that generated them. This is helpful for tools that make source code 2531 transformations. 2532 2533 `leoAst.py <https://leo-editor.github.io/leo-editor/appendices.html#leoast-py>`_ 2534 unifies the 2535 token-based and parse-tree-based views of python programs by inserting 2536 two-way links between tokens and ast nodes. 2537 2538 `LibCST <https://libcst.readthedocs.io/>`_ parses code as a Concrete Syntax 2539 Tree that looks like an ast tree and keeps all formatting details. It's 2540 useful for building automated refactoring (codemod) applications and 2541 linters. 2542 2543 `Parso <https://parso.readthedocs.io>`_ is a Python parser that supports 2544 error recovery and round-trip parsing for different Python versions (in 2545 multiple Python versions). Parso is also able to list multiple syntax errors 2546 in your Python file. 2547