blob: 25cb17811e7183e9df680f6fd2b88090ce601fcf [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
Ivan Levkivskyi9932a222019-01-22 11:18:22 +000083 :attr:`lineno`, :attr:`col_offset`, :attr:`lineno`, and :attr:`col_offset`
84 attributes. The :attr:`lineno` and :attr:`end_lineno` are the first and
85 last line numbers of source text span (1-indexed so the first line is line 1)
86 and the :attr:`col_offset` and :attr:`end_col_offset` are the corresponding
87 UTF-8 byte offsets of the first and last tokens that generated the node.
88 The UTF-8 offset is recorded because the parser uses UTF-8 internally.
89
90 Note that the end positions are not required by the compiler and are
91 therefore optional. The end offset is *after* the last symbol, for example
92 one can get the source segment of a one-line expression node using
93 ``source_line[node.col_offset : node.end_col_offset]``.
Georg Brandl0c77a822008-06-10 16:37:50 +000094
95 The constructor of a class :class:`ast.T` parses its arguments as follows:
96
97 * If there are positional arguments, there must be as many as there are items
98 in :attr:`T._fields`; they will be assigned as attributes of these names.
99 * If there are keyword arguments, they will set the attributes of the same
100 names to the given values.
101
102 For example, to create and populate an :class:`ast.UnaryOp` node, you could
103 use ::
104
105 node = ast.UnaryOp()
106 node.op = ast.USub()
Serhiy Storchaka3f228112018-09-27 17:42:37 +0300107 node.operand = ast.Constant()
108 node.operand.value = 5
Georg Brandl0c77a822008-06-10 16:37:50 +0000109 node.operand.lineno = 0
110 node.operand.col_offset = 0
111 node.lineno = 0
112 node.col_offset = 0
113
114 or the more compact ::
115
Serhiy Storchaka3f228112018-09-27 17:42:37 +0300116 node = ast.UnaryOp(ast.USub(), ast.Constant(5, lineno=0, col_offset=0),
Georg Brandl0c77a822008-06-10 16:37:50 +0000117 lineno=0, col_offset=0)
118
Serhiy Storchaka85a2eef2020-02-17 11:03:00 +0200119.. versionchanged:: 3.8
120
121 Class :class:`ast.Constant` is now used for all constants.
122
Serhiy Storchaka13d52c22020-03-10 18:52:34 +0200123.. versionchanged:: 3.9
124
125 Simple indices are represented by their value, extended slices are
126 represented as tuples.
127
Serhiy Storchaka3f228112018-09-27 17:42:37 +0300128.. deprecated:: 3.8
129
Serhiy Storchaka85a2eef2020-02-17 11:03:00 +0200130 Old classes :class:`ast.Num`, :class:`ast.Str`, :class:`ast.Bytes`,
Serhiy Storchaka3f228112018-09-27 17:42:37 +0300131 :class:`ast.NameConstant` and :class:`ast.Ellipsis` are still available,
Serhiy Storchaka13d52c22020-03-10 18:52:34 +0200132 but they will be removed in future Python releases. In the meantime,
Serhiy Storchaka85a2eef2020-02-17 11:03:00 +0200133 instantiating them will return an instance of a different class.
Serhiy Storchaka3f228112018-09-27 17:42:37 +0300134
Serhiy Storchaka13d52c22020-03-10 18:52:34 +0200135.. deprecated:: 3.9
136
137 Old classes :class:`ast.Index` and :class:`ast.ExtSlice` are still
138 available, but they will be removed in future Python releases.
139 In the meantime, instantiating them will return an instance of
140 a different class.
141
142
Pablo Galindo114081f2020-03-02 03:14:06 +0000143Literals
144^^^^^^^^
Georg Brandl0c77a822008-06-10 16:37:50 +0000145
Pablo Galindo114081f2020-03-02 03:14:06 +0000146.. class:: Constant(value)
Georg Brandl0c77a822008-06-10 16:37:50 +0000147
Pablo Galindo114081f2020-03-02 03:14:06 +0000148 A constant value. The ``value`` attribute of the ``Constant`` literal contains the
149 Python object it represents. The values represented can be simple types
150 such as a number, string or ``None``, but also immutable container types
151 (tuples and frozensets) if all of their elements are constant.
Georg Brandl0c77a822008-06-10 16:37:50 +0000152
Pablo Galindo114081f2020-03-02 03:14:06 +0000153 .. doctest::
Georg Brandl0c77a822008-06-10 16:37:50 +0000154
Pablo Galindo02f64cb2020-03-07 18:22:58 +0000155 >>> print(ast.dump(ast.parse('123', mode='eval'), indent=4))
156 Expression(
Serhiy Storchakab7e95252020-03-10 00:07:47 +0200157 body=Constant(value=123))
Pablo Galindo114081f2020-03-02 03:14:06 +0000158
159
160.. class:: FormattedValue(value, conversion, format_spec)
161
162 Node representing a single formatting field in an f-string. If the string
163 contains a single formatting field and nothing else the node can be
164 isolated otherwise it appears in :class:`JoinedStr`.
165
166 * ``value`` is any expression node (such as a literal, a variable, or a
167 function call).
168 * ``conversion`` is an integer:
169
170 * -1: no formatting
171 * 115: ``!s`` string formatting
172 * 114: ``!r`` repr formatting
173 * 97: ``!a`` ascii formatting
174
175 * ``format_spec`` is a :class:`JoinedStr` node representing the formatting
176 of the value, or ``None`` if no format was specified. Both
177 ``conversion`` and ``format_spec`` can be set at the same time.
178
179
180.. class:: JoinedStr(values)
181
182 An f-string, comprising a series of :class:`FormattedValue` and :class:`Constant`
183 nodes.
184
185 .. doctest::
186
Pablo Galindo02f64cb2020-03-07 18:22:58 +0000187 >>> print(ast.dump(ast.parse('f"sin({a}) is {sin(a):.3}"', mode='eval'), indent=4))
188 Expression(
189 body=JoinedStr(
190 values=[
Serhiy Storchakab7e95252020-03-10 00:07:47 +0200191 Constant(value='sin('),
Pablo Galindo02f64cb2020-03-07 18:22:58 +0000192 FormattedValue(
193 value=Name(id='a', ctx=Load()),
Serhiy Storchakab7e95252020-03-10 00:07:47 +0200194 conversion=-1),
195 Constant(value=') is '),
Pablo Galindo02f64cb2020-03-07 18:22:58 +0000196 FormattedValue(
197 value=Call(
198 func=Name(id='sin', ctx=Load()),
199 args=[
200 Name(id='a', ctx=Load())],
201 keywords=[]),
202 conversion=-1,
203 format_spec=JoinedStr(
204 values=[
Serhiy Storchakab7e95252020-03-10 00:07:47 +0200205 Constant(value='.3')]))]))
Pablo Galindo114081f2020-03-02 03:14:06 +0000206
207
208.. class:: List(elts, ctx)
209 Tuple(elts, ctx)
210
211 A list or tuple. ``elts`` holds a list of nodes representing the elements.
212 ``ctx`` is :class:`Store` if the container is an assignment target (i.e.
213 ``(x,y)=something``), and :class:`Load` otherwise.
214
215 .. doctest::
216
Pablo Galindo02f64cb2020-03-07 18:22:58 +0000217 >>> print(ast.dump(ast.parse('[1, 2, 3]', mode='eval'), indent=4))
218 Expression(
219 body=List(
220 elts=[
Serhiy Storchakab7e95252020-03-10 00:07:47 +0200221 Constant(value=1),
222 Constant(value=2),
223 Constant(value=3)],
Pablo Galindo02f64cb2020-03-07 18:22:58 +0000224 ctx=Load()))
225 >>> print(ast.dump(ast.parse('(1, 2, 3)', mode='eval'), indent=4))
226 Expression(
227 body=Tuple(
228 elts=[
Serhiy Storchakab7e95252020-03-10 00:07:47 +0200229 Constant(value=1),
230 Constant(value=2),
231 Constant(value=3)],
Pablo Galindo02f64cb2020-03-07 18:22:58 +0000232 ctx=Load()))
Pablo Galindo114081f2020-03-02 03:14:06 +0000233
234
235.. class:: Set(elts)
236
237 A set. ``elts`` holds a list of nodes representing the set's elements.
238
239 .. doctest::
240
Pablo Galindo02f64cb2020-03-07 18:22:58 +0000241 >>> print(ast.dump(ast.parse('{1, 2, 3}', mode='eval'), indent=4))
242 Expression(
243 body=Set(
244 elts=[
Serhiy Storchakab7e95252020-03-10 00:07:47 +0200245 Constant(value=1),
246 Constant(value=2),
247 Constant(value=3)]))
Pablo Galindo114081f2020-03-02 03:14:06 +0000248
249
250.. class:: Dict(keys, values)
251
252 A dictionary. ``keys`` and ``values`` hold lists of nodes representing the
253 keys and the values respectively, in matching order (what would be returned
254 when calling :code:`dictionary.keys()` and :code:`dictionary.values()`).
255
256 When doing dictionary unpacking using dictionary literals the expression to be
257 expanded goes in the ``values`` list, with a ``None`` at the corresponding
258 position in ``keys``.
259
260 .. doctest::
261
Pablo Galindo02f64cb2020-03-07 18:22:58 +0000262 >>> print(ast.dump(ast.parse('{"a":1, **d}', mode='eval'), indent=4))
263 Expression(
264 body=Dict(
265 keys=[
Serhiy Storchakab7e95252020-03-10 00:07:47 +0200266 Constant(value='a'),
Pablo Galindo02f64cb2020-03-07 18:22:58 +0000267 None],
268 values=[
Serhiy Storchakab7e95252020-03-10 00:07:47 +0200269 Constant(value=1),
Pablo Galindo02f64cb2020-03-07 18:22:58 +0000270 Name(id='d', ctx=Load())]))
Pablo Galindo114081f2020-03-02 03:14:06 +0000271
272
273Variables
274^^^^^^^^^
275
276.. class:: Name(id, ctx)
277
278 A variable name. ``id`` holds the name as a string, and ``ctx`` is one of
279 the following types.
280
281
282.. class:: Load()
283 Store()
284 Del()
285
286 Variable references can be used to load the value of a variable, to assign
287 a new value to it, or to delete it. Variable references are given a context
288 to distinguish these cases.
289
290 .. doctest::
291
292 >>> print(ast.dump(ast.parse('a'), indent=4))
293 Module(
294 body=[
295 Expr(
296 value=Name(id='a', ctx=Load()))],
297 type_ignores=[])
298
299 >>> print(ast.dump(ast.parse('a = 1'), indent=4))
300 Module(
301 body=[
302 Assign(
303 targets=[
304 Name(id='a', ctx=Store())],
Serhiy Storchakab7e95252020-03-10 00:07:47 +0200305 value=Constant(value=1))],
Pablo Galindo114081f2020-03-02 03:14:06 +0000306 type_ignores=[])
307
308 >>> print(ast.dump(ast.parse('del a'), indent=4))
309 Module(
310 body=[
311 Delete(
312 targets=[
313 Name(id='a', ctx=Del())])],
314 type_ignores=[])
315
316
317.. class:: Starred(value, ctx)
318
319 A ``*var`` variable reference. ``value`` holds the variable, typically a
320 :class:`Name` node. This type must be used when building a :class:`Call`
321 node with ``*args``.
322
323 .. doctest::
324
325 >>> print(ast.dump(ast.parse('a, *b = it'), indent=4))
326 Module(
327 body=[
328 Assign(
329 targets=[
330 Tuple(
331 elts=[
332 Name(id='a', ctx=Store()),
333 Starred(
334 value=Name(id='b', ctx=Store()),
335 ctx=Store())],
336 ctx=Store())],
Serhiy Storchakab7e95252020-03-10 00:07:47 +0200337 value=Name(id='it', ctx=Load()))],
Pablo Galindo114081f2020-03-02 03:14:06 +0000338 type_ignores=[])
339
340
341Expressions
342^^^^^^^^^^^
343
344.. class:: Expr(value)
345
346 When an expression, such as a function call, appears as a statement by itself
347 with its return value not used or stored, it is wrapped in this container.
348 ``value`` holds one of the other nodes in this section, a :class:`Constant`, a
349 :class:`Name`, a :class:`Lambda`, a :class:`Yield` or :class:`YieldFrom` node.
350
351 .. doctest::
352
353 >>> print(ast.dump(ast.parse('-a'), indent=4))
354 Module(
355 body=[
356 Expr(
357 value=UnaryOp(
358 op=USub(),
359 operand=Name(id='a', ctx=Load())))],
360 type_ignores=[])
361
362
363.. class:: UnaryOp(op, operand)
364
365 A unary operation. ``op`` is the operator, and ``operand`` any expression
366 node.
367
368
369.. class:: UAdd
370 USub
371 Not
372 Invert
373
374 Unary operator tokens. :class:`Not` is the ``not`` keyword, :class:`Invert`
375 is the ``~`` operator.
376
377 .. doctest::
378
Pablo Galindo02f64cb2020-03-07 18:22:58 +0000379 >>> print(ast.dump(ast.parse('not x', mode='eval'), indent=4))
380 Expression(
381 body=UnaryOp(
382 op=Not(),
383 operand=Name(id='x', ctx=Load())))
Pablo Galindo114081f2020-03-02 03:14:06 +0000384
385
386.. class:: BinOp(left, op, right)
387
388 A binary operation (like addition or division). ``op`` is the operator, and
389 ``left`` and ``right`` are any expression nodes.
390
391 .. doctest::
392
Pablo Galindo02f64cb2020-03-07 18:22:58 +0000393 >>> print(ast.dump(ast.parse('x + y', mode='eval'), indent=4))
394 Expression(
395 body=BinOp(
396 left=Name(id='x', ctx=Load()),
397 op=Add(),
398 right=Name(id='y', ctx=Load())))
Pablo Galindo114081f2020-03-02 03:14:06 +0000399
400
401.. class:: Add
402 Sub
403 Mult
404 Div
405 FloorDiv
406 Mod
407 Pow
408 LShift
409 RShift
410 BitOr
411 BitXor
412 BitAnd
413 MatMult
414
415 Binary operator tokens.
416
417
418.. class:: BoolOp(op, values)
419
420 A boolean operation, 'or' or 'and'. ``op`` is :class:`Or` or :class:`And`.
421 ``values`` are the values involved. Consecutive operations with the same
422 operator, such as ``a or b or c``, are collapsed into one node with several
423 values.
424
425 This doesn't include ``not``, which is a :class:`UnaryOp`.
426
427 .. doctest::
428
Pablo Galindo02f64cb2020-03-07 18:22:58 +0000429 >>> print(ast.dump(ast.parse('x or y', mode='eval'), indent=4))
430 Expression(
431 body=BoolOp(
432 op=Or(),
433 values=[
434 Name(id='x', ctx=Load()),
435 Name(id='y', ctx=Load())]))
Pablo Galindo114081f2020-03-02 03:14:06 +0000436
437
438.. class:: And
439 Or
440
441 Boolean operator tokens.
442
443
444.. class:: Compare(left, ops, comparators)
445
446 A comparison of two or more values. ``left`` is the first value in the
447 comparison, ``ops`` the list of operators, and ``comparators`` the list
448 of values after the first element in the comparison.
449
450 .. doctest::
451
Pablo Galindo02f64cb2020-03-07 18:22:58 +0000452 >>> print(ast.dump(ast.parse('1 <= a < 10', mode='eval'), indent=4))
453 Expression(
454 body=Compare(
Serhiy Storchakab7e95252020-03-10 00:07:47 +0200455 left=Constant(value=1),
Pablo Galindo02f64cb2020-03-07 18:22:58 +0000456 ops=[
457 LtE(),
458 Lt()],
459 comparators=[
460 Name(id='a', ctx=Load()),
Serhiy Storchakab7e95252020-03-10 00:07:47 +0200461 Constant(value=10)]))
Pablo Galindo114081f2020-03-02 03:14:06 +0000462
463
464.. class:: Eq
465 NotEq
466 Lt
467 LtE
468 Gt
469 GtE
470 Is
471 IsNot
472 In
473 NotIn
474
475 Comparison operator tokens.
476
477
478.. class:: Call(func, args, keywords, starargs, kwargs)
479
480 A function call. ``func`` is the function, which will often be a
481 :class:`Name` or :class:`Attribute` object. Of the arguments:
482
483 * ``args`` holds a list of the arguments passed by position.
484 * ``keywords`` holds a list of :class:`keyword` objects representing
485 arguments passed by keyword.
486
487 When creating a ``Call`` node, ``args`` and ``keywords`` are required, but
488 they can be empty lists. ``starargs`` and ``kwargs`` are optional.
489
490 .. doctest::
491
Pablo Galindo02f64cb2020-03-07 18:22:58 +0000492 >>> print(ast.dump(ast.parse('func(a, b=c, *d, **e)', mode='eval'), indent=4))
493 Expression(
494 body=Call(
495 func=Name(id='func', ctx=Load()),
496 args=[
497 Name(id='a', ctx=Load()),
498 Starred(
499 value=Name(id='d', ctx=Load()),
500 ctx=Load())],
501 keywords=[
502 keyword(
503 arg='b',
504 value=Name(id='c', ctx=Load())),
505 keyword(
Pablo Galindo02f64cb2020-03-07 18:22:58 +0000506 value=Name(id='e', ctx=Load()))]))
Pablo Galindo114081f2020-03-02 03:14:06 +0000507
508
509.. class:: keyword(arg, value)
510
511 A keyword argument to a function call or class definition. ``arg`` is a raw
512 string of the parameter name, ``value`` is a node to pass in.
513
514
515.. class:: IfExp(test, body, orelse)
516
517 An expression such as ``a if b else c``. Each field holds a single node, so
518 in the following example, all three are :class:`Name` nodes.
519
520 .. doctest::
521
Pablo Galindo02f64cb2020-03-07 18:22:58 +0000522 >>> print(ast.dump(ast.parse('a if b else c', mode='eval'), indent=4))
523 Expression(
524 body=IfExp(
525 test=Name(id='b', ctx=Load()),
526 body=Name(id='a', ctx=Load()),
527 orelse=Name(id='c', ctx=Load())))
Pablo Galindo114081f2020-03-02 03:14:06 +0000528
529
530.. class:: Attribute(value, attr, ctx)
531
532 Attribute access, e.g. ``d.keys``. ``value`` is a node, typically a
533 :class:`Name`. ``attr`` is a bare string giving the name of the attribute,
534 and ``ctx`` is :class:`Load`, :class:`Store` or :class:`Del` according to how
535 the attribute is acted on.
536
537 .. doctest::
538
Pablo Galindo02f64cb2020-03-07 18:22:58 +0000539 >>> print(ast.dump(ast.parse('snake.colour', mode='eval'), indent=4))
540 Expression(
541 body=Attribute(
542 value=Name(id='snake', ctx=Load()),
543 attr='colour',
544 ctx=Load()))
Pablo Galindo114081f2020-03-02 03:14:06 +0000545
546
547.. class:: NamedExpr(target, value)
548
549 A named expression. This AST node is produced by the assignment expressions
550 operator (also known as the walrus operator). As opposed to the :class:`Assign`
551 node in which the first argument can be multiple nodes, in this case both
552 ``target`` and ``value`` must be single nodes.
553
554 .. doctest::
555
Pablo Galindo02f64cb2020-03-07 18:22:58 +0000556 >>> print(ast.dump(ast.parse('(x := 4)', mode='eval'), indent=4))
557 Expression(
558 body=NamedExpr(
559 target=Name(id='x', ctx=Store()),
Serhiy Storchakab7e95252020-03-10 00:07:47 +0200560 value=Constant(value=4)))
Pablo Galindo114081f2020-03-02 03:14:06 +0000561
562
563Subscripting
564~~~~~~~~~~~~
565
566.. class:: Subscript(value, slice, ctx)
567
Serhiy Storchaka13d52c22020-03-10 18:52:34 +0200568 A subscript, such as ``l[1]``. ``value`` is the subscripted object
569 (usually sequence or mapping). ``slice`` is an index, slice or key.
570 It can be a :class:`Tuple` and contain a :class:`Slice`.
571 ``ctx`` is :class:`Load`, :class:`Store` or :class:`Del`
Pablo Galindo114081f2020-03-02 03:14:06 +0000572 according to the action performed with the subscript.
573
Pablo Galindo114081f2020-03-02 03:14:06 +0000574 .. doctest::
575
Serhiy Storchaka13d52c22020-03-10 18:52:34 +0200576 >>> print(ast.dump(ast.parse('l[1:2, 3]', mode='eval'), indent=4))
Pablo Galindo02f64cb2020-03-07 18:22:58 +0000577 Expression(
578 body=Subscript(
579 value=Name(id='l', ctx=Load()),
Serhiy Storchaka13d52c22020-03-10 18:52:34 +0200580 slice=Tuple(
581 elts=[
582 Slice(
583 lower=Constant(value=1),
584 upper=Constant(value=2)),
585 Constant(value=3)],
586 ctx=Load()),
Pablo Galindo02f64cb2020-03-07 18:22:58 +0000587 ctx=Load()))
Pablo Galindo114081f2020-03-02 03:14:06 +0000588
589
590.. class:: Slice(lower, upper, step)
591
Serhiy Storchaka13d52c22020-03-10 18:52:34 +0200592 Regular slicing (on the form ``lower:upper`` or ``lower:upper:step``).
593 Can occur only inside the *slice* field of :class:`Subscript`, either
594 directly or as an element of :class:`Tuple`.
Pablo Galindo114081f2020-03-02 03:14:06 +0000595
596 .. doctest::
597
Pablo Galindo02f64cb2020-03-07 18:22:58 +0000598 >>> print(ast.dump(ast.parse('l[1:2]', mode='eval'), indent=4))
599 Expression(
600 body=Subscript(
601 value=Name(id='l', ctx=Load()),
602 slice=Slice(
Serhiy Storchakab7e95252020-03-10 00:07:47 +0200603 lower=Constant(value=1),
604 upper=Constant(value=2)),
Pablo Galindo02f64cb2020-03-07 18:22:58 +0000605 ctx=Load()))
Pablo Galindo114081f2020-03-02 03:14:06 +0000606
607
Pablo Galindo114081f2020-03-02 03:14:06 +0000608Comprehensions
609~~~~~~~~~~~~~~
610
611.. class:: ListComp(elt, generators)
612 SetComp(elt, generators)
613 GeneratorExp(elt, generators)
614 DictComp(key, value, generators)
615
616 List and set comprehensions, generator expressions, and dictionary
617 comprehensions. ``elt`` (or ``key`` and ``value``) is a single node
618 representing the part that will be evaluated for each item.
619
620 ``generators`` is a list of :class:`comprehension` nodes.
621
622 .. doctest::
623
Pablo Galindo02f64cb2020-03-07 18:22:58 +0000624 >>> print(ast.dump(ast.parse('[x for x in numbers]', mode='eval'), indent=4))
625 Expression(
626 body=ListComp(
627 elt=Name(id='x', ctx=Load()),
628 generators=[
629 comprehension(
630 target=Name(id='x', ctx=Store()),
631 iter=Name(id='numbers', ctx=Load()),
632 ifs=[],
633 is_async=0)]))
634 >>> print(ast.dump(ast.parse('{x: x**2 for x in numbers}', mode='eval'), indent=4))
635 Expression(
636 body=DictComp(
637 key=Name(id='x', ctx=Load()),
638 value=BinOp(
639 left=Name(id='x', ctx=Load()),
640 op=Pow(),
Serhiy Storchakab7e95252020-03-10 00:07:47 +0200641 right=Constant(value=2)),
Pablo Galindo02f64cb2020-03-07 18:22:58 +0000642 generators=[
643 comprehension(
644 target=Name(id='x', ctx=Store()),
645 iter=Name(id='numbers', ctx=Load()),
646 ifs=[],
647 is_async=0)]))
648 >>> print(ast.dump(ast.parse('{x for x in numbers}', mode='eval'), indent=4))
649 Expression(
650 body=SetComp(
651 elt=Name(id='x', ctx=Load()),
652 generators=[
653 comprehension(
654 target=Name(id='x', ctx=Store()),
655 iter=Name(id='numbers', ctx=Load()),
656 ifs=[],
657 is_async=0)]))
Pablo Galindo114081f2020-03-02 03:14:06 +0000658
659
660.. class:: comprehension(target, iter, ifs, is_async)
661
662 One ``for`` clause in a comprehension. ``target`` is the reference to use for
663 each element - typically a :class:`Name` or :class:`Tuple` node. ``iter``
664 is the object to iterate over. ``ifs`` is a list of test expressions: each
665 ``for`` clause can have multiple ``ifs``.
666
667 ``is_async`` indicates a comprehension is asynchronous (using an
668 ``async for`` instead of ``for``). The value is an integer (0 or 1).
669
670 .. doctest::
671
Pablo Galindo02f64cb2020-03-07 18:22:58 +0000672 >>> print(ast.dump(ast.parse('[ord(c) for line in file for c in line]', mode='eval'),
Pablo Galindo114081f2020-03-02 03:14:06 +0000673 ... indent=4)) # Multiple comprehensions in one.
674 Expression(
675 body=ListComp(
676 elt=Call(
677 func=Name(id='ord', ctx=Load()),
678 args=[
679 Name(id='c', ctx=Load())],
680 keywords=[]),
681 generators=[
682 comprehension(
683 target=Name(id='line', ctx=Store()),
684 iter=Name(id='file', ctx=Load()),
685 ifs=[],
686 is_async=0),
687 comprehension(
688 target=Name(id='c', ctx=Store()),
689 iter=Name(id='line', ctx=Load()),
690 ifs=[],
691 is_async=0)]))
692
Pablo Galindo02f64cb2020-03-07 18:22:58 +0000693 >>> 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 +0000694 ... indent=4)) # generator comprehension
695 Expression(
696 body=GeneratorExp(
697 elt=BinOp(
698 left=Name(id='n', ctx=Load()),
699 op=Pow(),
Serhiy Storchakab7e95252020-03-10 00:07:47 +0200700 right=Constant(value=2)),
Pablo Galindo114081f2020-03-02 03:14:06 +0000701 generators=[
702 comprehension(
703 target=Name(id='n', ctx=Store()),
704 iter=Name(id='it', ctx=Load()),
705 ifs=[
706 Compare(
707 left=Name(id='n', ctx=Load()),
708 ops=[
709 Gt()],
710 comparators=[
Serhiy Storchakab7e95252020-03-10 00:07:47 +0200711 Constant(value=5)]),
Pablo Galindo114081f2020-03-02 03:14:06 +0000712 Compare(
713 left=Name(id='n', ctx=Load()),
714 ops=[
715 Lt()],
716 comparators=[
Serhiy Storchakab7e95252020-03-10 00:07:47 +0200717 Constant(value=10)])],
Pablo Galindo114081f2020-03-02 03:14:06 +0000718 is_async=0)]))
719
Pablo Galindo02f64cb2020-03-07 18:22:58 +0000720 >>> print(ast.dump(ast.parse('[i async for i in soc]', mode='eval'),
Pablo Galindo114081f2020-03-02 03:14:06 +0000721 ... indent=4)) # Async comprehension
Pablo Galindo02f64cb2020-03-07 18:22:58 +0000722 Expression(
723 body=ListComp(
724 elt=Name(id='i', ctx=Load()),
725 generators=[
726 comprehension(
727 target=Name(id='i', ctx=Store()),
728 iter=Name(id='soc', ctx=Load()),
729 ifs=[],
730 is_async=1)]))
Pablo Galindo114081f2020-03-02 03:14:06 +0000731
732Statements
733^^^^^^^^^^
734
735.. class:: Assign(targets, value, type_comment)
736
737 An assignment. ``targets`` is a list of nodes, and ``value`` is a single node.
738
739 Multiple nodes in ``targets`` represents assigning the same value to each.
740 Unpacking is represented by putting a :class:`Tuple` or :class:`List`
741 within ``targets``.
742
743 .. attribute:: type_comment
744
745 ``type_comment`` is an optional string with the type annotation as a comment.
746
747 .. doctest::
748
Pablo Galindo02f64cb2020-03-07 18:22:58 +0000749 >>> print(ast.dump(ast.parse('a = b = 1'), indent=4)) # Multiple assignment
Pablo Galindo114081f2020-03-02 03:14:06 +0000750 Module(
751 body=[
752 Assign(
753 targets=[
754 Name(id='a', ctx=Store()),
755 Name(id='b', ctx=Store())],
Serhiy Storchakab7e95252020-03-10 00:07:47 +0200756 value=Constant(value=1))],
Pablo Galindo114081f2020-03-02 03:14:06 +0000757 type_ignores=[])
758
Pablo Galindo02f64cb2020-03-07 18:22:58 +0000759 >>> print(ast.dump(ast.parse('a,b = c'), indent=4)) # Unpacking
Pablo Galindo114081f2020-03-02 03:14:06 +0000760 Module(
761 body=[
762 Assign(
763 targets=[
764 Tuple(
765 elts=[
766 Name(id='a', ctx=Store()),
767 Name(id='b', ctx=Store())],
768 ctx=Store())],
Serhiy Storchakab7e95252020-03-10 00:07:47 +0200769 value=Name(id='c', ctx=Load()))],
Pablo Galindo114081f2020-03-02 03:14:06 +0000770 type_ignores=[])
771
772
773.. class:: AnnAssign(target, annotation, value, simple)
774
775 An assignment with a type annotation. ``target`` is a single node and can
776 be a :class:`Name`, a :class:`Attribute` or a :class:`Subscript`.
777 ``annotation`` is the annotation, such as a :class:`Constant` or :class:`Name`
778 node. ``value`` is a single optional node. ``simple`` is a boolean integer
779 set to True for a :class:`Name` node in ``target`` that do not appear in
780 between parenthesis and are hence pure names and not expressions.
781
782 .. doctest::
783
Pablo Galindo02f64cb2020-03-07 18:22:58 +0000784 >>> print(ast.dump(ast.parse('c: int'), indent=4))
Pablo Galindo114081f2020-03-02 03:14:06 +0000785 Module(
786 body=[
787 AnnAssign(
788 target=Name(id='c', ctx=Store()),
789 annotation=Name(id='int', ctx=Load()),
Pablo Galindo114081f2020-03-02 03:14:06 +0000790 simple=1)],
791 type_ignores=[])
792
Pablo Galindo02f64cb2020-03-07 18:22:58 +0000793 >>> print(ast.dump(ast.parse('(a): int = 1'), indent=4)) # Annotation with parenthesis
Pablo Galindo114081f2020-03-02 03:14:06 +0000794 Module(
795 body=[
796 AnnAssign(
797 target=Name(id='a', ctx=Store()),
798 annotation=Name(id='int', ctx=Load()),
Serhiy Storchakab7e95252020-03-10 00:07:47 +0200799 value=Constant(value=1),
Pablo Galindo114081f2020-03-02 03:14:06 +0000800 simple=0)],
801 type_ignores=[])
802
Pablo Galindo02f64cb2020-03-07 18:22:58 +0000803 >>> print(ast.dump(ast.parse('a.b: int'), indent=4)) # Attribute annotation
Pablo Galindo114081f2020-03-02 03:14:06 +0000804 Module(
805 body=[
806 AnnAssign(
807 target=Attribute(
808 value=Name(id='a', ctx=Load()),
809 attr='b',
810 ctx=Store()),
811 annotation=Name(id='int', ctx=Load()),
Pablo Galindo114081f2020-03-02 03:14:06 +0000812 simple=0)],
813 type_ignores=[])
814
Pablo Galindo02f64cb2020-03-07 18:22:58 +0000815 >>> print(ast.dump(ast.parse('a[1]: int'), indent=4)) # Subscript annotation
Pablo Galindo114081f2020-03-02 03:14:06 +0000816 Module(
817 body=[
818 AnnAssign(
819 target=Subscript(
820 value=Name(id='a', ctx=Load()),
Serhiy Storchaka13d52c22020-03-10 18:52:34 +0200821 slice=Constant(value=1),
Pablo Galindo114081f2020-03-02 03:14:06 +0000822 ctx=Store()),
823 annotation=Name(id='int', ctx=Load()),
Pablo Galindo114081f2020-03-02 03:14:06 +0000824 simple=0)],
825 type_ignores=[])
826
827
828.. class:: AugAssign(target, op, value)
829
830 Augmented assignment, such as ``a += 1``. In the following example,
831 ``target`` is a :class:`Name` node for ``x`` (with the :class:`Store`
832 context), ``op`` is :class:`Add`, and ``value`` is a :class:`Constant` with
833 value for 1.
834
835 The ``target`` attribute connot be of class :class:`Tuple` or :class:`List`,
836 unlike the targets of :class:`Assign`.
837
838 .. doctest::
839
Pablo Galindo02f64cb2020-03-07 18:22:58 +0000840 >>> print(ast.dump(ast.parse('x += 2'), indent=4))
Pablo Galindo114081f2020-03-02 03:14:06 +0000841 Module(
842 body=[
843 AugAssign(
844 target=Name(id='x', ctx=Store()),
845 op=Add(),
Serhiy Storchakab7e95252020-03-10 00:07:47 +0200846 value=Constant(value=2))],
Pablo Galindo114081f2020-03-02 03:14:06 +0000847 type_ignores=[])
848
849
850.. class:: Raise(exc, cause)
851
852 A ``raise`` statement. ``exc`` is the exception object to be raised, normally a
853 :class:`Call` or :class:`Name`, or ``None`` for a standalone ``raise``.
854 ``cause`` is the optional part for ``y`` in ``raise x from y``.
855
856 .. doctest::
857
Pablo Galindo02f64cb2020-03-07 18:22:58 +0000858 >>> print(ast.dump(ast.parse('raise x from y'), indent=4))
Pablo Galindo114081f2020-03-02 03:14:06 +0000859 Module(
860 body=[
861 Raise(
862 exc=Name(id='x', ctx=Load()),
863 cause=Name(id='y', ctx=Load()))],
864 type_ignores=[])
865
866
867.. class:: Assert(test, msg)
868
869 An assertion. ``test`` holds the condition, such as a :class:`Compare` node.
870 ``msg`` holds the failure message.
871
872 .. doctest::
873
Pablo Galindo02f64cb2020-03-07 18:22:58 +0000874 >>> print(ast.dump(ast.parse('assert x,y'), indent=4))
Pablo Galindo114081f2020-03-02 03:14:06 +0000875 Module(
876 body=[
877 Assert(
878 test=Name(id='x', ctx=Load()),
879 msg=Name(id='y', ctx=Load()))],
880 type_ignores=[])
881
882
883.. class:: Delete(targets)
884
885 Represents a ``del`` statement. ``targets`` is a list of nodes, such as
886 :class:`Name`, :class:`Attribute` or :class:`Subscript` nodes.
887
888 .. doctest::
889
Pablo Galindo02f64cb2020-03-07 18:22:58 +0000890 >>> print(ast.dump(ast.parse('del x,y,z'), indent=4))
Pablo Galindo114081f2020-03-02 03:14:06 +0000891 Module(
892 body=[
893 Delete(
894 targets=[
895 Name(id='x', ctx=Del()),
896 Name(id='y', ctx=Del()),
897 Name(id='z', ctx=Del())])],
898 type_ignores=[])
899
900
901.. class:: Pass()
902
903 A ``pass`` statement.
904
905 .. doctest::
906
Pablo Galindo02f64cb2020-03-07 18:22:58 +0000907 >>> print(ast.dump(ast.parse('pass'), indent=4))
Pablo Galindo114081f2020-03-02 03:14:06 +0000908 Module(
909 body=[
910 Pass()],
911 type_ignores=[])
912
913
914Other statements which are only applicable inside functions or loops are
915described in other sections.
916
917Imports
918~~~~~~~
919
920.. class:: Import(names)
921
922 An import statement. ``names`` is a list of :class:`alias` nodes.
923
924 .. doctest::
925
Pablo Galindo02f64cb2020-03-07 18:22:58 +0000926 >>> print(ast.dump(ast.parse('import x,y,z'), indent=4))
Pablo Galindo114081f2020-03-02 03:14:06 +0000927 Module(
928 body=[
929 Import(
930 names=[
Serhiy Storchakab7e95252020-03-10 00:07:47 +0200931 alias(name='x'),
932 alias(name='y'),
933 alias(name='z')])],
Pablo Galindo114081f2020-03-02 03:14:06 +0000934 type_ignores=[])
935
936
937.. class:: ImportFrom(module, names, level)
938
939 Represents ``from x import y``. ``module`` is a raw string of the 'from' name,
940 without any leading dots, or ``None`` for statements such as ``from . import foo``.
941 ``level`` is an integer holding the level of the relative import (0 means
942 absolute import).
943
944 .. doctest::
945
Pablo Galindo02f64cb2020-03-07 18:22:58 +0000946 >>> print(ast.dump(ast.parse('from y import x,y,z'), indent=4))
Pablo Galindo114081f2020-03-02 03:14:06 +0000947 Module(
948 body=[
949 ImportFrom(
950 module='y',
951 names=[
Serhiy Storchakab7e95252020-03-10 00:07:47 +0200952 alias(name='x'),
953 alias(name='y'),
954 alias(name='z')],
Pablo Galindo114081f2020-03-02 03:14:06 +0000955 level=0)],
956 type_ignores=[])
957
958
959.. class:: alias(name, asname)
960
961 Both parameters are raw strings of the names. ``asname`` can be ``None`` if
962 the regular name is to be used.
963
964 .. doctest::
965
Pablo Galindo02f64cb2020-03-07 18:22:58 +0000966 >>> print(ast.dump(ast.parse('from ..foo.bar import a as b, c'), indent=4))
Pablo Galindo114081f2020-03-02 03:14:06 +0000967 Module(
968 body=[
969 ImportFrom(
970 module='foo.bar',
971 names=[
972 alias(name='a', asname='b'),
Serhiy Storchakab7e95252020-03-10 00:07:47 +0200973 alias(name='c')],
Pablo Galindo114081f2020-03-02 03:14:06 +0000974 level=2)],
975 type_ignores=[])
976
977Control flow
978^^^^^^^^^^^^
979
980.. note::
981 Optional clauses such as ``else`` are stored as an empty list if they're
982 not present.
983
984.. class:: If(test, body, orelse)
985
986 An ``if`` statement. ``test`` holds a single node, such as a :class:`Compare`
987 node. ``body`` and ``orelse`` each hold a list of nodes.
988
989 ``elif`` clauses don't have a special representation in the AST, but rather
990 appear as extra :class:`If` nodes within the ``orelse`` section of the
991 previous one.
992
993 .. doctest::
994
995 >>> print(ast.dump(ast.parse("""
996 ... if x:
997 ... ...
998 ... elif y:
999 ... ...
1000 ... else:
1001 ... ...
1002 ... """), indent=4))
1003 Module(
1004 body=[
1005 If(
1006 test=Name(id='x', ctx=Load()),
1007 body=[
1008 Expr(
Serhiy Storchakab7e95252020-03-10 00:07:47 +02001009 value=Constant(value=Ellipsis))],
Pablo Galindo114081f2020-03-02 03:14:06 +00001010 orelse=[
1011 If(
1012 test=Name(id='y', 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 Expr(
Serhiy Storchakab7e95252020-03-10 00:07:47 +02001018 value=Constant(value=Ellipsis))])])],
Pablo Galindo114081f2020-03-02 03:14:06 +00001019 type_ignores=[])
1020
1021
1022.. class:: For(target, iter, body, orelse, type_comment)
1023
1024 A ``for`` loop. ``target`` holds the variable(s) the loop assigns to, as a
1025 single :class:`Name`, :class:`Tuple` or :class:`List` node. ``iter`` holds
1026 the item to be looped over, again as a single node. ``body`` and ``orelse``
1027 contain lists of nodes to execute. Those in ``orelse`` are executed if the
1028 loop finishes normally, rather than via a ``break`` statement.
1029
1030 .. attribute:: type_comment
1031
1032 ``type_comment`` is an optional string with the type annotation as a comment.
1033
1034 .. doctest::
1035
1036 >>> print(ast.dump(ast.parse("""
1037 ... for x in y:
1038 ... ...
1039 ... else:
1040 ... ...
1041 ... """), indent=4))
1042 Module(
1043 body=[
1044 For(
1045 target=Name(id='x', ctx=Store()),
1046 iter=Name(id='y', ctx=Load()),
1047 body=[
1048 Expr(
Serhiy Storchakab7e95252020-03-10 00:07:47 +02001049 value=Constant(value=Ellipsis))],
Pablo Galindo114081f2020-03-02 03:14:06 +00001050 orelse=[
1051 Expr(
Serhiy Storchakab7e95252020-03-10 00:07:47 +02001052 value=Constant(value=Ellipsis))])],
Pablo Galindo114081f2020-03-02 03:14:06 +00001053 type_ignores=[])
1054
1055
1056.. class:: While(test, body, orelse)
1057
1058 A ``while`` loop. ``test`` holds the condition, such as a :class:`Compare`
1059 node.
1060
1061 .. doctest::
1062
1063 >> print(ast.dump(ast.parse("""
1064 ... while x:
1065 ... ...
1066 ... else:
1067 ... ...
1068 ... """), indent=4))
1069 Module(
1070 body=[
1071 While(
1072 test=Name(id='x', ctx=Load()),
1073 body=[
1074 Expr(
Serhiy Storchakab7e95252020-03-10 00:07:47 +02001075 value=Constant(value=Ellipsis))],
Pablo Galindo114081f2020-03-02 03:14:06 +00001076 orelse=[
1077 Expr(
Serhiy Storchakab7e95252020-03-10 00:07:47 +02001078 value=Constant(value=Ellipsis))])],
Pablo Galindo114081f2020-03-02 03:14:06 +00001079 type_ignores=[])
1080
1081
1082.. class:: Break
1083 Continue
1084
1085 The ``break`` and ``continue`` statements.
1086
1087 .. doctest::
1088
1089 >>> print(ast.dump(ast.parse("""\
1090 ... for a in b:
1091 ... if a > 5:
1092 ... break
1093 ... else:
1094 ... continue
1095 ...
1096 ... """), indent=4))
1097 Module(
1098 body=[
1099 For(
1100 target=Name(id='a', ctx=Store()),
1101 iter=Name(id='b', ctx=Load()),
1102 body=[
1103 If(
1104 test=Compare(
1105 left=Name(id='a', ctx=Load()),
1106 ops=[
1107 Gt()],
1108 comparators=[
Serhiy Storchakab7e95252020-03-10 00:07:47 +02001109 Constant(value=5)]),
Pablo Galindo114081f2020-03-02 03:14:06 +00001110 body=[
1111 Break()],
1112 orelse=[
1113 Continue()])],
Serhiy Storchakab7e95252020-03-10 00:07:47 +02001114 orelse=[])],
Pablo Galindo114081f2020-03-02 03:14:06 +00001115 type_ignores=[])
1116
1117
1118.. class:: Try(body, handlers, orelse, finalbody)
1119
1120 ``try`` blocks. All attributes are list of nodes to execute, except for
1121 ``handlers``, which is a list of :class:`ExceptHandler` nodes.
1122
1123 .. doctest::
1124
1125 >>> print(ast.dump(ast.parse("""
1126 ... try:
1127 ... ...
1128 ... except Exception:
1129 ... ...
1130 ... except OtherException as e:
1131 ... ...
1132 ... else:
1133 ... ...
1134 ... finally:
1135 ... ...
1136 ... """), indent=4))
1137 Module(
1138 body=[
1139 Try(
1140 body=[
1141 Expr(
Serhiy Storchakab7e95252020-03-10 00:07:47 +02001142 value=Constant(value=Ellipsis))],
Pablo Galindo114081f2020-03-02 03:14:06 +00001143 handlers=[
1144 ExceptHandler(
1145 type=Name(id='Exception', ctx=Load()),
Pablo Galindo114081f2020-03-02 03:14:06 +00001146 body=[
1147 Expr(
Serhiy Storchakab7e95252020-03-10 00:07:47 +02001148 value=Constant(value=Ellipsis))]),
Pablo Galindo114081f2020-03-02 03:14:06 +00001149 ExceptHandler(
1150 type=Name(id='OtherException', ctx=Load()),
1151 name='e',
1152 body=[
1153 Expr(
Serhiy Storchakab7e95252020-03-10 00:07:47 +02001154 value=Constant(value=Ellipsis))])],
Pablo Galindo114081f2020-03-02 03:14:06 +00001155 orelse=[
1156 Expr(
Serhiy Storchakab7e95252020-03-10 00:07:47 +02001157 value=Constant(value=Ellipsis))],
Pablo Galindo114081f2020-03-02 03:14:06 +00001158 finalbody=[
1159 Expr(
Serhiy Storchakab7e95252020-03-10 00:07:47 +02001160 value=Constant(value=Ellipsis))])],
Pablo Galindo114081f2020-03-02 03:14:06 +00001161 type_ignores=[])
1162
1163
1164.. class:: ExceptHandler(type, name, body)
1165
1166 A single ``except`` clause. ``type`` is the exception type it will match,
1167 typically a :class:`Name` node (or ``None`` for a catch-all ``except:`` clause).
1168 ``name`` is a raw string for the name to hold the exception, or ``None`` if
1169 the clause doesn't have ``as foo``. ``body`` is a list of nodes.
1170
1171 .. doctest::
1172
1173 >>> print(ast.dump(ast.parse("""\
1174 ... try:
1175 ... a + 1
1176 ... except TypeError:
1177 ... pass
1178 ... """), indent=4))
1179 Module(
1180 body=[
1181 Try(
1182 body=[
1183 Expr(
1184 value=BinOp(
1185 left=Name(id='a', ctx=Load()),
1186 op=Add(),
Serhiy Storchakab7e95252020-03-10 00:07:47 +02001187 right=Constant(value=1)))],
Pablo Galindo114081f2020-03-02 03:14:06 +00001188 handlers=[
1189 ExceptHandler(
1190 type=Name(id='TypeError', ctx=Load()),
Pablo Galindo114081f2020-03-02 03:14:06 +00001191 body=[
1192 Pass()])],
1193 orelse=[],
1194 finalbody=[])],
1195 type_ignores=[])
1196
1197
1198.. class:: With(items, body, type_comment)
1199
1200 A ``with`` block. ``items`` is a list of :class:`withitem` nodes representing
1201 the context managers, and ``body`` is the indented block inside the context.
1202
1203 .. attribute:: type_comment
1204
1205 ``type_comment`` is an optional string with the type annotation as a comment.
1206
1207
1208.. class:: withitem(context_expr, optional_vars)
1209
1210 A single context manager in a ``with`` block. ``context_expr`` is the context
1211 manager, often a :class:`Call` node. ``optional_vars`` is a :class:`Name`,
1212 :class:`Tuple` or :class:`List` for the ``as foo`` part, or ``None`` if that
1213 isn't used.
1214
1215 .. doctest::
1216
1217 >>> print(ast.dump(ast.parse("""\
1218 ... with a as b, c as d:
1219 ... something(b, d)
1220 ... """), indent=4))
1221 Module(
1222 body=[
1223 With(
1224 items=[
1225 withitem(
1226 context_expr=Name(id='a', ctx=Load()),
1227 optional_vars=Name(id='b', ctx=Store())),
1228 withitem(
1229 context_expr=Name(id='c', ctx=Load()),
1230 optional_vars=Name(id='d', ctx=Store()))],
1231 body=[
1232 Expr(
1233 value=Call(
1234 func=Name(id='something', ctx=Load()),
1235 args=[
1236 Name(id='b', ctx=Load()),
1237 Name(id='d', ctx=Load())],
Serhiy Storchakab7e95252020-03-10 00:07:47 +02001238 keywords=[]))])],
Pablo Galindo114081f2020-03-02 03:14:06 +00001239 type_ignores=[])
1240
1241
1242Function and class definitions
1243^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1244
1245.. class:: FunctionDef(name, args, body, decorator_list, returns, type_comment)
1246
1247 A function definition.
1248
1249 * ``name`` is a raw string of the function name.
1250 * ``args`` is a :class:`arguments` node.
1251 * ``body`` is the list of nodes inside the function.
1252 * ``decorator_list`` is the list of decorators to be applied, stored outermost
1253 first (i.e. the first in the list will be applied last).
1254 * ``returns`` is the return annotation.
1255
1256 .. attribute:: type_comment
1257
1258 ``type_comment`` is an optional string with the type annotation as a comment.
1259
1260
1261.. class:: Lambda(args, body)
1262
1263 ``lambda`` is a minimal function definition that can be used inside an
1264 expression. Unlike :class:`FunctionDef`, ``body`` holds a single node.
1265
1266 .. doctest::
1267
Pablo Galindo02f64cb2020-03-07 18:22:58 +00001268 >>> print(ast.dump(ast.parse('lambda x,y: ...'), indent=4))
Pablo Galindo114081f2020-03-02 03:14:06 +00001269 Module(
1270 body=[
1271 Expr(
1272 value=Lambda(
1273 args=arguments(
1274 posonlyargs=[],
1275 args=[
Serhiy Storchakab7e95252020-03-10 00:07:47 +02001276 arg(arg='x'),
1277 arg(arg='y')],
Pablo Galindo114081f2020-03-02 03:14:06 +00001278 kwonlyargs=[],
1279 kw_defaults=[],
Pablo Galindo114081f2020-03-02 03:14:06 +00001280 defaults=[]),
Serhiy Storchakab7e95252020-03-10 00:07:47 +02001281 body=Constant(value=Ellipsis)))],
Pablo Galindo114081f2020-03-02 03:14:06 +00001282 type_ignores=[])
1283
1284
1285.. class:: arguments(posonlyargs, args, vararg, kwonlyargs, kw_defaults, kwarg, defaults)
1286
1287 The arguments for a function.
1288
1289 * ``posonlyargs``, ``args`` and ``kwonlyargs`` are lists of :class:`arg` nodes.
1290 * ``vararg`` and ``kwarg`` are single :class:`arg` nodes, referring to the
1291 ``*args, **kwargs`` parameters.
1292 * ``kw_defaults`` is a list of default values for keyword-only arguments. If
1293 one is ``None``, the corresponding argument is required.
1294 * ``defaults`` is a list of default values for arguments that can be passed
1295 positionally. If there are fewer defaults, they correspond to the last n
1296 arguments.
1297
1298
1299.. class:: arg(arg, annotation, type_comment)
1300
1301 A single argument in a list. ``arg`` is a raw string of the argument
1302 name, ``annotation`` is its annotation, such as a :class:`Str` or
1303 :class:`Name` node.
1304
1305 .. attribute:: type_comment
1306
1307 ``type_comment`` is an optional string with the type annotation as a comment
1308
1309 .. doctest::
1310
1311 >>> print(ast.dump(ast.parse("""\
1312 ... @decorator1
1313 ... @decorator2
1314 ... def f(a: 'annotation', b=1, c=2, *d, e, f=3, **g) -> 'return annotation':
1315 ... pass
1316 ... """), indent=4))
1317 Module(
1318 body=[
1319 FunctionDef(
1320 name='f',
1321 args=arguments(
1322 posonlyargs=[],
1323 args=[
1324 arg(
1325 arg='a',
Serhiy Storchakab7e95252020-03-10 00:07:47 +02001326 annotation=Constant(value='annotation')),
1327 arg(arg='b'),
1328 arg(arg='c')],
1329 vararg=arg(arg='d'),
Pablo Galindo114081f2020-03-02 03:14:06 +00001330 kwonlyargs=[
Serhiy Storchakab7e95252020-03-10 00:07:47 +02001331 arg(arg='e'),
1332 arg(arg='f')],
Pablo Galindo114081f2020-03-02 03:14:06 +00001333 kw_defaults=[
1334 None,
Serhiy Storchakab7e95252020-03-10 00:07:47 +02001335 Constant(value=3)],
1336 kwarg=arg(arg='g'),
Pablo Galindo114081f2020-03-02 03:14:06 +00001337 defaults=[
Serhiy Storchakab7e95252020-03-10 00:07:47 +02001338 Constant(value=1),
1339 Constant(value=2)]),
Pablo Galindo114081f2020-03-02 03:14:06 +00001340 body=[
1341 Pass()],
1342 decorator_list=[
1343 Name(id='decorator1', ctx=Load()),
1344 Name(id='decorator2', ctx=Load())],
Serhiy Storchakab7e95252020-03-10 00:07:47 +02001345 returns=Constant(value='return annotation'))],
Pablo Galindo114081f2020-03-02 03:14:06 +00001346 type_ignores=[])
1347
1348
1349.. class:: Return(value)
1350
1351 A ``return`` statement.
1352
1353 .. doctest::
1354
Pablo Galindo02f64cb2020-03-07 18:22:58 +00001355 >>> print(ast.dump(ast.parse('return 4'), indent=4))
Pablo Galindo114081f2020-03-02 03:14:06 +00001356 Module(
1357 body=[
1358 Return(
Serhiy Storchakab7e95252020-03-10 00:07:47 +02001359 value=Constant(value=4))],
Pablo Galindo114081f2020-03-02 03:14:06 +00001360 type_ignores=[])
1361
1362
1363.. class:: Yield(value)
1364 YieldFrom(value)
1365
1366 A ``yield`` or ``yield from`` expression. Because these are expressions, they
1367 must be wrapped in a :class:`Expr` node if the value sent back is not used.
1368
1369 .. doctest::
1370
Pablo Galindo02f64cb2020-03-07 18:22:58 +00001371 >>> print(ast.dump(ast.parse('yield x'), indent=4))
Pablo Galindo114081f2020-03-02 03:14:06 +00001372 Module(
1373 body=[
1374 Expr(
1375 value=Yield(
1376 value=Name(id='x', ctx=Load())))],
1377 type_ignores=[])
1378
Pablo Galindo02f64cb2020-03-07 18:22:58 +00001379 >>> print(ast.dump(ast.parse('yield from x'), indent=4))
Pablo Galindo114081f2020-03-02 03:14:06 +00001380 Module(
1381 body=[
1382 Expr(
1383 value=YieldFrom(
1384 value=Name(id='x', ctx=Load())))],
1385 type_ignores=[])
1386
1387
1388.. class:: Global(names)
1389 Nonlocal(names)
1390
1391 ``global`` and ``nonlocal`` statements. ``names`` is a list of raw strings.
1392
1393 .. doctest::
1394
Pablo Galindo02f64cb2020-03-07 18:22:58 +00001395 >>> print(ast.dump(ast.parse('global x,y,z'), indent=4))
Pablo Galindo114081f2020-03-02 03:14:06 +00001396 Module(
1397 body=[
1398 Global(
1399 names=[
1400 'x',
1401 'y',
1402 'z'])],
1403 type_ignores=[])
1404
Pablo Galindo02f64cb2020-03-07 18:22:58 +00001405 >>> print(ast.dump(ast.parse('nonlocal x,y,z'), indent=4))
Pablo Galindo114081f2020-03-02 03:14:06 +00001406 Module(
1407 body=[
1408 Nonlocal(
1409 names=[
1410 'x',
1411 'y',
1412 'z'])],
1413 type_ignores=[])
1414
1415
1416.. class:: ClassDef(name, bases, keywords, starargs, kwargs, body, decorator_list)
1417
1418 A class definition.
1419
1420 * ``name`` is a raw string for the class name
1421 * ``bases`` is a list of nodes for explicitly specified base classes.
1422 * ``keywords`` is a list of :class:`keyword` nodes, principally for 'metaclass'.
1423 Other keywords will be passed to the metaclass, as per `PEP-3115
1424 <http://www.python.org/dev/peps/pep-3115/>`_.
1425 * ``starargs`` and ``kwargs`` are each a single node, as in a function call.
1426 starargs will be expanded to join the list of base classes, and kwargs will
1427 be passed to the metaclass.
1428 * ``body`` is a list of nodes representing the code within the class
1429 definition.
1430 * ``decorator_list`` is a list of nodes, as in :class:`FunctionDef`.
1431
1432 .. doctest::
1433
1434 >>> print(ast.dump(ast.parse("""\
1435 ... @decorator1
1436 ... @decorator2
1437 ... class Foo(base1, base2, metaclass=meta):
1438 ... pass
1439 ... """), indent=4))
1440 Module(
1441 body=[
1442 ClassDef(
1443 name='Foo',
1444 bases=[
1445 Name(id='base1', ctx=Load()),
1446 Name(id='base2', ctx=Load())],
1447 keywords=[
1448 keyword(
1449 arg='metaclass',
1450 value=Name(id='meta', ctx=Load()))],
1451 body=[
1452 Pass()],
1453 decorator_list=[
1454 Name(id='decorator1', ctx=Load()),
1455 Name(id='decorator2', ctx=Load())])],
1456 type_ignores=[])
1457
1458Async and await
1459^^^^^^^^^^^^^^^
1460
1461.. class:: AsyncFunctionDef(name, args, body, decorator_list, returns, type_comment)
1462
1463 An ``async def`` function definition. Has the same fields as
1464 :class:`FunctionDef`.
1465
1466
1467.. class:: Await(value)
1468
1469 An ``await`` expression. ``value`` is what it waits for.
1470 Only valid in the body of an :class:`AsyncFunctionDef`.
1471
1472.. doctest::
1473
1474 >>> print(ast.dump(ast.parse("""\
1475 ... async def f():
1476 ... await other_func()
1477 ... """), indent=4))
1478 Module(
1479 body=[
1480 AsyncFunctionDef(
1481 name='f',
1482 args=arguments(
1483 posonlyargs=[],
1484 args=[],
Pablo Galindo114081f2020-03-02 03:14:06 +00001485 kwonlyargs=[],
1486 kw_defaults=[],
Pablo Galindo114081f2020-03-02 03:14:06 +00001487 defaults=[]),
1488 body=[
1489 Expr(
1490 value=Await(
1491 value=Call(
1492 func=Name(id='other_func', ctx=Load()),
1493 args=[],
1494 keywords=[])))],
Serhiy Storchakab7e95252020-03-10 00:07:47 +02001495 decorator_list=[])],
Pablo Galindo114081f2020-03-02 03:14:06 +00001496 type_ignores=[])
1497
1498
1499.. class:: AsyncFor(target, iter, body, orelse, type_comment)
1500 AsyncWith(items, body, type_comment)
1501
1502 ``async for`` loops and ``async with`` context managers. They have the same
1503 fields as :class:`For` and :class:`With`, respectively. Only valid in the
1504 body of an :class:`AsyncFunctionDef`.
Georg Brandl0c77a822008-06-10 16:37:50 +00001505
1506
1507:mod:`ast` Helpers
1508------------------
1509
Martin Panter2e4571a2015-11-14 01:07:43 +00001510Apart from the node classes, the :mod:`ast` module defines these utility functions
Georg Brandl0c77a822008-06-10 16:37:50 +00001511and classes for traversing abstract syntax trees:
1512
Guido van Rossum10b55c12019-06-11 17:23:12 -07001513.. function:: parse(source, filename='<unknown>', mode='exec', *, type_comments=False, feature_version=None)
Georg Brandl0c77a822008-06-10 16:37:50 +00001514
Terry Reedyfeac6242011-01-24 21:36:03 +00001515 Parse the source into an AST node. Equivalent to ``compile(source,
Benjamin Petersonec9199b2008-11-08 17:05:00 +00001516 filename, mode, ast.PyCF_ONLY_AST)``.
Georg Brandl0c77a822008-06-10 16:37:50 +00001517
Guido van Rossumdcfcd142019-01-31 03:40:27 -08001518 If ``type_comments=True`` is given, the parser is modified to check
1519 and return type comments as specified by :pep:`484` and :pep:`526`.
1520 This is equivalent to adding :data:`ast.PyCF_TYPE_COMMENTS` to the
1521 flags passed to :func:`compile()`. This will report syntax errors
1522 for misplaced type comments. Without this flag, type comments will
1523 be ignored, and the ``type_comment`` field on selected AST nodes
1524 will always be ``None``. In addition, the locations of ``# type:
1525 ignore`` comments will be returned as the ``type_ignores``
1526 attribute of :class:`Module` (otherwise it is always an empty list).
1527
1528 In addition, if ``mode`` is ``'func_type'``, the input syntax is
1529 modified to correspond to :pep:`484` "signature type comments",
1530 e.g. ``(str, int) -> List[str]``.
1531
Guido van Rossum10b55c12019-06-11 17:23:12 -07001532 Also, setting ``feature_version`` to a tuple ``(major, minor)``
1533 will attempt to parse using that Python version's grammar.
1534 Currently ``major`` must equal to ``3``. For example, setting
1535 ``feature_version=(3, 4)`` will allow the use of ``async`` and
1536 ``await`` as variable names. The lowest supported version is
1537 ``(3, 4)``; the highest is ``sys.version_info[0:2]``.
Guido van Rossum495da292019-03-07 12:38:08 -08001538
Brett Cannon7a7f1002018-03-09 12:03:22 -08001539 .. warning::
1540 It is possible to crash the Python interpreter with a
1541 sufficiently large/complex string due to stack depth limitations
1542 in Python's AST compiler.
1543
Guido van Rossumdcfcd142019-01-31 03:40:27 -08001544 .. versionchanged:: 3.8
Guido van Rossum495da292019-03-07 12:38:08 -08001545 Added ``type_comments``, ``mode='func_type'`` and ``feature_version``.
Guido van Rossumdcfcd142019-01-31 03:40:27 -08001546
Georg Brandl48310cd2009-01-03 21:18:54 +00001547
Pablo Galindo27fc3b62019-11-24 23:02:40 +00001548.. function:: unparse(ast_obj)
1549
1550 Unparse an :class:`ast.AST` object and generate a string with code
1551 that would produce an equivalent :class:`ast.AST` object if parsed
1552 back with :func:`ast.parse`.
1553
1554 .. warning::
Gurupad Hegde6c7bb382019-12-28 17:16:02 -05001555 The produced code string will not necessarily be equal to the original
Pablo Galindo6e399992020-06-28 02:22:30 +01001556 code that generated the :class:`ast.AST` object (without any compiler
1557 optimizations, such as constant tuples/frozensets).
1558
1559 .. warning::
1560 Trying to unparse a highly complex expression would result with
1561 :exc:`RecursionError`.
Pablo Galindo27fc3b62019-11-24 23:02:40 +00001562
1563 .. versionadded:: 3.9
1564
1565
Georg Brandl0c77a822008-06-10 16:37:50 +00001566.. function:: literal_eval(node_or_string)
1567
Georg Brandlb9b389e2014-11-05 20:20:28 +01001568 Safely evaluate an expression node or a string containing a Python literal or
1569 container display. The string or node provided may only consist of the
1570 following Python literal structures: strings, bytes, numbers, tuples, lists,
1571 dicts, sets, booleans, and ``None``.
Georg Brandl0c77a822008-06-10 16:37:50 +00001572
Georg Brandlb9b389e2014-11-05 20:20:28 +01001573 This can be used for safely evaluating strings containing Python values from
1574 untrusted sources without the need to parse the values oneself. It is not
1575 capable of evaluating arbitrarily complex expressions, for example involving
1576 operators or indexing.
Georg Brandl0c77a822008-06-10 16:37:50 +00001577
Brett Cannon7a7f1002018-03-09 12:03:22 -08001578 .. warning::
1579 It is possible to crash the Python interpreter with a
1580 sufficiently large/complex string due to stack depth limitations
1581 in Python's AST compiler.
1582
Georg Brandl492f3fc2010-07-11 09:41:21 +00001583 .. versionchanged:: 3.2
Georg Brandl85f21772010-07-13 06:38:10 +00001584 Now allows bytes and set literals.
Georg Brandl492f3fc2010-07-11 09:41:21 +00001585
Raymond Hettinger4fcf5c12020-01-02 22:21:18 -07001586 .. versionchanged:: 3.9
1587 Now supports creating empty sets with ``'set()'``.
1588
Georg Brandl0c77a822008-06-10 16:37:50 +00001589
Amaury Forgeot d'Arcfdfe62d2008-06-17 20:36:03 +00001590.. function:: get_docstring(node, clean=True)
Georg Brandl0c77a822008-06-10 16:37:50 +00001591
1592 Return the docstring of the given *node* (which must be a
INADA Naokicb41b272017-02-23 00:31:59 +09001593 :class:`FunctionDef`, :class:`AsyncFunctionDef`, :class:`ClassDef`,
1594 or :class:`Module` node), or ``None`` if it has no docstring.
1595 If *clean* is true, clean up the docstring's indentation with
1596 :func:`inspect.cleandoc`.
1597
1598 .. versionchanged:: 3.5
1599 :class:`AsyncFunctionDef` is now supported.
1600
Georg Brandl0c77a822008-06-10 16:37:50 +00001601
Ivan Levkivskyi9932a222019-01-22 11:18:22 +00001602.. function:: get_source_segment(source, node, *, padded=False)
1603
1604 Get source code segment of the *source* that generated *node*.
1605 If some location information (:attr:`lineno`, :attr:`end_lineno`,
1606 :attr:`col_offset`, or :attr:`end_col_offset`) is missing, return ``None``.
1607
1608 If *padded* is ``True``, the first line of a multi-line statement will
1609 be padded with spaces to match its original position.
1610
1611 .. versionadded:: 3.8
1612
1613
Georg Brandl0c77a822008-06-10 16:37:50 +00001614.. function:: fix_missing_locations(node)
1615
1616 When you compile a node tree with :func:`compile`, the compiler expects
1617 :attr:`lineno` and :attr:`col_offset` attributes for every node that supports
1618 them. This is rather tedious to fill in for generated nodes, so this helper
1619 adds these attributes recursively where not already set, by setting them to
1620 the values of the parent node. It works recursively starting at *node*.
1621
1622
1623.. function:: increment_lineno(node, n=1)
1624
Ivan Levkivskyi9932a222019-01-22 11:18:22 +00001625 Increment the line number and end line number of each node in the tree
1626 starting at *node* by *n*. This is useful to "move code" to a different
1627 location in a file.
Georg Brandl0c77a822008-06-10 16:37:50 +00001628
1629
1630.. function:: copy_location(new_node, old_node)
1631
Ivan Levkivskyi9932a222019-01-22 11:18:22 +00001632 Copy source location (:attr:`lineno`, :attr:`col_offset`, :attr:`end_lineno`,
1633 and :attr:`end_col_offset`) from *old_node* to *new_node* if possible,
1634 and return *new_node*.
Georg Brandl0c77a822008-06-10 16:37:50 +00001635
1636
1637.. function:: iter_fields(node)
1638
1639 Yield a tuple of ``(fieldname, value)`` for each field in ``node._fields``
1640 that is present on *node*.
1641
1642
1643.. function:: iter_child_nodes(node)
1644
1645 Yield all direct child nodes of *node*, that is, all fields that are nodes
1646 and all items of fields that are lists of nodes.
1647
1648
1649.. function:: walk(node)
1650
Georg Brandl619e7ba2011-01-09 07:38:51 +00001651 Recursively yield all descendant nodes in the tree starting at *node*
1652 (including *node* itself), in no specified order. This is useful if you only
1653 want to modify nodes in place and don't care about the context.
Georg Brandl0c77a822008-06-10 16:37:50 +00001654
1655
1656.. class:: NodeVisitor()
1657
1658 A node visitor base class that walks the abstract syntax tree and calls a
1659 visitor function for every node found. This function may return a value
Georg Brandl36ab1ef2009-01-03 21:17:04 +00001660 which is forwarded by the :meth:`visit` method.
Georg Brandl0c77a822008-06-10 16:37:50 +00001661
1662 This class is meant to be subclassed, with the subclass adding visitor
1663 methods.
1664
1665 .. method:: visit(node)
1666
1667 Visit a node. The default implementation calls the method called
1668 :samp:`self.visit_{classname}` where *classname* is the name of the node
1669 class, or :meth:`generic_visit` if that method doesn't exist.
1670
1671 .. method:: generic_visit(node)
1672
1673 This visitor calls :meth:`visit` on all children of the node.
Georg Brandl48310cd2009-01-03 21:18:54 +00001674
Georg Brandl0c77a822008-06-10 16:37:50 +00001675 Note that child nodes of nodes that have a custom visitor method won't be
1676 visited unless the visitor calls :meth:`generic_visit` or visits them
1677 itself.
1678
1679 Don't use the :class:`NodeVisitor` if you want to apply changes to nodes
1680 during traversal. For this a special visitor exists
1681 (:class:`NodeTransformer`) that allows modifications.
1682
Serhiy Storchakac3ea41e2019-08-26 10:13:19 +03001683 .. deprecated:: 3.8
1684
1685 Methods :meth:`visit_Num`, :meth:`visit_Str`, :meth:`visit_Bytes`,
1686 :meth:`visit_NameConstant` and :meth:`visit_Ellipsis` are deprecated
1687 now and will not be called in future Python versions. Add the
1688 :meth:`visit_Constant` method to handle all constant nodes.
1689
Georg Brandl0c77a822008-06-10 16:37:50 +00001690
1691.. class:: NodeTransformer()
1692
1693 A :class:`NodeVisitor` subclass that walks the abstract syntax tree and
1694 allows modification of nodes.
1695
Georg Brandl36ab1ef2009-01-03 21:17:04 +00001696 The :class:`NodeTransformer` will walk the AST and use the return value of
1697 the visitor methods to replace or remove the old node. If the return value
1698 of the visitor method is ``None``, the node will be removed from its
1699 location, otherwise it is replaced with the return value. The return value
1700 may be the original node in which case no replacement takes place.
Georg Brandl0c77a822008-06-10 16:37:50 +00001701
1702 Here is an example transformer that rewrites all occurrences of name lookups
1703 (``foo``) to ``data['foo']``::
1704
1705 class RewriteName(NodeTransformer):
1706
1707 def visit_Name(self, node):
Batuhan Taşkaya6680f4a2020-01-12 23:38:53 +03001708 return Subscript(
Georg Brandl0c77a822008-06-10 16:37:50 +00001709 value=Name(id='data', ctx=Load()),
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02001710 slice=Constant(value=node.id),
Georg Brandl0c77a822008-06-10 16:37:50 +00001711 ctx=node.ctx
Pablo Galindoc00c86b2020-03-12 00:48:19 +00001712 )
Georg Brandl0c77a822008-06-10 16:37:50 +00001713
1714 Keep in mind that if the node you're operating on has child nodes you must
1715 either transform the child nodes yourself or call the :meth:`generic_visit`
1716 method for the node first.
1717
1718 For nodes that were part of a collection of statements (that applies to all
1719 statement nodes), the visitor may also return a list of nodes rather than
1720 just a single node.
1721
Batuhan Taşkaya6680f4a2020-01-12 23:38:53 +03001722 If :class:`NodeTransformer` introduces new nodes (that weren't part of
1723 original tree) without giving them location information (such as
1724 :attr:`lineno`), :func:`fix_missing_locations` should be called with
1725 the new sub-tree to recalculate the location information::
1726
1727 tree = ast.parse('foo', mode='eval')
1728 new_tree = fix_missing_locations(RewriteName().visit(tree))
1729
Georg Brandl0c77a822008-06-10 16:37:50 +00001730 Usually you use the transformer like this::
1731
1732 node = YourTransformer().visit(node)
1733
1734
Serhiy Storchaka850573b2019-09-09 19:33:13 +03001735.. function:: dump(node, annotate_fields=True, include_attributes=False, *, indent=None)
Georg Brandl0c77a822008-06-10 16:37:50 +00001736
1737 Return a formatted dump of the tree in *node*. This is mainly useful for
Serhiy Storchakae64f9482019-08-29 09:30:23 +03001738 debugging purposes. If *annotate_fields* is true (by default),
1739 the returned string will show the names and the values for fields.
1740 If *annotate_fields* is false, the result string will be more compact by
1741 omitting unambiguous field names. Attributes such as line
Benjamin Petersondcf97b92008-07-02 17:30:14 +00001742 numbers and column offsets are not dumped by default. If this is wanted,
Serhiy Storchakae64f9482019-08-29 09:30:23 +03001743 *include_attributes* can be set to true.
Senthil Kumaranf3695bf2016-01-06 21:26:53 -08001744
Serhiy Storchaka850573b2019-09-09 19:33:13 +03001745 If *indent* is a non-negative integer or string, then the tree will be
1746 pretty-printed with that indent level. An indent level
1747 of 0, negative, or ``""`` will only insert newlines. ``None`` (the default)
1748 selects the single line representation. Using a positive integer indent
1749 indents that many spaces per level. If *indent* is a string (such as ``"\t"``),
1750 that string is used to indent each level.
1751
1752 .. versionchanged:: 3.9
1753 Added the *indent* option.
1754
1755
Serhiy Storchaka832e8642019-09-09 23:36:13 +03001756.. _ast-cli:
1757
1758Command-Line Usage
1759------------------
1760
1761.. versionadded:: 3.9
1762
1763The :mod:`ast` module can be executed as a script from the command line.
1764It is as simple as:
1765
1766.. code-block:: sh
1767
1768 python -m ast [-m <mode>] [-a] [infile]
1769
1770The following options are accepted:
1771
1772.. program:: ast
1773
1774.. cmdoption:: -h, --help
1775
1776 Show the help message and exit.
1777
1778.. cmdoption:: -m <mode>
1779 --mode <mode>
1780
1781 Specify what kind of code must be compiled, like the *mode* argument
1782 in :func:`parse`.
1783
Batuhan Taşkaya814d6872019-12-16 21:23:27 +03001784.. cmdoption:: --no-type-comments
1785
1786 Don't parse type comments.
1787
Serhiy Storchaka832e8642019-09-09 23:36:13 +03001788.. cmdoption:: -a, --include-attributes
1789
1790 Include attributes such as line numbers and column offsets.
1791
Batuhan Taşkaya814d6872019-12-16 21:23:27 +03001792.. cmdoption:: -i <indent>
1793 --indent <indent>
1794
1795 Indentation of nodes in AST (number of spaces).
1796
Serhiy Storchaka832e8642019-09-09 23:36:13 +03001797If :file:`infile` is specified its contents are parsed to AST and dumped
1798to stdout. Otherwise, the content is read from stdin.
1799
1800
Senthil Kumaranf3695bf2016-01-06 21:26:53 -08001801.. seealso::
1802
Sanyam Khurana338cd832018-01-20 05:55:37 +05301803 `Green Tree Snakes <https://greentreesnakes.readthedocs.io/>`_, an external documentation resource, has good
Senthil Kumaranf3695bf2016-01-06 21:26:53 -08001804 details on working with Python ASTs.