blob: b5e1be826911575b2a89c7c0b48a62714d340ea7 [file] [log] [blame]
Alexander Belopolskyf0a0d142010-10-27 03:06:43 +00001:mod:`ast` --- Abstract Syntax Trees
2====================================
Georg Brandl0c77a822008-06-10 16:37:50 +00003
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
Pablo Galindo114081f2020-03-02 03:14:06 +000010.. testsetup::
11
12 import ast
13
Raymond Hettinger10480942011-01-10 03:26:08 +000014**Source code:** :source:`Lib/ast.py`
Georg Brandl0c77a822008-06-10 16:37:50 +000015
Raymond Hettinger4f707fd2011-01-10 19:54:11 +000016--------------
17
Georg Brandl0c77a822008-06-10 16:37:50 +000018The :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
Benjamin Petersonec9199b2008-11-08 17:05:00 +000023An abstract syntax tree can be generated by passing :data:`ast.PyCF_ONLY_AST` as
Georg Brandl22b34312009-07-26 14:54:51 +000024a flag to the :func:`compile` built-in function, or using the :func:`parse`
Georg Brandl0c77a822008-06-10 16:37:50 +000025helper provided in this module. The result will be a tree of objects whose
Benjamin Petersonec9199b2008-11-08 17:05:00 +000026classes 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.
Georg Brandl0c77a822008-06-10 16:37:50 +000028
Georg Brandl0c77a822008-06-10 16:37:50 +000029
Pablo Galindo114081f2020-03-02 03:14:06 +000030.. _abstract-grammar:
31
32Abstract Grammar
33----------------
34
35The abstract grammar is currently defined as follows:
36
37.. literalinclude:: ../../Parser/Python.asdl
Batuhan Taskayab7a78ca2020-05-07 23:57:26 +030038 :language: asdl
Pablo Galindo114081f2020-03-02 03:14:06 +000039
40
Georg Brandl0c77a822008-06-10 16:37:50 +000041Node 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:`below <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
Serhiy Storchaka913876d2018-10-28 13:41:26 +020059 .. index:: single: ? (question mark); in AST grammar
60 .. index:: single: * (asterisk); in AST grammar
61
Georg Brandl0c77a822008-06-10 16:37:50 +000062 .. attribute:: _fields
63
64 Each concrete class has an attribute :attr:`_fields` which gives the names
65 of all child nodes.
66
67 Each instance of a concrete class has one attribute for each child node,
68 of the type as defined in the grammar. For example, :class:`ast.BinOp`
69 instances have an attribute :attr:`left` of type :class:`ast.expr`.
70
71 If these attributes are marked as optional in the grammar (using a
72 question mark), the value might be ``None``. If the attributes can have
73 zero-or-more values (marked with an asterisk), the values are represented
74 as Python lists. All possible attributes must be present and have valid
75 values when compiling an AST with :func:`compile`.
76
77 .. attribute:: lineno
78 col_offset
Ivan Levkivskyi9932a222019-01-22 11:18:22 +000079 end_lineno
80 end_col_offset
Georg Brandl0c77a822008-06-10 16:37:50 +000081
82 Instances of :class:`ast.expr` and :class:`ast.stmt` subclasses have
Matthew Suozzobffb1372020-11-03 16:28:42 -050083 :attr:`lineno`, :attr:`col_offset`, :attr:`end_lineno`, and
84 :attr:`end_col_offset` attributes. The :attr:`lineno` and :attr:`end_lineno`
85 are the first and last line numbers of source text span (1-indexed so the
86 first line is line 1) and the :attr:`col_offset` and :attr:`end_col_offset`
87 are the corresponding UTF-8 byte offsets of the first and last tokens that
88 generated the node. The UTF-8 offset is recorded because the parser uses
89 UTF-8 internally.
Ivan Levkivskyi9932a222019-01-22 11:18:22 +000090
91 Note that the end positions are not required by the compiler and are
92 therefore optional. The end offset is *after* the last symbol, for example
93 one can get the source segment of a one-line expression node using
94 ``source_line[node.col_offset : node.end_col_offset]``.
Georg Brandl0c77a822008-06-10 16:37:50 +000095
96 The constructor of a class :class:`ast.T` parses its arguments as follows:
97
98 * If there are positional arguments, there must be as many as there are items
99 in :attr:`T._fields`; they will be assigned as attributes of these names.
100 * If there are keyword arguments, they will set the attributes of the same
101 names to the given values.
102
103 For example, to create and populate an :class:`ast.UnaryOp` node, you could
104 use ::
105
106 node = ast.UnaryOp()
107 node.op = ast.USub()
Serhiy Storchaka3f228112018-09-27 17:42:37 +0300108 node.operand = ast.Constant()
109 node.operand.value = 5
Georg Brandl0c77a822008-06-10 16:37:50 +0000110 node.operand.lineno = 0
111 node.operand.col_offset = 0
112 node.lineno = 0
113 node.col_offset = 0
114
115 or the more compact ::
116
Serhiy Storchaka3f228112018-09-27 17:42:37 +0300117 node = ast.UnaryOp(ast.USub(), ast.Constant(5, lineno=0, col_offset=0),
Georg Brandl0c77a822008-06-10 16:37:50 +0000118 lineno=0, col_offset=0)
119
Serhiy Storchaka85a2eef2020-02-17 11:03:00 +0200120.. versionchanged:: 3.8
121
122 Class :class:`ast.Constant` is now used for all constants.
123
Serhiy Storchaka13d52c22020-03-10 18:52:34 +0200124.. versionchanged:: 3.9
125
126 Simple indices are represented by their value, extended slices are
127 represented as tuples.
128
Serhiy Storchaka3f228112018-09-27 17:42:37 +0300129.. deprecated:: 3.8
130
Serhiy Storchaka85a2eef2020-02-17 11:03:00 +0200131 Old classes :class:`ast.Num`, :class:`ast.Str`, :class:`ast.Bytes`,
Serhiy Storchaka3f228112018-09-27 17:42:37 +0300132 :class:`ast.NameConstant` and :class:`ast.Ellipsis` are still available,
Serhiy Storchaka13d52c22020-03-10 18:52:34 +0200133 but they will be removed in future Python releases. In the meantime,
Serhiy Storchaka85a2eef2020-02-17 11:03:00 +0200134 instantiating them will return an instance of a different class.
Serhiy Storchaka3f228112018-09-27 17:42:37 +0300135
Serhiy Storchaka13d52c22020-03-10 18:52:34 +0200136.. deprecated:: 3.9
137
138 Old classes :class:`ast.Index` and :class:`ast.ExtSlice` are still
139 available, but they will be removed in future Python releases.
140 In the meantime, instantiating them will return an instance of
141 a different class.
142
Pablo Galindo62e3b632021-03-03 18:25:41 +0000143.. note::
144 The descriptions of the specific node classes displayed here
145 were initially adapted from the fantastic `Green Tree
146 Snakes <https://greentreesnakes.readthedocs.io/en/latest/>`__ project and
147 all its contributors.
Serhiy Storchaka13d52c22020-03-10 18:52:34 +0200148
Pablo Galindo114081f2020-03-02 03:14:06 +0000149Literals
150^^^^^^^^
Georg Brandl0c77a822008-06-10 16:37:50 +0000151
Pablo Galindo114081f2020-03-02 03:14:06 +0000152.. class:: Constant(value)
Georg Brandl0c77a822008-06-10 16:37:50 +0000153
Pablo Galindo114081f2020-03-02 03:14:06 +0000154 A constant value. The ``value`` attribute of the ``Constant`` literal contains the
155 Python object it represents. The values represented can be simple types
156 such as a number, string or ``None``, but also immutable container types
157 (tuples and frozensets) if all of their elements are constant.
Georg Brandl0c77a822008-06-10 16:37:50 +0000158
Pablo Galindo114081f2020-03-02 03:14:06 +0000159 .. doctest::
Georg Brandl0c77a822008-06-10 16:37:50 +0000160
Pablo Galindo02f64cb2020-03-07 18:22:58 +0000161 >>> print(ast.dump(ast.parse('123', mode='eval'), indent=4))
162 Expression(
Serhiy Storchakab7e95252020-03-10 00:07:47 +0200163 body=Constant(value=123))
Pablo Galindo114081f2020-03-02 03:14:06 +0000164
165
166.. class:: FormattedValue(value, conversion, format_spec)
167
168 Node representing a single formatting field in an f-string. If the string
169 contains a single formatting field and nothing else the node can be
170 isolated otherwise it appears in :class:`JoinedStr`.
171
172 * ``value`` is any expression node (such as a literal, a variable, or a
173 function call).
174 * ``conversion`` is an integer:
175
176 * -1: no formatting
177 * 115: ``!s`` string formatting
178 * 114: ``!r`` repr formatting
179 * 97: ``!a`` ascii formatting
180
181 * ``format_spec`` is a :class:`JoinedStr` node representing the formatting
182 of the value, or ``None`` if no format was specified. Both
183 ``conversion`` and ``format_spec`` can be set at the same time.
184
185
186.. class:: JoinedStr(values)
187
188 An f-string, comprising a series of :class:`FormattedValue` and :class:`Constant`
189 nodes.
190
191 .. doctest::
192
Pablo Galindo02f64cb2020-03-07 18:22:58 +0000193 >>> print(ast.dump(ast.parse('f"sin({a}) is {sin(a):.3}"', mode='eval'), indent=4))
194 Expression(
195 body=JoinedStr(
196 values=[
Serhiy Storchakab7e95252020-03-10 00:07:47 +0200197 Constant(value='sin('),
Pablo Galindo02f64cb2020-03-07 18:22:58 +0000198 FormattedValue(
199 value=Name(id='a', ctx=Load()),
Serhiy Storchakab7e95252020-03-10 00:07:47 +0200200 conversion=-1),
201 Constant(value=') is '),
Pablo Galindo02f64cb2020-03-07 18:22:58 +0000202 FormattedValue(
203 value=Call(
204 func=Name(id='sin', ctx=Load()),
205 args=[
206 Name(id='a', ctx=Load())],
207 keywords=[]),
208 conversion=-1,
209 format_spec=JoinedStr(
210 values=[
Serhiy Storchakab7e95252020-03-10 00:07:47 +0200211 Constant(value='.3')]))]))
Pablo Galindo114081f2020-03-02 03:14:06 +0000212
213
214.. class:: List(elts, ctx)
215 Tuple(elts, ctx)
216
217 A list or tuple. ``elts`` holds a list of nodes representing the elements.
218 ``ctx`` is :class:`Store` if the container is an assignment target (i.e.
219 ``(x,y)=something``), and :class:`Load` otherwise.
220
221 .. doctest::
222
Pablo Galindo02f64cb2020-03-07 18:22:58 +0000223 >>> print(ast.dump(ast.parse('[1, 2, 3]', mode='eval'), indent=4))
224 Expression(
225 body=List(
226 elts=[
Serhiy Storchakab7e95252020-03-10 00:07:47 +0200227 Constant(value=1),
228 Constant(value=2),
229 Constant(value=3)],
Pablo Galindo02f64cb2020-03-07 18:22:58 +0000230 ctx=Load()))
231 >>> print(ast.dump(ast.parse('(1, 2, 3)', mode='eval'), indent=4))
232 Expression(
233 body=Tuple(
234 elts=[
Serhiy Storchakab7e95252020-03-10 00:07:47 +0200235 Constant(value=1),
236 Constant(value=2),
237 Constant(value=3)],
Pablo Galindo02f64cb2020-03-07 18:22:58 +0000238 ctx=Load()))
Pablo Galindo114081f2020-03-02 03:14:06 +0000239
240
241.. class:: Set(elts)
242
243 A set. ``elts`` holds a list of nodes representing the set's elements.
244
245 .. doctest::
246
Pablo Galindo02f64cb2020-03-07 18:22:58 +0000247 >>> print(ast.dump(ast.parse('{1, 2, 3}', mode='eval'), indent=4))
248 Expression(
249 body=Set(
250 elts=[
Serhiy Storchakab7e95252020-03-10 00:07:47 +0200251 Constant(value=1),
252 Constant(value=2),
253 Constant(value=3)]))
Pablo Galindo114081f2020-03-02 03:14:06 +0000254
255
256.. class:: Dict(keys, values)
257
258 A dictionary. ``keys`` and ``values`` hold lists of nodes representing the
259 keys and the values respectively, in matching order (what would be returned
260 when calling :code:`dictionary.keys()` and :code:`dictionary.values()`).
261
262 When doing dictionary unpacking using dictionary literals the expression to be
263 expanded goes in the ``values`` list, with a ``None`` at the corresponding
264 position in ``keys``.
265
266 .. doctest::
267
Pablo Galindo02f64cb2020-03-07 18:22:58 +0000268 >>> print(ast.dump(ast.parse('{"a":1, **d}', mode='eval'), indent=4))
269 Expression(
270 body=Dict(
271 keys=[
Serhiy Storchakab7e95252020-03-10 00:07:47 +0200272 Constant(value='a'),
Pablo Galindo02f64cb2020-03-07 18:22:58 +0000273 None],
274 values=[
Serhiy Storchakab7e95252020-03-10 00:07:47 +0200275 Constant(value=1),
Pablo Galindo02f64cb2020-03-07 18:22:58 +0000276 Name(id='d', ctx=Load())]))
Pablo Galindo114081f2020-03-02 03:14:06 +0000277
278
279Variables
280^^^^^^^^^
281
282.. class:: Name(id, ctx)
283
284 A variable name. ``id`` holds the name as a string, and ``ctx`` is one of
285 the following types.
286
287
288.. class:: Load()
289 Store()
290 Del()
291
292 Variable references can be used to load the value of a variable, to assign
293 a new value to it, or to delete it. Variable references are given a context
294 to distinguish these cases.
295
296 .. doctest::
297
298 >>> print(ast.dump(ast.parse('a'), indent=4))
299 Module(
300 body=[
301 Expr(
302 value=Name(id='a', ctx=Load()))],
303 type_ignores=[])
304
305 >>> print(ast.dump(ast.parse('a = 1'), indent=4))
306 Module(
307 body=[
308 Assign(
309 targets=[
310 Name(id='a', ctx=Store())],
Serhiy Storchakab7e95252020-03-10 00:07:47 +0200311 value=Constant(value=1))],
Pablo Galindo114081f2020-03-02 03:14:06 +0000312 type_ignores=[])
313
314 >>> print(ast.dump(ast.parse('del a'), indent=4))
315 Module(
316 body=[
317 Delete(
318 targets=[
319 Name(id='a', ctx=Del())])],
320 type_ignores=[])
321
322
323.. class:: Starred(value, ctx)
324
325 A ``*var`` variable reference. ``value`` holds the variable, typically a
326 :class:`Name` node. This type must be used when building a :class:`Call`
327 node with ``*args``.
328
329 .. doctest::
330
331 >>> print(ast.dump(ast.parse('a, *b = it'), indent=4))
332 Module(
333 body=[
334 Assign(
335 targets=[
336 Tuple(
337 elts=[
338 Name(id='a', ctx=Store()),
339 Starred(
340 value=Name(id='b', ctx=Store()),
341 ctx=Store())],
342 ctx=Store())],
Serhiy Storchakab7e95252020-03-10 00:07:47 +0200343 value=Name(id='it', ctx=Load()))],
Pablo Galindo114081f2020-03-02 03:14:06 +0000344 type_ignores=[])
345
346
347Expressions
348^^^^^^^^^^^
349
350.. class:: Expr(value)
351
352 When an expression, such as a function call, appears as a statement by itself
353 with its return value not used or stored, it is wrapped in this container.
354 ``value`` holds one of the other nodes in this section, a :class:`Constant`, a
355 :class:`Name`, a :class:`Lambda`, a :class:`Yield` or :class:`YieldFrom` node.
356
357 .. doctest::
358
359 >>> print(ast.dump(ast.parse('-a'), indent=4))
360 Module(
361 body=[
362 Expr(
363 value=UnaryOp(
364 op=USub(),
365 operand=Name(id='a', ctx=Load())))],
366 type_ignores=[])
367
368
369.. class:: UnaryOp(op, operand)
370
371 A unary operation. ``op`` is the operator, and ``operand`` any expression
372 node.
373
374
375.. class:: UAdd
376 USub
377 Not
378 Invert
379
380 Unary operator tokens. :class:`Not` is the ``not`` keyword, :class:`Invert`
381 is the ``~`` operator.
382
383 .. doctest::
384
Pablo Galindo02f64cb2020-03-07 18:22:58 +0000385 >>> print(ast.dump(ast.parse('not x', mode='eval'), indent=4))
386 Expression(
387 body=UnaryOp(
388 op=Not(),
389 operand=Name(id='x', ctx=Load())))
Pablo Galindo114081f2020-03-02 03:14:06 +0000390
391
392.. class:: BinOp(left, op, right)
393
394 A binary operation (like addition or division). ``op`` is the operator, and
395 ``left`` and ``right`` are any expression nodes.
396
397 .. doctest::
398
Pablo Galindo02f64cb2020-03-07 18:22:58 +0000399 >>> print(ast.dump(ast.parse('x + y', mode='eval'), indent=4))
400 Expression(
401 body=BinOp(
402 left=Name(id='x', ctx=Load()),
403 op=Add(),
404 right=Name(id='y', ctx=Load())))
Pablo Galindo114081f2020-03-02 03:14:06 +0000405
406
407.. class:: Add
408 Sub
409 Mult
410 Div
411 FloorDiv
412 Mod
413 Pow
414 LShift
415 RShift
416 BitOr
417 BitXor
418 BitAnd
419 MatMult
420
421 Binary operator tokens.
422
423
424.. class:: BoolOp(op, values)
425
426 A boolean operation, 'or' or 'and'. ``op`` is :class:`Or` or :class:`And`.
427 ``values`` are the values involved. Consecutive operations with the same
428 operator, such as ``a or b or c``, are collapsed into one node with several
429 values.
430
431 This doesn't include ``not``, which is a :class:`UnaryOp`.
432
433 .. doctest::
434
Pablo Galindo02f64cb2020-03-07 18:22:58 +0000435 >>> print(ast.dump(ast.parse('x or y', mode='eval'), indent=4))
436 Expression(
437 body=BoolOp(
438 op=Or(),
439 values=[
440 Name(id='x', ctx=Load()),
441 Name(id='y', ctx=Load())]))
Pablo Galindo114081f2020-03-02 03:14:06 +0000442
443
444.. class:: And
445 Or
446
447 Boolean operator tokens.
448
449
450.. class:: Compare(left, ops, comparators)
451
452 A comparison of two or more values. ``left`` is the first value in the
453 comparison, ``ops`` the list of operators, and ``comparators`` the list
454 of values after the first element in the comparison.
455
456 .. doctest::
457
Pablo Galindo02f64cb2020-03-07 18:22:58 +0000458 >>> print(ast.dump(ast.parse('1 <= a < 10', mode='eval'), indent=4))
459 Expression(
460 body=Compare(
Serhiy Storchakab7e95252020-03-10 00:07:47 +0200461 left=Constant(value=1),
Pablo Galindo02f64cb2020-03-07 18:22:58 +0000462 ops=[
463 LtE(),
464 Lt()],
465 comparators=[
466 Name(id='a', ctx=Load()),
Serhiy Storchakab7e95252020-03-10 00:07:47 +0200467 Constant(value=10)]))
Pablo Galindo114081f2020-03-02 03:14:06 +0000468
469
470.. class:: Eq
471 NotEq
472 Lt
473 LtE
474 Gt
475 GtE
476 Is
477 IsNot
478 In
479 NotIn
480
481 Comparison operator tokens.
482
483
484.. class:: Call(func, args, keywords, starargs, kwargs)
485
486 A function call. ``func`` is the function, which will often be a
487 :class:`Name` or :class:`Attribute` object. Of the arguments:
488
489 * ``args`` holds a list of the arguments passed by position.
490 * ``keywords`` holds a list of :class:`keyword` objects representing
491 arguments passed by keyword.
492
493 When creating a ``Call`` node, ``args`` and ``keywords`` are required, but
494 they can be empty lists. ``starargs`` and ``kwargs`` are optional.
495
496 .. doctest::
497
Pablo Galindo02f64cb2020-03-07 18:22:58 +0000498 >>> print(ast.dump(ast.parse('func(a, b=c, *d, **e)', mode='eval'), indent=4))
499 Expression(
500 body=Call(
501 func=Name(id='func', ctx=Load()),
502 args=[
503 Name(id='a', ctx=Load()),
504 Starred(
505 value=Name(id='d', ctx=Load()),
506 ctx=Load())],
507 keywords=[
508 keyword(
509 arg='b',
510 value=Name(id='c', ctx=Load())),
511 keyword(
Pablo Galindo02f64cb2020-03-07 18:22:58 +0000512 value=Name(id='e', ctx=Load()))]))
Pablo Galindo114081f2020-03-02 03:14:06 +0000513
514
515.. class:: keyword(arg, value)
516
517 A keyword argument to a function call or class definition. ``arg`` is a raw
518 string of the parameter name, ``value`` is a node to pass in.
519
520
521.. class:: IfExp(test, body, orelse)
522
523 An expression such as ``a if b else c``. Each field holds a single node, so
524 in the following example, all three are :class:`Name` nodes.
525
526 .. doctest::
527
Pablo Galindo02f64cb2020-03-07 18:22:58 +0000528 >>> print(ast.dump(ast.parse('a if b else c', mode='eval'), indent=4))
529 Expression(
530 body=IfExp(
531 test=Name(id='b', ctx=Load()),
532 body=Name(id='a', ctx=Load()),
533 orelse=Name(id='c', ctx=Load())))
Pablo Galindo114081f2020-03-02 03:14:06 +0000534
535
536.. class:: Attribute(value, attr, ctx)
537
538 Attribute access, e.g. ``d.keys``. ``value`` is a node, typically a
539 :class:`Name`. ``attr`` is a bare string giving the name of the attribute,
540 and ``ctx`` is :class:`Load`, :class:`Store` or :class:`Del` according to how
541 the attribute is acted on.
542
543 .. doctest::
544
Pablo Galindo02f64cb2020-03-07 18:22:58 +0000545 >>> print(ast.dump(ast.parse('snake.colour', mode='eval'), indent=4))
546 Expression(
547 body=Attribute(
548 value=Name(id='snake', ctx=Load()),
549 attr='colour',
550 ctx=Load()))
Pablo Galindo114081f2020-03-02 03:14:06 +0000551
552
553.. class:: NamedExpr(target, value)
554
555 A named expression. This AST node is produced by the assignment expressions
556 operator (also known as the walrus operator). As opposed to the :class:`Assign`
557 node in which the first argument can be multiple nodes, in this case both
558 ``target`` and ``value`` must be single nodes.
559
560 .. doctest::
561
Pablo Galindo02f64cb2020-03-07 18:22:58 +0000562 >>> print(ast.dump(ast.parse('(x := 4)', mode='eval'), indent=4))
563 Expression(
564 body=NamedExpr(
565 target=Name(id='x', ctx=Store()),
Serhiy Storchakab7e95252020-03-10 00:07:47 +0200566 value=Constant(value=4)))
Pablo Galindo114081f2020-03-02 03:14:06 +0000567
568
569Subscripting
570~~~~~~~~~~~~
571
572.. class:: Subscript(value, slice, ctx)
573
Serhiy Storchaka13d52c22020-03-10 18:52:34 +0200574 A subscript, such as ``l[1]``. ``value`` is the subscripted object
575 (usually sequence or mapping). ``slice`` is an index, slice or key.
576 It can be a :class:`Tuple` and contain a :class:`Slice`.
577 ``ctx`` is :class:`Load`, :class:`Store` or :class:`Del`
Pablo Galindo114081f2020-03-02 03:14:06 +0000578 according to the action performed with the subscript.
579
Pablo Galindo114081f2020-03-02 03:14:06 +0000580 .. doctest::
581
Serhiy Storchaka13d52c22020-03-10 18:52:34 +0200582 >>> print(ast.dump(ast.parse('l[1:2, 3]', mode='eval'), indent=4))
Pablo Galindo02f64cb2020-03-07 18:22:58 +0000583 Expression(
584 body=Subscript(
585 value=Name(id='l', ctx=Load()),
Serhiy Storchaka13d52c22020-03-10 18:52:34 +0200586 slice=Tuple(
587 elts=[
588 Slice(
589 lower=Constant(value=1),
590 upper=Constant(value=2)),
591 Constant(value=3)],
592 ctx=Load()),
Pablo Galindo02f64cb2020-03-07 18:22:58 +0000593 ctx=Load()))
Pablo Galindo114081f2020-03-02 03:14:06 +0000594
595
596.. class:: Slice(lower, upper, step)
597
Serhiy Storchaka13d52c22020-03-10 18:52:34 +0200598 Regular slicing (on the form ``lower:upper`` or ``lower:upper:step``).
599 Can occur only inside the *slice* field of :class:`Subscript`, either
600 directly or as an element of :class:`Tuple`.
Pablo Galindo114081f2020-03-02 03:14:06 +0000601
602 .. doctest::
603
Pablo Galindo02f64cb2020-03-07 18:22:58 +0000604 >>> print(ast.dump(ast.parse('l[1:2]', mode='eval'), indent=4))
605 Expression(
606 body=Subscript(
607 value=Name(id='l', ctx=Load()),
608 slice=Slice(
Serhiy Storchakab7e95252020-03-10 00:07:47 +0200609 lower=Constant(value=1),
610 upper=Constant(value=2)),
Pablo Galindo02f64cb2020-03-07 18:22:58 +0000611 ctx=Load()))
Pablo Galindo114081f2020-03-02 03:14:06 +0000612
613
Pablo Galindo114081f2020-03-02 03:14:06 +0000614Comprehensions
615~~~~~~~~~~~~~~
616
617.. class:: ListComp(elt, generators)
618 SetComp(elt, generators)
619 GeneratorExp(elt, generators)
620 DictComp(key, value, generators)
621
622 List and set comprehensions, generator expressions, and dictionary
623 comprehensions. ``elt`` (or ``key`` and ``value``) is a single node
624 representing the part that will be evaluated for each item.
625
626 ``generators`` is a list of :class:`comprehension` nodes.
627
628 .. doctest::
629
Pablo Galindo02f64cb2020-03-07 18:22:58 +0000630 >>> print(ast.dump(ast.parse('[x for x in numbers]', mode='eval'), indent=4))
631 Expression(
632 body=ListComp(
633 elt=Name(id='x', ctx=Load()),
634 generators=[
635 comprehension(
636 target=Name(id='x', ctx=Store()),
637 iter=Name(id='numbers', ctx=Load()),
638 ifs=[],
639 is_async=0)]))
640 >>> print(ast.dump(ast.parse('{x: x**2 for x in numbers}', mode='eval'), indent=4))
641 Expression(
642 body=DictComp(
643 key=Name(id='x', ctx=Load()),
644 value=BinOp(
645 left=Name(id='x', ctx=Load()),
646 op=Pow(),
Serhiy Storchakab7e95252020-03-10 00:07:47 +0200647 right=Constant(value=2)),
Pablo Galindo02f64cb2020-03-07 18:22:58 +0000648 generators=[
649 comprehension(
650 target=Name(id='x', ctx=Store()),
651 iter=Name(id='numbers', ctx=Load()),
652 ifs=[],
653 is_async=0)]))
654 >>> print(ast.dump(ast.parse('{x for x in numbers}', mode='eval'), indent=4))
655 Expression(
656 body=SetComp(
657 elt=Name(id='x', ctx=Load()),
658 generators=[
659 comprehension(
660 target=Name(id='x', ctx=Store()),
661 iter=Name(id='numbers', ctx=Load()),
662 ifs=[],
663 is_async=0)]))
Pablo Galindo114081f2020-03-02 03:14:06 +0000664
665
666.. class:: comprehension(target, iter, ifs, is_async)
667
668 One ``for`` clause in a comprehension. ``target`` is the reference to use for
669 each element - typically a :class:`Name` or :class:`Tuple` node. ``iter``
670 is the object to iterate over. ``ifs`` is a list of test expressions: each
671 ``for`` clause can have multiple ``ifs``.
672
673 ``is_async`` indicates a comprehension is asynchronous (using an
674 ``async for`` instead of ``for``). The value is an integer (0 or 1).
675
676 .. doctest::
677
Pablo Galindo02f64cb2020-03-07 18:22:58 +0000678 >>> print(ast.dump(ast.parse('[ord(c) for line in file for c in line]', mode='eval'),
Pablo Galindo114081f2020-03-02 03:14:06 +0000679 ... indent=4)) # Multiple comprehensions in one.
680 Expression(
681 body=ListComp(
682 elt=Call(
683 func=Name(id='ord', ctx=Load()),
684 args=[
685 Name(id='c', ctx=Load())],
686 keywords=[]),
687 generators=[
688 comprehension(
689 target=Name(id='line', ctx=Store()),
690 iter=Name(id='file', ctx=Load()),
691 ifs=[],
692 is_async=0),
693 comprehension(
694 target=Name(id='c', ctx=Store()),
695 iter=Name(id='line', ctx=Load()),
696 ifs=[],
697 is_async=0)]))
698
Pablo Galindo02f64cb2020-03-07 18:22:58 +0000699 >>> print(ast.dump(ast.parse('(n**2 for n in it if n>5 if n<10)', mode='eval'),
Pablo Galindo114081f2020-03-02 03:14:06 +0000700 ... indent=4)) # generator comprehension
701 Expression(
702 body=GeneratorExp(
703 elt=BinOp(
704 left=Name(id='n', ctx=Load()),
705 op=Pow(),
Serhiy Storchakab7e95252020-03-10 00:07:47 +0200706 right=Constant(value=2)),
Pablo Galindo114081f2020-03-02 03:14:06 +0000707 generators=[
708 comprehension(
709 target=Name(id='n', ctx=Store()),
710 iter=Name(id='it', ctx=Load()),
711 ifs=[
712 Compare(
713 left=Name(id='n', ctx=Load()),
714 ops=[
715 Gt()],
716 comparators=[
Serhiy Storchakab7e95252020-03-10 00:07:47 +0200717 Constant(value=5)]),
Pablo Galindo114081f2020-03-02 03:14:06 +0000718 Compare(
719 left=Name(id='n', ctx=Load()),
720 ops=[
721 Lt()],
722 comparators=[
Serhiy Storchakab7e95252020-03-10 00:07:47 +0200723 Constant(value=10)])],
Pablo Galindo114081f2020-03-02 03:14:06 +0000724 is_async=0)]))
725
Pablo Galindo02f64cb2020-03-07 18:22:58 +0000726 >>> print(ast.dump(ast.parse('[i async for i in soc]', mode='eval'),
Pablo Galindo114081f2020-03-02 03:14:06 +0000727 ... indent=4)) # Async comprehension
Pablo Galindo02f64cb2020-03-07 18:22:58 +0000728 Expression(
729 body=ListComp(
730 elt=Name(id='i', ctx=Load()),
731 generators=[
732 comprehension(
733 target=Name(id='i', ctx=Store()),
734 iter=Name(id='soc', ctx=Load()),
735 ifs=[],
736 is_async=1)]))
Pablo Galindo114081f2020-03-02 03:14:06 +0000737
738Statements
739^^^^^^^^^^
740
741.. class:: Assign(targets, value, type_comment)
742
743 An assignment. ``targets`` is a list of nodes, and ``value`` is a single node.
744
745 Multiple nodes in ``targets`` represents assigning the same value to each.
746 Unpacking is represented by putting a :class:`Tuple` or :class:`List`
747 within ``targets``.
748
749 .. attribute:: type_comment
750
751 ``type_comment`` is an optional string with the type annotation as a comment.
752
753 .. doctest::
754
Pablo Galindo02f64cb2020-03-07 18:22:58 +0000755 >>> print(ast.dump(ast.parse('a = b = 1'), indent=4)) # Multiple assignment
Pablo Galindo114081f2020-03-02 03:14:06 +0000756 Module(
757 body=[
758 Assign(
759 targets=[
760 Name(id='a', ctx=Store()),
761 Name(id='b', ctx=Store())],
Serhiy Storchakab7e95252020-03-10 00:07:47 +0200762 value=Constant(value=1))],
Pablo Galindo114081f2020-03-02 03:14:06 +0000763 type_ignores=[])
764
Pablo Galindo02f64cb2020-03-07 18:22:58 +0000765 >>> print(ast.dump(ast.parse('a,b = c'), indent=4)) # Unpacking
Pablo Galindo114081f2020-03-02 03:14:06 +0000766 Module(
767 body=[
768 Assign(
769 targets=[
770 Tuple(
771 elts=[
772 Name(id='a', ctx=Store()),
773 Name(id='b', ctx=Store())],
774 ctx=Store())],
Serhiy Storchakab7e95252020-03-10 00:07:47 +0200775 value=Name(id='c', ctx=Load()))],
Pablo Galindo114081f2020-03-02 03:14:06 +0000776 type_ignores=[])
777
778
779.. class:: AnnAssign(target, annotation, value, simple)
780
781 An assignment with a type annotation. ``target`` is a single node and can
782 be a :class:`Name`, a :class:`Attribute` or a :class:`Subscript`.
783 ``annotation`` is the annotation, such as a :class:`Constant` or :class:`Name`
784 node. ``value`` is a single optional node. ``simple`` is a boolean integer
785 set to True for a :class:`Name` node in ``target`` that do not appear in
786 between parenthesis and are hence pure names and not expressions.
787
788 .. doctest::
789
Pablo Galindo02f64cb2020-03-07 18:22:58 +0000790 >>> print(ast.dump(ast.parse('c: int'), indent=4))
Pablo Galindo114081f2020-03-02 03:14:06 +0000791 Module(
792 body=[
793 AnnAssign(
794 target=Name(id='c', ctx=Store()),
795 annotation=Name(id='int', ctx=Load()),
Pablo Galindo114081f2020-03-02 03:14:06 +0000796 simple=1)],
797 type_ignores=[])
798
Pablo Galindo02f64cb2020-03-07 18:22:58 +0000799 >>> print(ast.dump(ast.parse('(a): int = 1'), indent=4)) # Annotation with parenthesis
Pablo Galindo114081f2020-03-02 03:14:06 +0000800 Module(
801 body=[
802 AnnAssign(
803 target=Name(id='a', ctx=Store()),
804 annotation=Name(id='int', ctx=Load()),
Serhiy Storchakab7e95252020-03-10 00:07:47 +0200805 value=Constant(value=1),
Pablo Galindo114081f2020-03-02 03:14:06 +0000806 simple=0)],
807 type_ignores=[])
808
Pablo Galindo02f64cb2020-03-07 18:22:58 +0000809 >>> print(ast.dump(ast.parse('a.b: int'), indent=4)) # Attribute annotation
Pablo Galindo114081f2020-03-02 03:14:06 +0000810 Module(
811 body=[
812 AnnAssign(
813 target=Attribute(
814 value=Name(id='a', ctx=Load()),
815 attr='b',
816 ctx=Store()),
817 annotation=Name(id='int', ctx=Load()),
Pablo Galindo114081f2020-03-02 03:14:06 +0000818 simple=0)],
819 type_ignores=[])
820
Pablo Galindo02f64cb2020-03-07 18:22:58 +0000821 >>> print(ast.dump(ast.parse('a[1]: int'), indent=4)) # Subscript annotation
Pablo Galindo114081f2020-03-02 03:14:06 +0000822 Module(
823 body=[
824 AnnAssign(
825 target=Subscript(
826 value=Name(id='a', ctx=Load()),
Serhiy Storchaka13d52c22020-03-10 18:52:34 +0200827 slice=Constant(value=1),
Pablo Galindo114081f2020-03-02 03:14:06 +0000828 ctx=Store()),
829 annotation=Name(id='int', ctx=Load()),
Pablo Galindo114081f2020-03-02 03:14:06 +0000830 simple=0)],
831 type_ignores=[])
832
833
834.. class:: AugAssign(target, op, value)
835
836 Augmented assignment, such as ``a += 1``. In the following example,
837 ``target`` is a :class:`Name` node for ``x`` (with the :class:`Store`
838 context), ``op`` is :class:`Add`, and ``value`` is a :class:`Constant` with
839 value for 1.
840
841 The ``target`` attribute connot be of class :class:`Tuple` or :class:`List`,
842 unlike the targets of :class:`Assign`.
843
844 .. doctest::
845
Pablo Galindo02f64cb2020-03-07 18:22:58 +0000846 >>> print(ast.dump(ast.parse('x += 2'), indent=4))
Pablo Galindo114081f2020-03-02 03:14:06 +0000847 Module(
848 body=[
849 AugAssign(
850 target=Name(id='x', ctx=Store()),
851 op=Add(),
Serhiy Storchakab7e95252020-03-10 00:07:47 +0200852 value=Constant(value=2))],
Pablo Galindo114081f2020-03-02 03:14:06 +0000853 type_ignores=[])
854
855
856.. class:: Raise(exc, cause)
857
858 A ``raise`` statement. ``exc`` is the exception object to be raised, normally a
859 :class:`Call` or :class:`Name`, or ``None`` for a standalone ``raise``.
860 ``cause`` is the optional part for ``y`` in ``raise x from y``.
861
862 .. doctest::
863
Pablo Galindo02f64cb2020-03-07 18:22:58 +0000864 >>> print(ast.dump(ast.parse('raise x from y'), indent=4))
Pablo Galindo114081f2020-03-02 03:14:06 +0000865 Module(
866 body=[
867 Raise(
868 exc=Name(id='x', ctx=Load()),
869 cause=Name(id='y', ctx=Load()))],
870 type_ignores=[])
871
872
873.. class:: Assert(test, msg)
874
875 An assertion. ``test`` holds the condition, such as a :class:`Compare` node.
876 ``msg`` holds the failure message.
877
878 .. doctest::
879
Pablo Galindo02f64cb2020-03-07 18:22:58 +0000880 >>> print(ast.dump(ast.parse('assert x,y'), indent=4))
Pablo Galindo114081f2020-03-02 03:14:06 +0000881 Module(
882 body=[
883 Assert(
884 test=Name(id='x', ctx=Load()),
885 msg=Name(id='y', ctx=Load()))],
886 type_ignores=[])
887
888
889.. class:: Delete(targets)
890
891 Represents a ``del`` statement. ``targets`` is a list of nodes, such as
892 :class:`Name`, :class:`Attribute` or :class:`Subscript` nodes.
893
894 .. doctest::
895
Pablo Galindo02f64cb2020-03-07 18:22:58 +0000896 >>> print(ast.dump(ast.parse('del x,y,z'), indent=4))
Pablo Galindo114081f2020-03-02 03:14:06 +0000897 Module(
898 body=[
899 Delete(
900 targets=[
901 Name(id='x', ctx=Del()),
902 Name(id='y', ctx=Del()),
903 Name(id='z', ctx=Del())])],
904 type_ignores=[])
905
906
907.. class:: Pass()
908
909 A ``pass`` statement.
910
911 .. doctest::
912
Pablo Galindo02f64cb2020-03-07 18:22:58 +0000913 >>> print(ast.dump(ast.parse('pass'), indent=4))
Pablo Galindo114081f2020-03-02 03:14:06 +0000914 Module(
915 body=[
916 Pass()],
917 type_ignores=[])
918
919
920Other statements which are only applicable inside functions or loops are
921described in other sections.
922
923Imports
924~~~~~~~
925
926.. class:: Import(names)
927
928 An import statement. ``names`` is a list of :class:`alias` nodes.
929
930 .. doctest::
931
Pablo Galindo02f64cb2020-03-07 18:22:58 +0000932 >>> print(ast.dump(ast.parse('import x,y,z'), indent=4))
Pablo Galindo114081f2020-03-02 03:14:06 +0000933 Module(
934 body=[
935 Import(
936 names=[
Serhiy Storchakab7e95252020-03-10 00:07:47 +0200937 alias(name='x'),
938 alias(name='y'),
939 alias(name='z')])],
Pablo Galindo114081f2020-03-02 03:14:06 +0000940 type_ignores=[])
941
942
943.. class:: ImportFrom(module, names, level)
944
945 Represents ``from x import y``. ``module`` is a raw string of the 'from' name,
946 without any leading dots, or ``None`` for statements such as ``from . import foo``.
947 ``level`` is an integer holding the level of the relative import (0 means
948 absolute import).
949
950 .. doctest::
951
Pablo Galindo02f64cb2020-03-07 18:22:58 +0000952 >>> print(ast.dump(ast.parse('from y import x,y,z'), indent=4))
Pablo Galindo114081f2020-03-02 03:14:06 +0000953 Module(
954 body=[
955 ImportFrom(
956 module='y',
957 names=[
Serhiy Storchakab7e95252020-03-10 00:07:47 +0200958 alias(name='x'),
959 alias(name='y'),
960 alias(name='z')],
Pablo Galindo114081f2020-03-02 03:14:06 +0000961 level=0)],
962 type_ignores=[])
963
964
965.. class:: alias(name, asname)
966
967 Both parameters are raw strings of the names. ``asname`` can be ``None`` if
968 the regular name is to be used.
969
970 .. doctest::
971
Pablo Galindo02f64cb2020-03-07 18:22:58 +0000972 >>> print(ast.dump(ast.parse('from ..foo.bar import a as b, c'), indent=4))
Pablo Galindo114081f2020-03-02 03:14:06 +0000973 Module(
974 body=[
975 ImportFrom(
976 module='foo.bar',
977 names=[
978 alias(name='a', asname='b'),
Serhiy Storchakab7e95252020-03-10 00:07:47 +0200979 alias(name='c')],
Pablo Galindo114081f2020-03-02 03:14:06 +0000980 level=2)],
981 type_ignores=[])
982
983Control flow
984^^^^^^^^^^^^
985
986.. note::
987 Optional clauses such as ``else`` are stored as an empty list if they're
988 not present.
989
990.. class:: If(test, body, orelse)
991
992 An ``if`` statement. ``test`` holds a single node, such as a :class:`Compare`
993 node. ``body`` and ``orelse`` each hold a list of nodes.
994
995 ``elif`` clauses don't have a special representation in the AST, but rather
996 appear as extra :class:`If` nodes within the ``orelse`` section of the
997 previous one.
998
999 .. doctest::
1000
1001 >>> print(ast.dump(ast.parse("""
1002 ... if x:
1003 ... ...
1004 ... elif y:
1005 ... ...
1006 ... else:
1007 ... ...
1008 ... """), indent=4))
1009 Module(
1010 body=[
1011 If(
1012 test=Name(id='x', ctx=Load()),
1013 body=[
1014 Expr(
Serhiy Storchakab7e95252020-03-10 00:07:47 +02001015 value=Constant(value=Ellipsis))],
Pablo Galindo114081f2020-03-02 03:14:06 +00001016 orelse=[
1017 If(
1018 test=Name(id='y', ctx=Load()),
1019 body=[
1020 Expr(
Serhiy Storchakab7e95252020-03-10 00:07:47 +02001021 value=Constant(value=Ellipsis))],
Pablo Galindo114081f2020-03-02 03:14:06 +00001022 orelse=[
1023 Expr(
Serhiy Storchakab7e95252020-03-10 00:07:47 +02001024 value=Constant(value=Ellipsis))])])],
Pablo Galindo114081f2020-03-02 03:14:06 +00001025 type_ignores=[])
1026
1027
1028.. class:: For(target, iter, body, orelse, type_comment)
1029
1030 A ``for`` loop. ``target`` holds the variable(s) the loop assigns to, as a
1031 single :class:`Name`, :class:`Tuple` or :class:`List` node. ``iter`` holds
1032 the item to be looped over, again as a single node. ``body`` and ``orelse``
1033 contain lists of nodes to execute. Those in ``orelse`` are executed if the
1034 loop finishes normally, rather than via a ``break`` statement.
1035
1036 .. attribute:: type_comment
1037
1038 ``type_comment`` is an optional string with the type annotation as a comment.
1039
1040 .. doctest::
1041
1042 >>> print(ast.dump(ast.parse("""
1043 ... for x in y:
1044 ... ...
1045 ... else:
1046 ... ...
1047 ... """), indent=4))
1048 Module(
1049 body=[
1050 For(
1051 target=Name(id='x', ctx=Store()),
1052 iter=Name(id='y', ctx=Load()),
1053 body=[
1054 Expr(
Serhiy Storchakab7e95252020-03-10 00:07:47 +02001055 value=Constant(value=Ellipsis))],
Pablo Galindo114081f2020-03-02 03:14:06 +00001056 orelse=[
1057 Expr(
Serhiy Storchakab7e95252020-03-10 00:07:47 +02001058 value=Constant(value=Ellipsis))])],
Pablo Galindo114081f2020-03-02 03:14:06 +00001059 type_ignores=[])
1060
1061
1062.. class:: While(test, body, orelse)
1063
1064 A ``while`` loop. ``test`` holds the condition, such as a :class:`Compare`
1065 node.
1066
1067 .. doctest::
1068
1069 >> print(ast.dump(ast.parse("""
1070 ... while x:
1071 ... ...
1072 ... else:
1073 ... ...
1074 ... """), indent=4))
1075 Module(
1076 body=[
1077 While(
1078 test=Name(id='x', ctx=Load()),
1079 body=[
1080 Expr(
Serhiy Storchakab7e95252020-03-10 00:07:47 +02001081 value=Constant(value=Ellipsis))],
Pablo Galindo114081f2020-03-02 03:14:06 +00001082 orelse=[
1083 Expr(
Serhiy Storchakab7e95252020-03-10 00:07:47 +02001084 value=Constant(value=Ellipsis))])],
Pablo Galindo114081f2020-03-02 03:14:06 +00001085 type_ignores=[])
1086
1087
1088.. class:: Break
1089 Continue
1090
1091 The ``break`` and ``continue`` statements.
1092
1093 .. doctest::
1094
1095 >>> print(ast.dump(ast.parse("""\
1096 ... for a in b:
1097 ... if a > 5:
1098 ... break
1099 ... else:
1100 ... continue
1101 ...
1102 ... """), indent=4))
1103 Module(
1104 body=[
1105 For(
1106 target=Name(id='a', ctx=Store()),
1107 iter=Name(id='b', ctx=Load()),
1108 body=[
1109 If(
1110 test=Compare(
1111 left=Name(id='a', ctx=Load()),
1112 ops=[
1113 Gt()],
1114 comparators=[
Serhiy Storchakab7e95252020-03-10 00:07:47 +02001115 Constant(value=5)]),
Pablo Galindo114081f2020-03-02 03:14:06 +00001116 body=[
1117 Break()],
1118 orelse=[
1119 Continue()])],
Serhiy Storchakab7e95252020-03-10 00:07:47 +02001120 orelse=[])],
Pablo Galindo114081f2020-03-02 03:14:06 +00001121 type_ignores=[])
1122
1123
1124.. class:: Try(body, handlers, orelse, finalbody)
1125
1126 ``try`` blocks. All attributes are list of nodes to execute, except for
1127 ``handlers``, which is a list of :class:`ExceptHandler` nodes.
1128
1129 .. doctest::
1130
1131 >>> print(ast.dump(ast.parse("""
1132 ... try:
1133 ... ...
1134 ... except Exception:
1135 ... ...
1136 ... except OtherException as e:
1137 ... ...
1138 ... else:
1139 ... ...
1140 ... finally:
1141 ... ...
1142 ... """), indent=4))
1143 Module(
1144 body=[
1145 Try(
1146 body=[
1147 Expr(
Serhiy Storchakab7e95252020-03-10 00:07:47 +02001148 value=Constant(value=Ellipsis))],
Pablo Galindo114081f2020-03-02 03:14:06 +00001149 handlers=[
1150 ExceptHandler(
1151 type=Name(id='Exception', ctx=Load()),
Pablo Galindo114081f2020-03-02 03:14:06 +00001152 body=[
1153 Expr(
Serhiy Storchakab7e95252020-03-10 00:07:47 +02001154 value=Constant(value=Ellipsis))]),
Pablo Galindo114081f2020-03-02 03:14:06 +00001155 ExceptHandler(
1156 type=Name(id='OtherException', ctx=Load()),
1157 name='e',
1158 body=[
1159 Expr(
Serhiy Storchakab7e95252020-03-10 00:07:47 +02001160 value=Constant(value=Ellipsis))])],
Pablo Galindo114081f2020-03-02 03:14:06 +00001161 orelse=[
1162 Expr(
Serhiy Storchakab7e95252020-03-10 00:07:47 +02001163 value=Constant(value=Ellipsis))],
Pablo Galindo114081f2020-03-02 03:14:06 +00001164 finalbody=[
1165 Expr(
Serhiy Storchakab7e95252020-03-10 00:07:47 +02001166 value=Constant(value=Ellipsis))])],
Pablo Galindo114081f2020-03-02 03:14:06 +00001167 type_ignores=[])
1168
1169
1170.. class:: ExceptHandler(type, name, body)
1171
1172 A single ``except`` clause. ``type`` is the exception type it will match,
1173 typically a :class:`Name` node (or ``None`` for a catch-all ``except:`` clause).
1174 ``name`` is a raw string for the name to hold the exception, or ``None`` if
1175 the clause doesn't have ``as foo``. ``body`` is a list of nodes.
1176
1177 .. doctest::
1178
1179 >>> print(ast.dump(ast.parse("""\
1180 ... try:
1181 ... a + 1
1182 ... except TypeError:
1183 ... pass
1184 ... """), indent=4))
1185 Module(
1186 body=[
1187 Try(
1188 body=[
1189 Expr(
1190 value=BinOp(
1191 left=Name(id='a', ctx=Load()),
1192 op=Add(),
Serhiy Storchakab7e95252020-03-10 00:07:47 +02001193 right=Constant(value=1)))],
Pablo Galindo114081f2020-03-02 03:14:06 +00001194 handlers=[
1195 ExceptHandler(
1196 type=Name(id='TypeError', ctx=Load()),
Pablo Galindo114081f2020-03-02 03:14:06 +00001197 body=[
1198 Pass()])],
1199 orelse=[],
1200 finalbody=[])],
1201 type_ignores=[])
1202
1203
1204.. class:: With(items, body, type_comment)
1205
1206 A ``with`` block. ``items`` is a list of :class:`withitem` nodes representing
1207 the context managers, and ``body`` is the indented block inside the context.
1208
1209 .. attribute:: type_comment
1210
1211 ``type_comment`` is an optional string with the type annotation as a comment.
1212
1213
1214.. class:: withitem(context_expr, optional_vars)
1215
1216 A single context manager in a ``with`` block. ``context_expr`` is the context
1217 manager, often a :class:`Call` node. ``optional_vars`` is a :class:`Name`,
1218 :class:`Tuple` or :class:`List` for the ``as foo`` part, or ``None`` if that
1219 isn't used.
1220
1221 .. doctest::
1222
1223 >>> print(ast.dump(ast.parse("""\
1224 ... with a as b, c as d:
1225 ... something(b, d)
1226 ... """), indent=4))
1227 Module(
1228 body=[
1229 With(
1230 items=[
1231 withitem(
1232 context_expr=Name(id='a', ctx=Load()),
1233 optional_vars=Name(id='b', ctx=Store())),
1234 withitem(
1235 context_expr=Name(id='c', ctx=Load()),
1236 optional_vars=Name(id='d', ctx=Store()))],
1237 body=[
1238 Expr(
1239 value=Call(
1240 func=Name(id='something', ctx=Load()),
1241 args=[
1242 Name(id='b', ctx=Load()),
1243 Name(id='d', ctx=Load())],
Serhiy Storchakab7e95252020-03-10 00:07:47 +02001244 keywords=[]))])],
Pablo Galindo114081f2020-03-02 03:14:06 +00001245 type_ignores=[])
1246
1247
Pablo Galindoa8e26152021-03-01 02:08:37 +00001248.. class:: Match(subject, cases)
1249
1250 A ``match`` statement. ``subject`` holds the subject of the match (the object
1251 that is being matched against the cases) and ``cases`` contains an iterable of
1252 :class:`match_case` nodes with the different cases.
1253
1254
1255.. class:: match_case(context_expr, optional_vars)
1256
1257 A single case pattern in a ``match`` statement. ``pattern`` contains the
1258 match pattern that will be used to match the subject against. Notice that
1259 the meaning of the :class:`AST` nodes in this attribute have a different
1260 meaning than in other places, as they represent patterns to match against.
1261 The ``guard`` attribute contains an expression that will be evaluated if
1262 the pattern matches the subject. If the pattern matches and the ``guard`` condition
1263 is truthy, the body of the case shall be executed. ``body`` contains a list
1264 of nodes to execute if the guard is truthy.
1265
1266 .. doctest::
1267
1268 >>> print(ast.dump(ast.parse("""
1269 ... match x:
1270 ... case [x] if x>0:
1271 ... ...
1272 ... case tuple():
1273 ... ...
1274 ... """), indent=4))
1275 Module(
1276 body=[
1277 Match(
1278 subject=Name(id='x', ctx=Load()),
1279 cases=[
1280 match_case(
1281 pattern=List(
1282 elts=[
1283 Name(id='x', ctx=Store())],
1284 ctx=Load()),
1285 guard=Compare(
1286 left=Name(id='x', ctx=Load()),
1287 ops=[
1288 Gt()],
1289 comparators=[
1290 Constant(value=0)]),
1291 body=[
1292 Expr(
1293 value=Constant(value=Ellipsis))]),
1294 match_case(
1295 pattern=Call(
1296 func=Name(id='tuple', ctx=Load()),
1297 args=[],
1298 keywords=[]),
1299 body=[
1300 Expr(
1301 value=Constant(value=Ellipsis))])])],
1302 type_ignores=[])
1303
1304.. class:: MatchAs(pattern, name)
1305
1306 A match "as-pattern". The as-pattern matches whatever pattern is on its
1307 left-hand side, but also binds the value to a name. ``pattern`` contains
1308 the match pattern that will be used to match the subject agsinst. The ``name``
1309 attribute contains the name that will be binded if the pattern is successful.
1310
1311 .. doctest::
1312
1313 >>> print(ast.dump(ast.parse("""
1314 ... match x:
1315 ... case [x] as y:
1316 ... ...
1317 ... """), indent=4))
1318 Module(
1319 body=[
1320 Match(
1321 subject=Name(id='x', ctx=Load()),
1322 cases=[
1323 match_case(
1324 pattern=MatchAs(
1325 pattern=List(
1326 elts=[
1327 Name(id='x', ctx=Store())],
1328 ctx=Load()),
1329 name='y'),
1330 body=[
1331 Expr(
1332 value=Constant(value=Ellipsis))])])],
1333 type_ignores=[])
1334
1335
1336.. class:: MatchOr(patterns)
1337
1338 A match "or-pattern". An or-pattern matches each of its subpatterns in turn
1339 to the subject, until one succeeds. The or-pattern is then deemed to
1340 succeed. If none of the subpatterns succeed the or-pattern fails. The
1341 ``patterns`` attribute contains a list of match patterns nodes that will be
1342 matched against the subject.
1343
1344 .. doctest::
1345
1346 >>> print(ast.dump(ast.parse("""
1347 ... match x:
1348 ... case [x] | (y):
1349 ... ...
1350 ... """), indent=4))
1351 Module(
1352 body=[
1353 Match(
1354 subject=Name(id='x', ctx=Load()),
1355 cases=[
1356 match_case(
1357 pattern=MatchOr(
1358 patterns=[
1359 List(
1360 elts=[
1361 Name(id='x', ctx=Store())],
1362 ctx=Load()),
1363 Name(id='y', ctx=Store())]),
1364 body=[
1365 Expr(
1366 value=Constant(value=Ellipsis))])])],
1367 type_ignores=[])
1368
1369
Pablo Galindo114081f2020-03-02 03:14:06 +00001370Function and class definitions
1371^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1372
1373.. class:: FunctionDef(name, args, body, decorator_list, returns, type_comment)
1374
1375 A function definition.
1376
1377 * ``name`` is a raw string of the function name.
1378 * ``args`` is a :class:`arguments` node.
1379 * ``body`` is the list of nodes inside the function.
1380 * ``decorator_list`` is the list of decorators to be applied, stored outermost
1381 first (i.e. the first in the list will be applied last).
1382 * ``returns`` is the return annotation.
1383
1384 .. attribute:: type_comment
1385
1386 ``type_comment`` is an optional string with the type annotation as a comment.
1387
1388
1389.. class:: Lambda(args, body)
1390
1391 ``lambda`` is a minimal function definition that can be used inside an
1392 expression. Unlike :class:`FunctionDef`, ``body`` holds a single node.
1393
1394 .. doctest::
1395
Pablo Galindo02f64cb2020-03-07 18:22:58 +00001396 >>> print(ast.dump(ast.parse('lambda x,y: ...'), indent=4))
Pablo Galindo114081f2020-03-02 03:14:06 +00001397 Module(
1398 body=[
1399 Expr(
1400 value=Lambda(
1401 args=arguments(
1402 posonlyargs=[],
1403 args=[
Serhiy Storchakab7e95252020-03-10 00:07:47 +02001404 arg(arg='x'),
1405 arg(arg='y')],
Pablo Galindo114081f2020-03-02 03:14:06 +00001406 kwonlyargs=[],
1407 kw_defaults=[],
Pablo Galindo114081f2020-03-02 03:14:06 +00001408 defaults=[]),
Serhiy Storchakab7e95252020-03-10 00:07:47 +02001409 body=Constant(value=Ellipsis)))],
Pablo Galindo114081f2020-03-02 03:14:06 +00001410 type_ignores=[])
1411
1412
1413.. class:: arguments(posonlyargs, args, vararg, kwonlyargs, kw_defaults, kwarg, defaults)
1414
1415 The arguments for a function.
1416
1417 * ``posonlyargs``, ``args`` and ``kwonlyargs`` are lists of :class:`arg` nodes.
1418 * ``vararg`` and ``kwarg`` are single :class:`arg` nodes, referring to the
1419 ``*args, **kwargs`` parameters.
1420 * ``kw_defaults`` is a list of default values for keyword-only arguments. If
1421 one is ``None``, the corresponding argument is required.
1422 * ``defaults`` is a list of default values for arguments that can be passed
1423 positionally. If there are fewer defaults, they correspond to the last n
1424 arguments.
1425
1426
1427.. class:: arg(arg, annotation, type_comment)
1428
1429 A single argument in a list. ``arg`` is a raw string of the argument
1430 name, ``annotation`` is its annotation, such as a :class:`Str` or
1431 :class:`Name` node.
1432
1433 .. attribute:: type_comment
1434
1435 ``type_comment`` is an optional string with the type annotation as a comment
1436
1437 .. doctest::
1438
1439 >>> print(ast.dump(ast.parse("""\
1440 ... @decorator1
1441 ... @decorator2
1442 ... def f(a: 'annotation', b=1, c=2, *d, e, f=3, **g) -> 'return annotation':
1443 ... pass
1444 ... """), indent=4))
1445 Module(
1446 body=[
1447 FunctionDef(
1448 name='f',
1449 args=arguments(
1450 posonlyargs=[],
1451 args=[
1452 arg(
1453 arg='a',
Serhiy Storchakab7e95252020-03-10 00:07:47 +02001454 annotation=Constant(value='annotation')),
1455 arg(arg='b'),
1456 arg(arg='c')],
1457 vararg=arg(arg='d'),
Pablo Galindo114081f2020-03-02 03:14:06 +00001458 kwonlyargs=[
Serhiy Storchakab7e95252020-03-10 00:07:47 +02001459 arg(arg='e'),
1460 arg(arg='f')],
Pablo Galindo114081f2020-03-02 03:14:06 +00001461 kw_defaults=[
1462 None,
Serhiy Storchakab7e95252020-03-10 00:07:47 +02001463 Constant(value=3)],
1464 kwarg=arg(arg='g'),
Pablo Galindo114081f2020-03-02 03:14:06 +00001465 defaults=[
Serhiy Storchakab7e95252020-03-10 00:07:47 +02001466 Constant(value=1),
1467 Constant(value=2)]),
Pablo Galindo114081f2020-03-02 03:14:06 +00001468 body=[
1469 Pass()],
1470 decorator_list=[
1471 Name(id='decorator1', ctx=Load()),
1472 Name(id='decorator2', ctx=Load())],
Serhiy Storchakab7e95252020-03-10 00:07:47 +02001473 returns=Constant(value='return annotation'))],
Pablo Galindo114081f2020-03-02 03:14:06 +00001474 type_ignores=[])
1475
1476
1477.. class:: Return(value)
1478
1479 A ``return`` statement.
1480
1481 .. doctest::
1482
Pablo Galindo02f64cb2020-03-07 18:22:58 +00001483 >>> print(ast.dump(ast.parse('return 4'), indent=4))
Pablo Galindo114081f2020-03-02 03:14:06 +00001484 Module(
1485 body=[
1486 Return(
Serhiy Storchakab7e95252020-03-10 00:07:47 +02001487 value=Constant(value=4))],
Pablo Galindo114081f2020-03-02 03:14:06 +00001488 type_ignores=[])
1489
1490
1491.. class:: Yield(value)
1492 YieldFrom(value)
1493
1494 A ``yield`` or ``yield from`` expression. Because these are expressions, they
1495 must be wrapped in a :class:`Expr` node if the value sent back is not used.
1496
1497 .. doctest::
1498
Pablo Galindo02f64cb2020-03-07 18:22:58 +00001499 >>> print(ast.dump(ast.parse('yield x'), indent=4))
Pablo Galindo114081f2020-03-02 03:14:06 +00001500 Module(
1501 body=[
1502 Expr(
1503 value=Yield(
1504 value=Name(id='x', ctx=Load())))],
1505 type_ignores=[])
1506
Pablo Galindo02f64cb2020-03-07 18:22:58 +00001507 >>> print(ast.dump(ast.parse('yield from x'), indent=4))
Pablo Galindo114081f2020-03-02 03:14:06 +00001508 Module(
1509 body=[
1510 Expr(
1511 value=YieldFrom(
1512 value=Name(id='x', ctx=Load())))],
1513 type_ignores=[])
1514
1515
1516.. class:: Global(names)
1517 Nonlocal(names)
1518
1519 ``global`` and ``nonlocal`` statements. ``names`` is a list of raw strings.
1520
1521 .. doctest::
1522
Pablo Galindo02f64cb2020-03-07 18:22:58 +00001523 >>> print(ast.dump(ast.parse('global x,y,z'), indent=4))
Pablo Galindo114081f2020-03-02 03:14:06 +00001524 Module(
1525 body=[
1526 Global(
1527 names=[
1528 'x',
1529 'y',
1530 'z'])],
1531 type_ignores=[])
1532
Pablo Galindo02f64cb2020-03-07 18:22:58 +00001533 >>> print(ast.dump(ast.parse('nonlocal x,y,z'), indent=4))
Pablo Galindo114081f2020-03-02 03:14:06 +00001534 Module(
1535 body=[
1536 Nonlocal(
1537 names=[
1538 'x',
1539 'y',
1540 'z'])],
1541 type_ignores=[])
1542
1543
1544.. class:: ClassDef(name, bases, keywords, starargs, kwargs, body, decorator_list)
1545
1546 A class definition.
1547
1548 * ``name`` is a raw string for the class name
1549 * ``bases`` is a list of nodes for explicitly specified base classes.
1550 * ``keywords`` is a list of :class:`keyword` nodes, principally for 'metaclass'.
1551 Other keywords will be passed to the metaclass, as per `PEP-3115
1552 <http://www.python.org/dev/peps/pep-3115/>`_.
1553 * ``starargs`` and ``kwargs`` are each a single node, as in a function call.
1554 starargs will be expanded to join the list of base classes, and kwargs will
1555 be passed to the metaclass.
1556 * ``body`` is a list of nodes representing the code within the class
1557 definition.
1558 * ``decorator_list`` is a list of nodes, as in :class:`FunctionDef`.
1559
1560 .. doctest::
1561
1562 >>> print(ast.dump(ast.parse("""\
1563 ... @decorator1
1564 ... @decorator2
1565 ... class Foo(base1, base2, metaclass=meta):
1566 ... pass
1567 ... """), indent=4))
1568 Module(
1569 body=[
1570 ClassDef(
1571 name='Foo',
1572 bases=[
1573 Name(id='base1', ctx=Load()),
1574 Name(id='base2', ctx=Load())],
1575 keywords=[
1576 keyword(
1577 arg='metaclass',
1578 value=Name(id='meta', ctx=Load()))],
1579 body=[
1580 Pass()],
1581 decorator_list=[
1582 Name(id='decorator1', ctx=Load()),
1583 Name(id='decorator2', ctx=Load())])],
1584 type_ignores=[])
1585
1586Async and await
1587^^^^^^^^^^^^^^^
1588
1589.. class:: AsyncFunctionDef(name, args, body, decorator_list, returns, type_comment)
1590
1591 An ``async def`` function definition. Has the same fields as
1592 :class:`FunctionDef`.
1593
1594
1595.. class:: Await(value)
1596
1597 An ``await`` expression. ``value`` is what it waits for.
1598 Only valid in the body of an :class:`AsyncFunctionDef`.
1599
1600.. doctest::
1601
1602 >>> print(ast.dump(ast.parse("""\
1603 ... async def f():
1604 ... await other_func()
1605 ... """), indent=4))
1606 Module(
1607 body=[
1608 AsyncFunctionDef(
1609 name='f',
1610 args=arguments(
1611 posonlyargs=[],
1612 args=[],
Pablo Galindo114081f2020-03-02 03:14:06 +00001613 kwonlyargs=[],
1614 kw_defaults=[],
Pablo Galindo114081f2020-03-02 03:14:06 +00001615 defaults=[]),
1616 body=[
1617 Expr(
1618 value=Await(
1619 value=Call(
1620 func=Name(id='other_func', ctx=Load()),
1621 args=[],
1622 keywords=[])))],
Serhiy Storchakab7e95252020-03-10 00:07:47 +02001623 decorator_list=[])],
Pablo Galindo114081f2020-03-02 03:14:06 +00001624 type_ignores=[])
1625
1626
1627.. class:: AsyncFor(target, iter, body, orelse, type_comment)
1628 AsyncWith(items, body, type_comment)
1629
1630 ``async for`` loops and ``async with`` context managers. They have the same
1631 fields as :class:`For` and :class:`With`, respectively. Only valid in the
1632 body of an :class:`AsyncFunctionDef`.
Georg Brandl0c77a822008-06-10 16:37:50 +00001633
Batuhan Taskayab37c9942020-10-22 19:02:43 +03001634.. note::
1635 When a string is parsed by :func:`ast.parse`, operator nodes (subclasses
1636 of :class:`ast.operator`, :class:`ast.unaryop`, :class:`ast.cmpop`,
1637 :class:`ast.boolop` and :class:`ast.expr_context`) on the returned tree
1638 will be singletons. Changes to one will be reflected in all other
1639 occurrences of the same value (e.g. :class:`ast.Add`).
1640
Georg Brandl0c77a822008-06-10 16:37:50 +00001641
1642:mod:`ast` Helpers
1643------------------
1644
Martin Panter2e4571a2015-11-14 01:07:43 +00001645Apart from the node classes, the :mod:`ast` module defines these utility functions
Georg Brandl0c77a822008-06-10 16:37:50 +00001646and classes for traversing abstract syntax trees:
1647
Guido van Rossum10b55c12019-06-11 17:23:12 -07001648.. function:: parse(source, filename='<unknown>', mode='exec', *, type_comments=False, feature_version=None)
Georg Brandl0c77a822008-06-10 16:37:50 +00001649
Terry Reedyfeac6242011-01-24 21:36:03 +00001650 Parse the source into an AST node. Equivalent to ``compile(source,
Benjamin Petersonec9199b2008-11-08 17:05:00 +00001651 filename, mode, ast.PyCF_ONLY_AST)``.
Georg Brandl0c77a822008-06-10 16:37:50 +00001652
Guido van Rossumdcfcd142019-01-31 03:40:27 -08001653 If ``type_comments=True`` is given, the parser is modified to check
1654 and return type comments as specified by :pep:`484` and :pep:`526`.
1655 This is equivalent to adding :data:`ast.PyCF_TYPE_COMMENTS` to the
1656 flags passed to :func:`compile()`. This will report syntax errors
1657 for misplaced type comments. Without this flag, type comments will
1658 be ignored, and the ``type_comment`` field on selected AST nodes
1659 will always be ``None``. In addition, the locations of ``# type:
1660 ignore`` comments will be returned as the ``type_ignores``
1661 attribute of :class:`Module` (otherwise it is always an empty list).
1662
1663 In addition, if ``mode`` is ``'func_type'``, the input syntax is
1664 modified to correspond to :pep:`484` "signature type comments",
1665 e.g. ``(str, int) -> List[str]``.
1666
Guido van Rossum10b55c12019-06-11 17:23:12 -07001667 Also, setting ``feature_version`` to a tuple ``(major, minor)``
1668 will attempt to parse using that Python version's grammar.
1669 Currently ``major`` must equal to ``3``. For example, setting
1670 ``feature_version=(3, 4)`` will allow the use of ``async`` and
1671 ``await`` as variable names. The lowest supported version is
1672 ``(3, 4)``; the highest is ``sys.version_info[0:2]``.
Guido van Rossum495da292019-03-07 12:38:08 -08001673
Brett Cannon7a7f1002018-03-09 12:03:22 -08001674 .. warning::
1675 It is possible to crash the Python interpreter with a
1676 sufficiently large/complex string due to stack depth limitations
1677 in Python's AST compiler.
1678
Guido van Rossumdcfcd142019-01-31 03:40:27 -08001679 .. versionchanged:: 3.8
Guido van Rossum495da292019-03-07 12:38:08 -08001680 Added ``type_comments``, ``mode='func_type'`` and ``feature_version``.
Guido van Rossumdcfcd142019-01-31 03:40:27 -08001681
Georg Brandl48310cd2009-01-03 21:18:54 +00001682
Pablo Galindo27fc3b62019-11-24 23:02:40 +00001683.. function:: unparse(ast_obj)
1684
1685 Unparse an :class:`ast.AST` object and generate a string with code
1686 that would produce an equivalent :class:`ast.AST` object if parsed
1687 back with :func:`ast.parse`.
1688
1689 .. warning::
Gurupad Hegde6c7bb382019-12-28 17:16:02 -05001690 The produced code string will not necessarily be equal to the original
Batuhan Taskaya8df10162020-06-28 04:11:43 +03001691 code that generated the :class:`ast.AST` object (without any compiler
1692 optimizations, such as constant tuples/frozensets).
1693
1694 .. warning::
1695 Trying to unparse a highly complex expression would result with
1696 :exc:`RecursionError`.
Pablo Galindo27fc3b62019-11-24 23:02:40 +00001697
1698 .. versionadded:: 3.9
1699
1700
Georg Brandl0c77a822008-06-10 16:37:50 +00001701.. function:: literal_eval(node_or_string)
1702
Georg Brandlb9b389e2014-11-05 20:20:28 +01001703 Safely evaluate an expression node or a string containing a Python literal or
1704 container display. The string or node provided may only consist of the
1705 following Python literal structures: strings, bytes, numbers, tuples, lists,
Batuhan Taskayafbc77232020-12-22 03:15:40 +03001706 dicts, sets, booleans, ``None`` and ``Ellipsis``.
Georg Brandl0c77a822008-06-10 16:37:50 +00001707
Georg Brandlb9b389e2014-11-05 20:20:28 +01001708 This can be used for safely evaluating strings containing Python values from
1709 untrusted sources without the need to parse the values oneself. It is not
1710 capable of evaluating arbitrarily complex expressions, for example involving
1711 operators or indexing.
Georg Brandl0c77a822008-06-10 16:37:50 +00001712
Brett Cannon7a7f1002018-03-09 12:03:22 -08001713 .. warning::
1714 It is possible to crash the Python interpreter with a
1715 sufficiently large/complex string due to stack depth limitations
1716 in Python's AST compiler.
1717
Batuhan Taskayafbc77232020-12-22 03:15:40 +03001718 It can raise :exc:`ValueError`, :exc:`TypeError`, :exc:`SyntaxError`,
1719 :exc:`MemoryError` and :exc:`RecursionError` depending on the malformed
1720 input.
1721
Georg Brandl492f3fc2010-07-11 09:41:21 +00001722 .. versionchanged:: 3.2
Georg Brandl85f21772010-07-13 06:38:10 +00001723 Now allows bytes and set literals.
Georg Brandl492f3fc2010-07-11 09:41:21 +00001724
Raymond Hettinger4fcf5c12020-01-02 22:21:18 -07001725 .. versionchanged:: 3.9
1726 Now supports creating empty sets with ``'set()'``.
1727
Batuhan Taskayae799aa82020-10-04 03:46:44 +03001728 .. versionchanged:: 3.10
1729 For string inputs, leading spaces and tabs are now stripped.
1730
Georg Brandl0c77a822008-06-10 16:37:50 +00001731
Amaury Forgeot d'Arcfdfe62d2008-06-17 20:36:03 +00001732.. function:: get_docstring(node, clean=True)
Georg Brandl0c77a822008-06-10 16:37:50 +00001733
1734 Return the docstring of the given *node* (which must be a
INADA Naokicb41b272017-02-23 00:31:59 +09001735 :class:`FunctionDef`, :class:`AsyncFunctionDef`, :class:`ClassDef`,
1736 or :class:`Module` node), or ``None`` if it has no docstring.
1737 If *clean* is true, clean up the docstring's indentation with
1738 :func:`inspect.cleandoc`.
1739
1740 .. versionchanged:: 3.5
1741 :class:`AsyncFunctionDef` is now supported.
1742
Georg Brandl0c77a822008-06-10 16:37:50 +00001743
Ivan Levkivskyi9932a222019-01-22 11:18:22 +00001744.. function:: get_source_segment(source, node, *, padded=False)
1745
1746 Get source code segment of the *source* that generated *node*.
1747 If some location information (:attr:`lineno`, :attr:`end_lineno`,
1748 :attr:`col_offset`, or :attr:`end_col_offset`) is missing, return ``None``.
1749
1750 If *padded* is ``True``, the first line of a multi-line statement will
1751 be padded with spaces to match its original position.
1752
1753 .. versionadded:: 3.8
1754
1755
Georg Brandl0c77a822008-06-10 16:37:50 +00001756.. function:: fix_missing_locations(node)
1757
1758 When you compile a node tree with :func:`compile`, the compiler expects
1759 :attr:`lineno` and :attr:`col_offset` attributes for every node that supports
1760 them. This is rather tedious to fill in for generated nodes, so this helper
1761 adds these attributes recursively where not already set, by setting them to
1762 the values of the parent node. It works recursively starting at *node*.
1763
1764
1765.. function:: increment_lineno(node, n=1)
1766
Ivan Levkivskyi9932a222019-01-22 11:18:22 +00001767 Increment the line number and end line number of each node in the tree
1768 starting at *node* by *n*. This is useful to "move code" to a different
1769 location in a file.
Georg Brandl0c77a822008-06-10 16:37:50 +00001770
1771
1772.. function:: copy_location(new_node, old_node)
1773
Ivan Levkivskyi9932a222019-01-22 11:18:22 +00001774 Copy source location (:attr:`lineno`, :attr:`col_offset`, :attr:`end_lineno`,
1775 and :attr:`end_col_offset`) from *old_node* to *new_node* if possible,
1776 and return *new_node*.
Georg Brandl0c77a822008-06-10 16:37:50 +00001777
1778
1779.. function:: iter_fields(node)
1780
1781 Yield a tuple of ``(fieldname, value)`` for each field in ``node._fields``
1782 that is present on *node*.
1783
1784
1785.. function:: iter_child_nodes(node)
1786
1787 Yield all direct child nodes of *node*, that is, all fields that are nodes
1788 and all items of fields that are lists of nodes.
1789
1790
1791.. function:: walk(node)
1792
Georg Brandl619e7ba2011-01-09 07:38:51 +00001793 Recursively yield all descendant nodes in the tree starting at *node*
1794 (including *node* itself), in no specified order. This is useful if you only
1795 want to modify nodes in place and don't care about the context.
Georg Brandl0c77a822008-06-10 16:37:50 +00001796
1797
1798.. class:: NodeVisitor()
1799
1800 A node visitor base class that walks the abstract syntax tree and calls a
1801 visitor function for every node found. This function may return a value
Georg Brandl36ab1ef2009-01-03 21:17:04 +00001802 which is forwarded by the :meth:`visit` method.
Georg Brandl0c77a822008-06-10 16:37:50 +00001803
1804 This class is meant to be subclassed, with the subclass adding visitor
1805 methods.
1806
1807 .. method:: visit(node)
1808
1809 Visit a node. The default implementation calls the method called
1810 :samp:`self.visit_{classname}` where *classname* is the name of the node
1811 class, or :meth:`generic_visit` if that method doesn't exist.
1812
1813 .. method:: generic_visit(node)
1814
1815 This visitor calls :meth:`visit` on all children of the node.
Georg Brandl48310cd2009-01-03 21:18:54 +00001816
Georg Brandl0c77a822008-06-10 16:37:50 +00001817 Note that child nodes of nodes that have a custom visitor method won't be
1818 visited unless the visitor calls :meth:`generic_visit` or visits them
1819 itself.
1820
1821 Don't use the :class:`NodeVisitor` if you want to apply changes to nodes
1822 during traversal. For this a special visitor exists
1823 (:class:`NodeTransformer`) that allows modifications.
1824
Serhiy Storchakac3ea41e2019-08-26 10:13:19 +03001825 .. deprecated:: 3.8
1826
1827 Methods :meth:`visit_Num`, :meth:`visit_Str`, :meth:`visit_Bytes`,
1828 :meth:`visit_NameConstant` and :meth:`visit_Ellipsis` are deprecated
1829 now and will not be called in future Python versions. Add the
1830 :meth:`visit_Constant` method to handle all constant nodes.
1831
Georg Brandl0c77a822008-06-10 16:37:50 +00001832
1833.. class:: NodeTransformer()
1834
1835 A :class:`NodeVisitor` subclass that walks the abstract syntax tree and
1836 allows modification of nodes.
1837
Georg Brandl36ab1ef2009-01-03 21:17:04 +00001838 The :class:`NodeTransformer` will walk the AST and use the return value of
1839 the visitor methods to replace or remove the old node. If the return value
1840 of the visitor method is ``None``, the node will be removed from its
1841 location, otherwise it is replaced with the return value. The return value
1842 may be the original node in which case no replacement takes place.
Georg Brandl0c77a822008-06-10 16:37:50 +00001843
1844 Here is an example transformer that rewrites all occurrences of name lookups
1845 (``foo``) to ``data['foo']``::
1846
1847 class RewriteName(NodeTransformer):
1848
1849 def visit_Name(self, node):
Batuhan Taşkaya6680f4a2020-01-12 23:38:53 +03001850 return Subscript(
Georg Brandl0c77a822008-06-10 16:37:50 +00001851 value=Name(id='data', ctx=Load()),
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02001852 slice=Constant(value=node.id),
Georg Brandl0c77a822008-06-10 16:37:50 +00001853 ctx=node.ctx
Pablo Galindoc00c86b2020-03-12 00:48:19 +00001854 )
Georg Brandl0c77a822008-06-10 16:37:50 +00001855
1856 Keep in mind that if the node you're operating on has child nodes you must
1857 either transform the child nodes yourself or call the :meth:`generic_visit`
1858 method for the node first.
1859
1860 For nodes that were part of a collection of statements (that applies to all
1861 statement nodes), the visitor may also return a list of nodes rather than
1862 just a single node.
1863
Batuhan Taşkaya6680f4a2020-01-12 23:38:53 +03001864 If :class:`NodeTransformer` introduces new nodes (that weren't part of
1865 original tree) without giving them location information (such as
1866 :attr:`lineno`), :func:`fix_missing_locations` should be called with
1867 the new sub-tree to recalculate the location information::
1868
1869 tree = ast.parse('foo', mode='eval')
1870 new_tree = fix_missing_locations(RewriteName().visit(tree))
1871
Georg Brandl0c77a822008-06-10 16:37:50 +00001872 Usually you use the transformer like this::
1873
1874 node = YourTransformer().visit(node)
1875
1876
Serhiy Storchaka850573b2019-09-09 19:33:13 +03001877.. function:: dump(node, annotate_fields=True, include_attributes=False, *, indent=None)
Georg Brandl0c77a822008-06-10 16:37:50 +00001878
1879 Return a formatted dump of the tree in *node*. This is mainly useful for
Serhiy Storchakae64f9482019-08-29 09:30:23 +03001880 debugging purposes. If *annotate_fields* is true (by default),
1881 the returned string will show the names and the values for fields.
1882 If *annotate_fields* is false, the result string will be more compact by
1883 omitting unambiguous field names. Attributes such as line
Benjamin Petersondcf97b92008-07-02 17:30:14 +00001884 numbers and column offsets are not dumped by default. If this is wanted,
Serhiy Storchakae64f9482019-08-29 09:30:23 +03001885 *include_attributes* can be set to true.
Senthil Kumaranf3695bf2016-01-06 21:26:53 -08001886
Serhiy Storchaka850573b2019-09-09 19:33:13 +03001887 If *indent* is a non-negative integer or string, then the tree will be
1888 pretty-printed with that indent level. An indent level
1889 of 0, negative, or ``""`` will only insert newlines. ``None`` (the default)
1890 selects the single line representation. Using a positive integer indent
1891 indents that many spaces per level. If *indent* is a string (such as ``"\t"``),
1892 that string is used to indent each level.
1893
1894 .. versionchanged:: 3.9
1895 Added the *indent* option.
1896
1897
Batuhan Taskaya15593892020-10-19 04:14:11 +03001898.. _ast-compiler-flags:
1899
1900Compiler Flags
1901--------------
1902
1903The following flags may be passed to :func:`compile` in order to change
1904effects on the compilation of a program:
1905
1906.. data:: PyCF_ALLOW_TOP_LEVEL_AWAIT
1907
1908 Enables support for top-level ``await``, ``async for``, ``async with``
1909 and async comprehensions.
1910
1911 .. versionadded:: 3.8
1912
1913.. data:: PyCF_ONLY_AST
1914
1915 Generates and returns an abstract syntax tree instead of returning a
1916 compiled code object.
1917
1918.. data:: PyCF_TYPE_COMMENTS
1919
1920 Enables support for :pep:`484` and :pep:`526` style type comments
1921 (``# type: <type>``, ``# type: ignore <stuff>``).
1922
1923 .. versionadded:: 3.8
1924
1925
Serhiy Storchaka832e8642019-09-09 23:36:13 +03001926.. _ast-cli:
1927
1928Command-Line Usage
1929------------------
1930
1931.. versionadded:: 3.9
1932
1933The :mod:`ast` module can be executed as a script from the command line.
1934It is as simple as:
1935
1936.. code-block:: sh
1937
1938 python -m ast [-m <mode>] [-a] [infile]
1939
1940The following options are accepted:
1941
1942.. program:: ast
1943
1944.. cmdoption:: -h, --help
1945
1946 Show the help message and exit.
1947
1948.. cmdoption:: -m <mode>
1949 --mode <mode>
1950
1951 Specify what kind of code must be compiled, like the *mode* argument
1952 in :func:`parse`.
1953
Batuhan Taşkaya814d6872019-12-16 21:23:27 +03001954.. cmdoption:: --no-type-comments
1955
1956 Don't parse type comments.
1957
Serhiy Storchaka832e8642019-09-09 23:36:13 +03001958.. cmdoption:: -a, --include-attributes
1959
1960 Include attributes such as line numbers and column offsets.
1961
Batuhan Taşkaya814d6872019-12-16 21:23:27 +03001962.. cmdoption:: -i <indent>
1963 --indent <indent>
1964
1965 Indentation of nodes in AST (number of spaces).
1966
Serhiy Storchaka832e8642019-09-09 23:36:13 +03001967If :file:`infile` is specified its contents are parsed to AST and dumped
1968to stdout. Otherwise, the content is read from stdin.
1969
1970
Senthil Kumaranf3695bf2016-01-06 21:26:53 -08001971.. seealso::
1972
Edward K. Reame3c971c2020-08-11 09:07:49 -05001973 `Green Tree Snakes <https://greentreesnakes.readthedocs.io/>`_, an external
1974 documentation resource, has good details on working with Python ASTs.
1975
1976 `ASTTokens <https://asttokens.readthedocs.io/en/latest/user-guide.html>`_
1977 annotates Python ASTs with the positions of tokens and text in the source
1978 code that generated them. This is helpful for tools that make source code
1979 transformations.
1980
1981 `leoAst.py <http://leoeditor.com/appendices.html#leoast-py>`_ unifies the
1982 token-based and parse-tree-based views of python programs by inserting
1983 two-way links between tokens and ast nodes.
1984
1985 `LibCST <https://libcst.readthedocs.io/>`_ parses code as a Concrete Syntax
1986 Tree that looks like an ast tree and keeps all formatting details. It's
1987 useful for building automated refactoring (codemod) applications and
1988 linters.
1989
1990 `Parso <https://parso.readthedocs.io>`_ is a Python parser that supports
1991 error recovery and round-trip parsing for different Python versions (in
1992 multiple Python versions). Parso is also able to list multiple syntax errors
Batuhan Taskayae799aa82020-10-04 03:46:44 +03001993 in your python file.