blob: aaedfbe1b9c013440e676543053f8d620a46ae11 [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
143
Pablo Galindo114081f2020-03-02 03:14:06 +0000144Literals
145^^^^^^^^
Georg Brandl0c77a822008-06-10 16:37:50 +0000146
Pablo Galindo114081f2020-03-02 03:14:06 +0000147.. class:: Constant(value)
Georg Brandl0c77a822008-06-10 16:37:50 +0000148
Pablo Galindo114081f2020-03-02 03:14:06 +0000149 A constant value. The ``value`` attribute of the ``Constant`` literal contains the
150 Python object it represents. The values represented can be simple types
151 such as a number, string or ``None``, but also immutable container types
152 (tuples and frozensets) if all of their elements are constant.
Georg Brandl0c77a822008-06-10 16:37:50 +0000153
Pablo Galindo114081f2020-03-02 03:14:06 +0000154 .. doctest::
Georg Brandl0c77a822008-06-10 16:37:50 +0000155
Pablo Galindo02f64cb2020-03-07 18:22:58 +0000156 >>> print(ast.dump(ast.parse('123', mode='eval'), indent=4))
157 Expression(
Serhiy Storchakab7e95252020-03-10 00:07:47 +0200158 body=Constant(value=123))
Pablo Galindo114081f2020-03-02 03:14:06 +0000159
160
161.. class:: FormattedValue(value, conversion, format_spec)
162
163 Node representing a single formatting field in an f-string. If the string
164 contains a single formatting field and nothing else the node can be
165 isolated otherwise it appears in :class:`JoinedStr`.
166
167 * ``value`` is any expression node (such as a literal, a variable, or a
168 function call).
169 * ``conversion`` is an integer:
170
171 * -1: no formatting
172 * 115: ``!s`` string formatting
173 * 114: ``!r`` repr formatting
174 * 97: ``!a`` ascii formatting
175
176 * ``format_spec`` is a :class:`JoinedStr` node representing the formatting
177 of the value, or ``None`` if no format was specified. Both
178 ``conversion`` and ``format_spec`` can be set at the same time.
179
180
181.. class:: JoinedStr(values)
182
183 An f-string, comprising a series of :class:`FormattedValue` and :class:`Constant`
184 nodes.
185
186 .. doctest::
187
Pablo Galindo02f64cb2020-03-07 18:22:58 +0000188 >>> print(ast.dump(ast.parse('f"sin({a}) is {sin(a):.3}"', mode='eval'), indent=4))
189 Expression(
190 body=JoinedStr(
191 values=[
Serhiy Storchakab7e95252020-03-10 00:07:47 +0200192 Constant(value='sin('),
Pablo Galindo02f64cb2020-03-07 18:22:58 +0000193 FormattedValue(
194 value=Name(id='a', ctx=Load()),
Serhiy Storchakab7e95252020-03-10 00:07:47 +0200195 conversion=-1),
196 Constant(value=') is '),
Pablo Galindo02f64cb2020-03-07 18:22:58 +0000197 FormattedValue(
198 value=Call(
199 func=Name(id='sin', ctx=Load()),
200 args=[
201 Name(id='a', ctx=Load())],
202 keywords=[]),
203 conversion=-1,
204 format_spec=JoinedStr(
205 values=[
Serhiy Storchakab7e95252020-03-10 00:07:47 +0200206 Constant(value='.3')]))]))
Pablo Galindo114081f2020-03-02 03:14:06 +0000207
208
209.. class:: List(elts, ctx)
210 Tuple(elts, ctx)
211
212 A list or tuple. ``elts`` holds a list of nodes representing the elements.
213 ``ctx`` is :class:`Store` if the container is an assignment target (i.e.
214 ``(x,y)=something``), and :class:`Load` otherwise.
215
216 .. doctest::
217
Pablo Galindo02f64cb2020-03-07 18:22:58 +0000218 >>> print(ast.dump(ast.parse('[1, 2, 3]', mode='eval'), indent=4))
219 Expression(
220 body=List(
221 elts=[
Serhiy Storchakab7e95252020-03-10 00:07:47 +0200222 Constant(value=1),
223 Constant(value=2),
224 Constant(value=3)],
Pablo Galindo02f64cb2020-03-07 18:22:58 +0000225 ctx=Load()))
226 >>> print(ast.dump(ast.parse('(1, 2, 3)', mode='eval'), indent=4))
227 Expression(
228 body=Tuple(
229 elts=[
Serhiy Storchakab7e95252020-03-10 00:07:47 +0200230 Constant(value=1),
231 Constant(value=2),
232 Constant(value=3)],
Pablo Galindo02f64cb2020-03-07 18:22:58 +0000233 ctx=Load()))
Pablo Galindo114081f2020-03-02 03:14:06 +0000234
235
236.. class:: Set(elts)
237
238 A set. ``elts`` holds a list of nodes representing the set's elements.
239
240 .. doctest::
241
Pablo Galindo02f64cb2020-03-07 18:22:58 +0000242 >>> print(ast.dump(ast.parse('{1, 2, 3}', mode='eval'), indent=4))
243 Expression(
244 body=Set(
245 elts=[
Serhiy Storchakab7e95252020-03-10 00:07:47 +0200246 Constant(value=1),
247 Constant(value=2),
248 Constant(value=3)]))
Pablo Galindo114081f2020-03-02 03:14:06 +0000249
250
251.. class:: Dict(keys, values)
252
253 A dictionary. ``keys`` and ``values`` hold lists of nodes representing the
254 keys and the values respectively, in matching order (what would be returned
255 when calling :code:`dictionary.keys()` and :code:`dictionary.values()`).
256
257 When doing dictionary unpacking using dictionary literals the expression to be
258 expanded goes in the ``values`` list, with a ``None`` at the corresponding
259 position in ``keys``.
260
261 .. doctest::
262
Pablo Galindo02f64cb2020-03-07 18:22:58 +0000263 >>> print(ast.dump(ast.parse('{"a":1, **d}', mode='eval'), indent=4))
264 Expression(
265 body=Dict(
266 keys=[
Serhiy Storchakab7e95252020-03-10 00:07:47 +0200267 Constant(value='a'),
Pablo Galindo02f64cb2020-03-07 18:22:58 +0000268 None],
269 values=[
Serhiy Storchakab7e95252020-03-10 00:07:47 +0200270 Constant(value=1),
Pablo Galindo02f64cb2020-03-07 18:22:58 +0000271 Name(id='d', ctx=Load())]))
Pablo Galindo114081f2020-03-02 03:14:06 +0000272
273
274Variables
275^^^^^^^^^
276
277.. class:: Name(id, ctx)
278
279 A variable name. ``id`` holds the name as a string, and ``ctx`` is one of
280 the following types.
281
282
283.. class:: Load()
284 Store()
285 Del()
286
287 Variable references can be used to load the value of a variable, to assign
288 a new value to it, or to delete it. Variable references are given a context
289 to distinguish these cases.
290
291 .. doctest::
292
293 >>> print(ast.dump(ast.parse('a'), indent=4))
294 Module(
295 body=[
296 Expr(
297 value=Name(id='a', ctx=Load()))],
298 type_ignores=[])
299
300 >>> print(ast.dump(ast.parse('a = 1'), indent=4))
301 Module(
302 body=[
303 Assign(
304 targets=[
305 Name(id='a', ctx=Store())],
Serhiy Storchakab7e95252020-03-10 00:07:47 +0200306 value=Constant(value=1))],
Pablo Galindo114081f2020-03-02 03:14:06 +0000307 type_ignores=[])
308
309 >>> print(ast.dump(ast.parse('del a'), indent=4))
310 Module(
311 body=[
312 Delete(
313 targets=[
314 Name(id='a', ctx=Del())])],
315 type_ignores=[])
316
317
318.. class:: Starred(value, ctx)
319
320 A ``*var`` variable reference. ``value`` holds the variable, typically a
321 :class:`Name` node. This type must be used when building a :class:`Call`
322 node with ``*args``.
323
324 .. doctest::
325
326 >>> print(ast.dump(ast.parse('a, *b = it'), indent=4))
327 Module(
328 body=[
329 Assign(
330 targets=[
331 Tuple(
332 elts=[
333 Name(id='a', ctx=Store()),
334 Starred(
335 value=Name(id='b', ctx=Store()),
336 ctx=Store())],
337 ctx=Store())],
Serhiy Storchakab7e95252020-03-10 00:07:47 +0200338 value=Name(id='it', ctx=Load()))],
Pablo Galindo114081f2020-03-02 03:14:06 +0000339 type_ignores=[])
340
341
342Expressions
343^^^^^^^^^^^
344
345.. class:: Expr(value)
346
347 When an expression, such as a function call, appears as a statement by itself
348 with its return value not used or stored, it is wrapped in this container.
349 ``value`` holds one of the other nodes in this section, a :class:`Constant`, a
350 :class:`Name`, a :class:`Lambda`, a :class:`Yield` or :class:`YieldFrom` node.
351
352 .. doctest::
353
354 >>> print(ast.dump(ast.parse('-a'), indent=4))
355 Module(
356 body=[
357 Expr(
358 value=UnaryOp(
359 op=USub(),
360 operand=Name(id='a', ctx=Load())))],
361 type_ignores=[])
362
363
364.. class:: UnaryOp(op, operand)
365
366 A unary operation. ``op`` is the operator, and ``operand`` any expression
367 node.
368
369
370.. class:: UAdd
371 USub
372 Not
373 Invert
374
375 Unary operator tokens. :class:`Not` is the ``not`` keyword, :class:`Invert`
376 is the ``~`` operator.
377
378 .. doctest::
379
Pablo Galindo02f64cb2020-03-07 18:22:58 +0000380 >>> print(ast.dump(ast.parse('not x', mode='eval'), indent=4))
381 Expression(
382 body=UnaryOp(
383 op=Not(),
384 operand=Name(id='x', ctx=Load())))
Pablo Galindo114081f2020-03-02 03:14:06 +0000385
386
387.. class:: BinOp(left, op, right)
388
389 A binary operation (like addition or division). ``op`` is the operator, and
390 ``left`` and ``right`` are any expression nodes.
391
392 .. doctest::
393
Pablo Galindo02f64cb2020-03-07 18:22:58 +0000394 >>> print(ast.dump(ast.parse('x + y', mode='eval'), indent=4))
395 Expression(
396 body=BinOp(
397 left=Name(id='x', ctx=Load()),
398 op=Add(),
399 right=Name(id='y', ctx=Load())))
Pablo Galindo114081f2020-03-02 03:14:06 +0000400
401
402.. class:: Add
403 Sub
404 Mult
405 Div
406 FloorDiv
407 Mod
408 Pow
409 LShift
410 RShift
411 BitOr
412 BitXor
413 BitAnd
414 MatMult
415
416 Binary operator tokens.
417
418
419.. class:: BoolOp(op, values)
420
421 A boolean operation, 'or' or 'and'. ``op`` is :class:`Or` or :class:`And`.
422 ``values`` are the values involved. Consecutive operations with the same
423 operator, such as ``a or b or c``, are collapsed into one node with several
424 values.
425
426 This doesn't include ``not``, which is a :class:`UnaryOp`.
427
428 .. doctest::
429
Pablo Galindo02f64cb2020-03-07 18:22:58 +0000430 >>> print(ast.dump(ast.parse('x or y', mode='eval'), indent=4))
431 Expression(
432 body=BoolOp(
433 op=Or(),
434 values=[
435 Name(id='x', ctx=Load()),
436 Name(id='y', ctx=Load())]))
Pablo Galindo114081f2020-03-02 03:14:06 +0000437
438
439.. class:: And
440 Or
441
442 Boolean operator tokens.
443
444
445.. class:: Compare(left, ops, comparators)
446
447 A comparison of two or more values. ``left`` is the first value in the
448 comparison, ``ops`` the list of operators, and ``comparators`` the list
449 of values after the first element in the comparison.
450
451 .. doctest::
452
Pablo Galindo02f64cb2020-03-07 18:22:58 +0000453 >>> print(ast.dump(ast.parse('1 <= a < 10', mode='eval'), indent=4))
454 Expression(
455 body=Compare(
Serhiy Storchakab7e95252020-03-10 00:07:47 +0200456 left=Constant(value=1),
Pablo Galindo02f64cb2020-03-07 18:22:58 +0000457 ops=[
458 LtE(),
459 Lt()],
460 comparators=[
461 Name(id='a', ctx=Load()),
Serhiy Storchakab7e95252020-03-10 00:07:47 +0200462 Constant(value=10)]))
Pablo Galindo114081f2020-03-02 03:14:06 +0000463
464
465.. class:: Eq
466 NotEq
467 Lt
468 LtE
469 Gt
470 GtE
471 Is
472 IsNot
473 In
474 NotIn
475
476 Comparison operator tokens.
477
478
479.. class:: Call(func, args, keywords, starargs, kwargs)
480
481 A function call. ``func`` is the function, which will often be a
482 :class:`Name` or :class:`Attribute` object. Of the arguments:
483
484 * ``args`` holds a list of the arguments passed by position.
485 * ``keywords`` holds a list of :class:`keyword` objects representing
486 arguments passed by keyword.
487
488 When creating a ``Call`` node, ``args`` and ``keywords`` are required, but
489 they can be empty lists. ``starargs`` and ``kwargs`` are optional.
490
491 .. doctest::
492
Pablo Galindo02f64cb2020-03-07 18:22:58 +0000493 >>> print(ast.dump(ast.parse('func(a, b=c, *d, **e)', mode='eval'), indent=4))
494 Expression(
495 body=Call(
496 func=Name(id='func', ctx=Load()),
497 args=[
498 Name(id='a', ctx=Load()),
499 Starred(
500 value=Name(id='d', ctx=Load()),
501 ctx=Load())],
502 keywords=[
503 keyword(
504 arg='b',
505 value=Name(id='c', ctx=Load())),
506 keyword(
Pablo Galindo02f64cb2020-03-07 18:22:58 +0000507 value=Name(id='e', ctx=Load()))]))
Pablo Galindo114081f2020-03-02 03:14:06 +0000508
509
510.. class:: keyword(arg, value)
511
512 A keyword argument to a function call or class definition. ``arg`` is a raw
513 string of the parameter name, ``value`` is a node to pass in.
514
515
516.. class:: IfExp(test, body, orelse)
517
518 An expression such as ``a if b else c``. Each field holds a single node, so
519 in the following example, all three are :class:`Name` nodes.
520
521 .. doctest::
522
Pablo Galindo02f64cb2020-03-07 18:22:58 +0000523 >>> print(ast.dump(ast.parse('a if b else c', mode='eval'), indent=4))
524 Expression(
525 body=IfExp(
526 test=Name(id='b', ctx=Load()),
527 body=Name(id='a', ctx=Load()),
528 orelse=Name(id='c', ctx=Load())))
Pablo Galindo114081f2020-03-02 03:14:06 +0000529
530
531.. class:: Attribute(value, attr, ctx)
532
533 Attribute access, e.g. ``d.keys``. ``value`` is a node, typically a
534 :class:`Name`. ``attr`` is a bare string giving the name of the attribute,
535 and ``ctx`` is :class:`Load`, :class:`Store` or :class:`Del` according to how
536 the attribute is acted on.
537
538 .. doctest::
539
Pablo Galindo02f64cb2020-03-07 18:22:58 +0000540 >>> print(ast.dump(ast.parse('snake.colour', mode='eval'), indent=4))
541 Expression(
542 body=Attribute(
543 value=Name(id='snake', ctx=Load()),
544 attr='colour',
545 ctx=Load()))
Pablo Galindo114081f2020-03-02 03:14:06 +0000546
547
548.. class:: NamedExpr(target, value)
549
550 A named expression. This AST node is produced by the assignment expressions
551 operator (also known as the walrus operator). As opposed to the :class:`Assign`
552 node in which the first argument can be multiple nodes, in this case both
553 ``target`` and ``value`` must be single nodes.
554
555 .. doctest::
556
Pablo Galindo02f64cb2020-03-07 18:22:58 +0000557 >>> print(ast.dump(ast.parse('(x := 4)', mode='eval'), indent=4))
558 Expression(
559 body=NamedExpr(
560 target=Name(id='x', ctx=Store()),
Serhiy Storchakab7e95252020-03-10 00:07:47 +0200561 value=Constant(value=4)))
Pablo Galindo114081f2020-03-02 03:14:06 +0000562
563
564Subscripting
565~~~~~~~~~~~~
566
567.. class:: Subscript(value, slice, ctx)
568
Serhiy Storchaka13d52c22020-03-10 18:52:34 +0200569 A subscript, such as ``l[1]``. ``value`` is the subscripted object
570 (usually sequence or mapping). ``slice`` is an index, slice or key.
571 It can be a :class:`Tuple` and contain a :class:`Slice`.
572 ``ctx`` is :class:`Load`, :class:`Store` or :class:`Del`
Pablo Galindo114081f2020-03-02 03:14:06 +0000573 according to the action performed with the subscript.
574
Pablo Galindo114081f2020-03-02 03:14:06 +0000575 .. doctest::
576
Serhiy Storchaka13d52c22020-03-10 18:52:34 +0200577 >>> print(ast.dump(ast.parse('l[1:2, 3]', mode='eval'), indent=4))
Pablo Galindo02f64cb2020-03-07 18:22:58 +0000578 Expression(
579 body=Subscript(
580 value=Name(id='l', ctx=Load()),
Serhiy Storchaka13d52c22020-03-10 18:52:34 +0200581 slice=Tuple(
582 elts=[
583 Slice(
584 lower=Constant(value=1),
585 upper=Constant(value=2)),
586 Constant(value=3)],
587 ctx=Load()),
Pablo Galindo02f64cb2020-03-07 18:22:58 +0000588 ctx=Load()))
Pablo Galindo114081f2020-03-02 03:14:06 +0000589
590
591.. class:: Slice(lower, upper, step)
592
Serhiy Storchaka13d52c22020-03-10 18:52:34 +0200593 Regular slicing (on the form ``lower:upper`` or ``lower:upper:step``).
594 Can occur only inside the *slice* field of :class:`Subscript`, either
595 directly or as an element of :class:`Tuple`.
Pablo Galindo114081f2020-03-02 03:14:06 +0000596
597 .. doctest::
598
Pablo Galindo02f64cb2020-03-07 18:22:58 +0000599 >>> print(ast.dump(ast.parse('l[1:2]', mode='eval'), indent=4))
600 Expression(
601 body=Subscript(
602 value=Name(id='l', ctx=Load()),
603 slice=Slice(
Serhiy Storchakab7e95252020-03-10 00:07:47 +0200604 lower=Constant(value=1),
605 upper=Constant(value=2)),
Pablo Galindo02f64cb2020-03-07 18:22:58 +0000606 ctx=Load()))
Pablo Galindo114081f2020-03-02 03:14:06 +0000607
608
Pablo Galindo114081f2020-03-02 03:14:06 +0000609Comprehensions
610~~~~~~~~~~~~~~
611
612.. class:: ListComp(elt, generators)
613 SetComp(elt, generators)
614 GeneratorExp(elt, generators)
615 DictComp(key, value, generators)
616
617 List and set comprehensions, generator expressions, and dictionary
618 comprehensions. ``elt`` (or ``key`` and ``value``) is a single node
619 representing the part that will be evaluated for each item.
620
621 ``generators`` is a list of :class:`comprehension` nodes.
622
623 .. doctest::
624
Pablo Galindo02f64cb2020-03-07 18:22:58 +0000625 >>> print(ast.dump(ast.parse('[x for x in numbers]', mode='eval'), indent=4))
626 Expression(
627 body=ListComp(
628 elt=Name(id='x', ctx=Load()),
629 generators=[
630 comprehension(
631 target=Name(id='x', ctx=Store()),
632 iter=Name(id='numbers', ctx=Load()),
633 ifs=[],
634 is_async=0)]))
635 >>> print(ast.dump(ast.parse('{x: x**2 for x in numbers}', mode='eval'), indent=4))
636 Expression(
637 body=DictComp(
638 key=Name(id='x', ctx=Load()),
639 value=BinOp(
640 left=Name(id='x', ctx=Load()),
641 op=Pow(),
Serhiy Storchakab7e95252020-03-10 00:07:47 +0200642 right=Constant(value=2)),
Pablo Galindo02f64cb2020-03-07 18:22:58 +0000643 generators=[
644 comprehension(
645 target=Name(id='x', ctx=Store()),
646 iter=Name(id='numbers', ctx=Load()),
647 ifs=[],
648 is_async=0)]))
649 >>> print(ast.dump(ast.parse('{x for x in numbers}', mode='eval'), indent=4))
650 Expression(
651 body=SetComp(
652 elt=Name(id='x', ctx=Load()),
653 generators=[
654 comprehension(
655 target=Name(id='x', ctx=Store()),
656 iter=Name(id='numbers', ctx=Load()),
657 ifs=[],
658 is_async=0)]))
Pablo Galindo114081f2020-03-02 03:14:06 +0000659
660
661.. class:: comprehension(target, iter, ifs, is_async)
662
663 One ``for`` clause in a comprehension. ``target`` is the reference to use for
664 each element - typically a :class:`Name` or :class:`Tuple` node. ``iter``
665 is the object to iterate over. ``ifs`` is a list of test expressions: each
666 ``for`` clause can have multiple ``ifs``.
667
668 ``is_async`` indicates a comprehension is asynchronous (using an
669 ``async for`` instead of ``for``). The value is an integer (0 or 1).
670
671 .. doctest::
672
Pablo Galindo02f64cb2020-03-07 18:22:58 +0000673 >>> print(ast.dump(ast.parse('[ord(c) for line in file for c in line]', mode='eval'),
Pablo Galindo114081f2020-03-02 03:14:06 +0000674 ... indent=4)) # Multiple comprehensions in one.
675 Expression(
676 body=ListComp(
677 elt=Call(
678 func=Name(id='ord', ctx=Load()),
679 args=[
680 Name(id='c', ctx=Load())],
681 keywords=[]),
682 generators=[
683 comprehension(
684 target=Name(id='line', ctx=Store()),
685 iter=Name(id='file', ctx=Load()),
686 ifs=[],
687 is_async=0),
688 comprehension(
689 target=Name(id='c', ctx=Store()),
690 iter=Name(id='line', ctx=Load()),
691 ifs=[],
692 is_async=0)]))
693
Pablo Galindo02f64cb2020-03-07 18:22:58 +0000694 >>> 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 +0000695 ... indent=4)) # generator comprehension
696 Expression(
697 body=GeneratorExp(
698 elt=BinOp(
699 left=Name(id='n', ctx=Load()),
700 op=Pow(),
Serhiy Storchakab7e95252020-03-10 00:07:47 +0200701 right=Constant(value=2)),
Pablo Galindo114081f2020-03-02 03:14:06 +0000702 generators=[
703 comprehension(
704 target=Name(id='n', ctx=Store()),
705 iter=Name(id='it', ctx=Load()),
706 ifs=[
707 Compare(
708 left=Name(id='n', ctx=Load()),
709 ops=[
710 Gt()],
711 comparators=[
Serhiy Storchakab7e95252020-03-10 00:07:47 +0200712 Constant(value=5)]),
Pablo Galindo114081f2020-03-02 03:14:06 +0000713 Compare(
714 left=Name(id='n', ctx=Load()),
715 ops=[
716 Lt()],
717 comparators=[
Serhiy Storchakab7e95252020-03-10 00:07:47 +0200718 Constant(value=10)])],
Pablo Galindo114081f2020-03-02 03:14:06 +0000719 is_async=0)]))
720
Pablo Galindo02f64cb2020-03-07 18:22:58 +0000721 >>> print(ast.dump(ast.parse('[i async for i in soc]', mode='eval'),
Pablo Galindo114081f2020-03-02 03:14:06 +0000722 ... indent=4)) # Async comprehension
Pablo Galindo02f64cb2020-03-07 18:22:58 +0000723 Expression(
724 body=ListComp(
725 elt=Name(id='i', ctx=Load()),
726 generators=[
727 comprehension(
728 target=Name(id='i', ctx=Store()),
729 iter=Name(id='soc', ctx=Load()),
730 ifs=[],
731 is_async=1)]))
Pablo Galindo114081f2020-03-02 03:14:06 +0000732
733Statements
734^^^^^^^^^^
735
736.. class:: Assign(targets, value, type_comment)
737
738 An assignment. ``targets`` is a list of nodes, and ``value`` is a single node.
739
740 Multiple nodes in ``targets`` represents assigning the same value to each.
741 Unpacking is represented by putting a :class:`Tuple` or :class:`List`
742 within ``targets``.
743
744 .. attribute:: type_comment
745
746 ``type_comment`` is an optional string with the type annotation as a comment.
747
748 .. doctest::
749
Pablo Galindo02f64cb2020-03-07 18:22:58 +0000750 >>> print(ast.dump(ast.parse('a = b = 1'), indent=4)) # Multiple assignment
Pablo Galindo114081f2020-03-02 03:14:06 +0000751 Module(
752 body=[
753 Assign(
754 targets=[
755 Name(id='a', ctx=Store()),
756 Name(id='b', ctx=Store())],
Serhiy Storchakab7e95252020-03-10 00:07:47 +0200757 value=Constant(value=1))],
Pablo Galindo114081f2020-03-02 03:14:06 +0000758 type_ignores=[])
759
Pablo Galindo02f64cb2020-03-07 18:22:58 +0000760 >>> print(ast.dump(ast.parse('a,b = c'), indent=4)) # Unpacking
Pablo Galindo114081f2020-03-02 03:14:06 +0000761 Module(
762 body=[
763 Assign(
764 targets=[
765 Tuple(
766 elts=[
767 Name(id='a', ctx=Store()),
768 Name(id='b', ctx=Store())],
769 ctx=Store())],
Serhiy Storchakab7e95252020-03-10 00:07:47 +0200770 value=Name(id='c', ctx=Load()))],
Pablo Galindo114081f2020-03-02 03:14:06 +0000771 type_ignores=[])
772
773
774.. class:: AnnAssign(target, annotation, value, simple)
775
776 An assignment with a type annotation. ``target`` is a single node and can
777 be a :class:`Name`, a :class:`Attribute` or a :class:`Subscript`.
778 ``annotation`` is the annotation, such as a :class:`Constant` or :class:`Name`
779 node. ``value`` is a single optional node. ``simple`` is a boolean integer
780 set to True for a :class:`Name` node in ``target`` that do not appear in
781 between parenthesis and are hence pure names and not expressions.
782
783 .. doctest::
784
Pablo Galindo02f64cb2020-03-07 18:22:58 +0000785 >>> print(ast.dump(ast.parse('c: int'), indent=4))
Pablo Galindo114081f2020-03-02 03:14:06 +0000786 Module(
787 body=[
788 AnnAssign(
789 target=Name(id='c', ctx=Store()),
790 annotation=Name(id='int', ctx=Load()),
Pablo Galindo114081f2020-03-02 03:14:06 +0000791 simple=1)],
792 type_ignores=[])
793
Pablo Galindo02f64cb2020-03-07 18:22:58 +0000794 >>> print(ast.dump(ast.parse('(a): int = 1'), indent=4)) # Annotation with parenthesis
Pablo Galindo114081f2020-03-02 03:14:06 +0000795 Module(
796 body=[
797 AnnAssign(
798 target=Name(id='a', ctx=Store()),
799 annotation=Name(id='int', ctx=Load()),
Serhiy Storchakab7e95252020-03-10 00:07:47 +0200800 value=Constant(value=1),
Pablo Galindo114081f2020-03-02 03:14:06 +0000801 simple=0)],
802 type_ignores=[])
803
Pablo Galindo02f64cb2020-03-07 18:22:58 +0000804 >>> print(ast.dump(ast.parse('a.b: int'), indent=4)) # Attribute annotation
Pablo Galindo114081f2020-03-02 03:14:06 +0000805 Module(
806 body=[
807 AnnAssign(
808 target=Attribute(
809 value=Name(id='a', ctx=Load()),
810 attr='b',
811 ctx=Store()),
812 annotation=Name(id='int', ctx=Load()),
Pablo Galindo114081f2020-03-02 03:14:06 +0000813 simple=0)],
814 type_ignores=[])
815
Pablo Galindo02f64cb2020-03-07 18:22:58 +0000816 >>> print(ast.dump(ast.parse('a[1]: int'), indent=4)) # Subscript annotation
Pablo Galindo114081f2020-03-02 03:14:06 +0000817 Module(
818 body=[
819 AnnAssign(
820 target=Subscript(
821 value=Name(id='a', ctx=Load()),
Serhiy Storchaka13d52c22020-03-10 18:52:34 +0200822 slice=Constant(value=1),
Pablo Galindo114081f2020-03-02 03:14:06 +0000823 ctx=Store()),
824 annotation=Name(id='int', ctx=Load()),
Pablo Galindo114081f2020-03-02 03:14:06 +0000825 simple=0)],
826 type_ignores=[])
827
828
829.. class:: AugAssign(target, op, value)
830
831 Augmented assignment, such as ``a += 1``. In the following example,
832 ``target`` is a :class:`Name` node for ``x`` (with the :class:`Store`
833 context), ``op`` is :class:`Add`, and ``value`` is a :class:`Constant` with
834 value for 1.
835
836 The ``target`` attribute connot be of class :class:`Tuple` or :class:`List`,
837 unlike the targets of :class:`Assign`.
838
839 .. doctest::
840
Pablo Galindo02f64cb2020-03-07 18:22:58 +0000841 >>> print(ast.dump(ast.parse('x += 2'), indent=4))
Pablo Galindo114081f2020-03-02 03:14:06 +0000842 Module(
843 body=[
844 AugAssign(
845 target=Name(id='x', ctx=Store()),
846 op=Add(),
Serhiy Storchakab7e95252020-03-10 00:07:47 +0200847 value=Constant(value=2))],
Pablo Galindo114081f2020-03-02 03:14:06 +0000848 type_ignores=[])
849
850
851.. class:: Raise(exc, cause)
852
853 A ``raise`` statement. ``exc`` is the exception object to be raised, normally a
854 :class:`Call` or :class:`Name`, or ``None`` for a standalone ``raise``.
855 ``cause`` is the optional part for ``y`` in ``raise x from y``.
856
857 .. doctest::
858
Pablo Galindo02f64cb2020-03-07 18:22:58 +0000859 >>> print(ast.dump(ast.parse('raise x from y'), indent=4))
Pablo Galindo114081f2020-03-02 03:14:06 +0000860 Module(
861 body=[
862 Raise(
863 exc=Name(id='x', ctx=Load()),
864 cause=Name(id='y', ctx=Load()))],
865 type_ignores=[])
866
867
868.. class:: Assert(test, msg)
869
870 An assertion. ``test`` holds the condition, such as a :class:`Compare` node.
871 ``msg`` holds the failure message.
872
873 .. doctest::
874
Pablo Galindo02f64cb2020-03-07 18:22:58 +0000875 >>> print(ast.dump(ast.parse('assert x,y'), indent=4))
Pablo Galindo114081f2020-03-02 03:14:06 +0000876 Module(
877 body=[
878 Assert(
879 test=Name(id='x', ctx=Load()),
880 msg=Name(id='y', ctx=Load()))],
881 type_ignores=[])
882
883
884.. class:: Delete(targets)
885
886 Represents a ``del`` statement. ``targets`` is a list of nodes, such as
887 :class:`Name`, :class:`Attribute` or :class:`Subscript` nodes.
888
889 .. doctest::
890
Pablo Galindo02f64cb2020-03-07 18:22:58 +0000891 >>> print(ast.dump(ast.parse('del x,y,z'), indent=4))
Pablo Galindo114081f2020-03-02 03:14:06 +0000892 Module(
893 body=[
894 Delete(
895 targets=[
896 Name(id='x', ctx=Del()),
897 Name(id='y', ctx=Del()),
898 Name(id='z', ctx=Del())])],
899 type_ignores=[])
900
901
902.. class:: Pass()
903
904 A ``pass`` statement.
905
906 .. doctest::
907
Pablo Galindo02f64cb2020-03-07 18:22:58 +0000908 >>> print(ast.dump(ast.parse('pass'), indent=4))
Pablo Galindo114081f2020-03-02 03:14:06 +0000909 Module(
910 body=[
911 Pass()],
912 type_ignores=[])
913
914
915Other statements which are only applicable inside functions or loops are
916described in other sections.
917
918Imports
919~~~~~~~
920
921.. class:: Import(names)
922
923 An import statement. ``names`` is a list of :class:`alias` nodes.
924
925 .. doctest::
926
Pablo Galindo02f64cb2020-03-07 18:22:58 +0000927 >>> print(ast.dump(ast.parse('import x,y,z'), indent=4))
Pablo Galindo114081f2020-03-02 03:14:06 +0000928 Module(
929 body=[
930 Import(
931 names=[
Serhiy Storchakab7e95252020-03-10 00:07:47 +0200932 alias(name='x'),
933 alias(name='y'),
934 alias(name='z')])],
Pablo Galindo114081f2020-03-02 03:14:06 +0000935 type_ignores=[])
936
937
938.. class:: ImportFrom(module, names, level)
939
940 Represents ``from x import y``. ``module`` is a raw string of the 'from' name,
941 without any leading dots, or ``None`` for statements such as ``from . import foo``.
942 ``level`` is an integer holding the level of the relative import (0 means
943 absolute import).
944
945 .. doctest::
946
Pablo Galindo02f64cb2020-03-07 18:22:58 +0000947 >>> print(ast.dump(ast.parse('from y import x,y,z'), indent=4))
Pablo Galindo114081f2020-03-02 03:14:06 +0000948 Module(
949 body=[
950 ImportFrom(
951 module='y',
952 names=[
Serhiy Storchakab7e95252020-03-10 00:07:47 +0200953 alias(name='x'),
954 alias(name='y'),
955 alias(name='z')],
Pablo Galindo114081f2020-03-02 03:14:06 +0000956 level=0)],
957 type_ignores=[])
958
959
960.. class:: alias(name, asname)
961
962 Both parameters are raw strings of the names. ``asname`` can be ``None`` if
963 the regular name is to be used.
964
965 .. doctest::
966
Pablo Galindo02f64cb2020-03-07 18:22:58 +0000967 >>> print(ast.dump(ast.parse('from ..foo.bar import a as b, c'), indent=4))
Pablo Galindo114081f2020-03-02 03:14:06 +0000968 Module(
969 body=[
970 ImportFrom(
971 module='foo.bar',
972 names=[
973 alias(name='a', asname='b'),
Serhiy Storchakab7e95252020-03-10 00:07:47 +0200974 alias(name='c')],
Pablo Galindo114081f2020-03-02 03:14:06 +0000975 level=2)],
976 type_ignores=[])
977
978Control flow
979^^^^^^^^^^^^
980
981.. note::
982 Optional clauses such as ``else`` are stored as an empty list if they're
983 not present.
984
985.. class:: If(test, body, orelse)
986
987 An ``if`` statement. ``test`` holds a single node, such as a :class:`Compare`
988 node. ``body`` and ``orelse`` each hold a list of nodes.
989
990 ``elif`` clauses don't have a special representation in the AST, but rather
991 appear as extra :class:`If` nodes within the ``orelse`` section of the
992 previous one.
993
994 .. doctest::
995
996 >>> print(ast.dump(ast.parse("""
997 ... if x:
998 ... ...
999 ... elif y:
1000 ... ...
1001 ... else:
1002 ... ...
1003 ... """), indent=4))
1004 Module(
1005 body=[
1006 If(
1007 test=Name(id='x', ctx=Load()),
1008 body=[
1009 Expr(
Serhiy Storchakab7e95252020-03-10 00:07:47 +02001010 value=Constant(value=Ellipsis))],
Pablo Galindo114081f2020-03-02 03:14:06 +00001011 orelse=[
1012 If(
1013 test=Name(id='y', ctx=Load()),
1014 body=[
1015 Expr(
Serhiy Storchakab7e95252020-03-10 00:07:47 +02001016 value=Constant(value=Ellipsis))],
Pablo Galindo114081f2020-03-02 03:14:06 +00001017 orelse=[
1018 Expr(
Serhiy Storchakab7e95252020-03-10 00:07:47 +02001019 value=Constant(value=Ellipsis))])])],
Pablo Galindo114081f2020-03-02 03:14:06 +00001020 type_ignores=[])
1021
1022
1023.. class:: For(target, iter, body, orelse, type_comment)
1024
1025 A ``for`` loop. ``target`` holds the variable(s) the loop assigns to, as a
1026 single :class:`Name`, :class:`Tuple` or :class:`List` node. ``iter`` holds
1027 the item to be looped over, again as a single node. ``body`` and ``orelse``
1028 contain lists of nodes to execute. Those in ``orelse`` are executed if the
1029 loop finishes normally, rather than via a ``break`` statement.
1030
1031 .. attribute:: type_comment
1032
1033 ``type_comment`` is an optional string with the type annotation as a comment.
1034
1035 .. doctest::
1036
1037 >>> print(ast.dump(ast.parse("""
1038 ... for x in y:
1039 ... ...
1040 ... else:
1041 ... ...
1042 ... """), indent=4))
1043 Module(
1044 body=[
1045 For(
1046 target=Name(id='x', ctx=Store()),
1047 iter=Name(id='y', ctx=Load()),
1048 body=[
1049 Expr(
Serhiy Storchakab7e95252020-03-10 00:07:47 +02001050 value=Constant(value=Ellipsis))],
Pablo Galindo114081f2020-03-02 03:14:06 +00001051 orelse=[
1052 Expr(
Serhiy Storchakab7e95252020-03-10 00:07:47 +02001053 value=Constant(value=Ellipsis))])],
Pablo Galindo114081f2020-03-02 03:14:06 +00001054 type_ignores=[])
1055
1056
1057.. class:: While(test, body, orelse)
1058
1059 A ``while`` loop. ``test`` holds the condition, such as a :class:`Compare`
1060 node.
1061
1062 .. doctest::
1063
1064 >> print(ast.dump(ast.parse("""
1065 ... while x:
1066 ... ...
1067 ... else:
1068 ... ...
1069 ... """), indent=4))
1070 Module(
1071 body=[
1072 While(
1073 test=Name(id='x', ctx=Load()),
1074 body=[
1075 Expr(
Serhiy Storchakab7e95252020-03-10 00:07:47 +02001076 value=Constant(value=Ellipsis))],
Pablo Galindo114081f2020-03-02 03:14:06 +00001077 orelse=[
1078 Expr(
Serhiy Storchakab7e95252020-03-10 00:07:47 +02001079 value=Constant(value=Ellipsis))])],
Pablo Galindo114081f2020-03-02 03:14:06 +00001080 type_ignores=[])
1081
1082
1083.. class:: Break
1084 Continue
1085
1086 The ``break`` and ``continue`` statements.
1087
1088 .. doctest::
1089
1090 >>> print(ast.dump(ast.parse("""\
1091 ... for a in b:
1092 ... if a > 5:
1093 ... break
1094 ... else:
1095 ... continue
1096 ...
1097 ... """), indent=4))
1098 Module(
1099 body=[
1100 For(
1101 target=Name(id='a', ctx=Store()),
1102 iter=Name(id='b', ctx=Load()),
1103 body=[
1104 If(
1105 test=Compare(
1106 left=Name(id='a', ctx=Load()),
1107 ops=[
1108 Gt()],
1109 comparators=[
Serhiy Storchakab7e95252020-03-10 00:07:47 +02001110 Constant(value=5)]),
Pablo Galindo114081f2020-03-02 03:14:06 +00001111 body=[
1112 Break()],
1113 orelse=[
1114 Continue()])],
Serhiy Storchakab7e95252020-03-10 00:07:47 +02001115 orelse=[])],
Pablo Galindo114081f2020-03-02 03:14:06 +00001116 type_ignores=[])
1117
1118
1119.. class:: Try(body, handlers, orelse, finalbody)
1120
1121 ``try`` blocks. All attributes are list of nodes to execute, except for
1122 ``handlers``, which is a list of :class:`ExceptHandler` nodes.
1123
1124 .. doctest::
1125
1126 >>> print(ast.dump(ast.parse("""
1127 ... try:
1128 ... ...
1129 ... except Exception:
1130 ... ...
1131 ... except OtherException as e:
1132 ... ...
1133 ... else:
1134 ... ...
1135 ... finally:
1136 ... ...
1137 ... """), indent=4))
1138 Module(
1139 body=[
1140 Try(
1141 body=[
1142 Expr(
Serhiy Storchakab7e95252020-03-10 00:07:47 +02001143 value=Constant(value=Ellipsis))],
Pablo Galindo114081f2020-03-02 03:14:06 +00001144 handlers=[
1145 ExceptHandler(
1146 type=Name(id='Exception', ctx=Load()),
Pablo Galindo114081f2020-03-02 03:14:06 +00001147 body=[
1148 Expr(
Serhiy Storchakab7e95252020-03-10 00:07:47 +02001149 value=Constant(value=Ellipsis))]),
Pablo Galindo114081f2020-03-02 03:14:06 +00001150 ExceptHandler(
1151 type=Name(id='OtherException', ctx=Load()),
1152 name='e',
1153 body=[
1154 Expr(
Serhiy Storchakab7e95252020-03-10 00:07:47 +02001155 value=Constant(value=Ellipsis))])],
Pablo Galindo114081f2020-03-02 03:14:06 +00001156 orelse=[
1157 Expr(
Serhiy Storchakab7e95252020-03-10 00:07:47 +02001158 value=Constant(value=Ellipsis))],
Pablo Galindo114081f2020-03-02 03:14:06 +00001159 finalbody=[
1160 Expr(
Serhiy Storchakab7e95252020-03-10 00:07:47 +02001161 value=Constant(value=Ellipsis))])],
Pablo Galindo114081f2020-03-02 03:14:06 +00001162 type_ignores=[])
1163
1164
1165.. class:: ExceptHandler(type, name, body)
1166
1167 A single ``except`` clause. ``type`` is the exception type it will match,
1168 typically a :class:`Name` node (or ``None`` for a catch-all ``except:`` clause).
1169 ``name`` is a raw string for the name to hold the exception, or ``None`` if
1170 the clause doesn't have ``as foo``. ``body`` is a list of nodes.
1171
1172 .. doctest::
1173
1174 >>> print(ast.dump(ast.parse("""\
1175 ... try:
1176 ... a + 1
1177 ... except TypeError:
1178 ... pass
1179 ... """), indent=4))
1180 Module(
1181 body=[
1182 Try(
1183 body=[
1184 Expr(
1185 value=BinOp(
1186 left=Name(id='a', ctx=Load()),
1187 op=Add(),
Serhiy Storchakab7e95252020-03-10 00:07:47 +02001188 right=Constant(value=1)))],
Pablo Galindo114081f2020-03-02 03:14:06 +00001189 handlers=[
1190 ExceptHandler(
1191 type=Name(id='TypeError', ctx=Load()),
Pablo Galindo114081f2020-03-02 03:14:06 +00001192 body=[
1193 Pass()])],
1194 orelse=[],
1195 finalbody=[])],
1196 type_ignores=[])
1197
1198
1199.. class:: With(items, body, type_comment)
1200
1201 A ``with`` block. ``items`` is a list of :class:`withitem` nodes representing
1202 the context managers, and ``body`` is the indented block inside the context.
1203
1204 .. attribute:: type_comment
1205
1206 ``type_comment`` is an optional string with the type annotation as a comment.
1207
1208
1209.. class:: withitem(context_expr, optional_vars)
1210
1211 A single context manager in a ``with`` block. ``context_expr`` is the context
1212 manager, often a :class:`Call` node. ``optional_vars`` is a :class:`Name`,
1213 :class:`Tuple` or :class:`List` for the ``as foo`` part, or ``None`` if that
1214 isn't used.
1215
1216 .. doctest::
1217
1218 >>> print(ast.dump(ast.parse("""\
1219 ... with a as b, c as d:
1220 ... something(b, d)
1221 ... """), indent=4))
1222 Module(
1223 body=[
1224 With(
1225 items=[
1226 withitem(
1227 context_expr=Name(id='a', ctx=Load()),
1228 optional_vars=Name(id='b', ctx=Store())),
1229 withitem(
1230 context_expr=Name(id='c', ctx=Load()),
1231 optional_vars=Name(id='d', ctx=Store()))],
1232 body=[
1233 Expr(
1234 value=Call(
1235 func=Name(id='something', ctx=Load()),
1236 args=[
1237 Name(id='b', ctx=Load()),
1238 Name(id='d', ctx=Load())],
Serhiy Storchakab7e95252020-03-10 00:07:47 +02001239 keywords=[]))])],
Pablo Galindo114081f2020-03-02 03:14:06 +00001240 type_ignores=[])
1241
1242
Pablo Galindoa8e26152021-03-01 02:08:37 +00001243.. class:: Match(subject, cases)
1244
1245 A ``match`` statement. ``subject`` holds the subject of the match (the object
1246 that is being matched against the cases) and ``cases`` contains an iterable of
1247 :class:`match_case` nodes with the different cases.
1248
1249
1250.. class:: match_case(context_expr, optional_vars)
1251
1252 A single case pattern in a ``match`` statement. ``pattern`` contains the
1253 match pattern that will be used to match the subject against. Notice that
1254 the meaning of the :class:`AST` nodes in this attribute have a different
1255 meaning than in other places, as they represent patterns to match against.
1256 The ``guard`` attribute contains an expression that will be evaluated if
1257 the pattern matches the subject. If the pattern matches and the ``guard`` condition
1258 is truthy, the body of the case shall be executed. ``body`` contains a list
1259 of nodes to execute if the guard is truthy.
1260
1261 .. doctest::
1262
1263 >>> print(ast.dump(ast.parse("""
1264 ... match x:
1265 ... case [x] if x>0:
1266 ... ...
1267 ... case tuple():
1268 ... ...
1269 ... """), indent=4))
1270 Module(
1271 body=[
1272 Match(
1273 subject=Name(id='x', ctx=Load()),
1274 cases=[
1275 match_case(
1276 pattern=List(
1277 elts=[
1278 Name(id='x', ctx=Store())],
1279 ctx=Load()),
1280 guard=Compare(
1281 left=Name(id='x', ctx=Load()),
1282 ops=[
1283 Gt()],
1284 comparators=[
1285 Constant(value=0)]),
1286 body=[
1287 Expr(
1288 value=Constant(value=Ellipsis))]),
1289 match_case(
1290 pattern=Call(
1291 func=Name(id='tuple', ctx=Load()),
1292 args=[],
1293 keywords=[]),
1294 body=[
1295 Expr(
1296 value=Constant(value=Ellipsis))])])],
1297 type_ignores=[])
1298
1299.. class:: MatchAs(pattern, name)
1300
1301 A match "as-pattern". The as-pattern matches whatever pattern is on its
1302 left-hand side, but also binds the value to a name. ``pattern`` contains
1303 the match pattern that will be used to match the subject agsinst. The ``name``
1304 attribute contains the name that will be binded if the pattern is successful.
1305
1306 .. doctest::
1307
1308 >>> print(ast.dump(ast.parse("""
1309 ... match x:
1310 ... case [x] as y:
1311 ... ...
1312 ... """), indent=4))
1313 Module(
1314 body=[
1315 Match(
1316 subject=Name(id='x', ctx=Load()),
1317 cases=[
1318 match_case(
1319 pattern=MatchAs(
1320 pattern=List(
1321 elts=[
1322 Name(id='x', ctx=Store())],
1323 ctx=Load()),
1324 name='y'),
1325 body=[
1326 Expr(
1327 value=Constant(value=Ellipsis))])])],
1328 type_ignores=[])
1329
1330
1331.. class:: MatchOr(patterns)
1332
1333 A match "or-pattern". An or-pattern matches each of its subpatterns in turn
1334 to the subject, until one succeeds. The or-pattern is then deemed to
1335 succeed. If none of the subpatterns succeed the or-pattern fails. The
1336 ``patterns`` attribute contains a list of match patterns nodes that will be
1337 matched against the subject.
1338
1339 .. doctest::
1340
1341 >>> print(ast.dump(ast.parse("""
1342 ... match x:
1343 ... case [x] | (y):
1344 ... ...
1345 ... """), indent=4))
1346 Module(
1347 body=[
1348 Match(
1349 subject=Name(id='x', ctx=Load()),
1350 cases=[
1351 match_case(
1352 pattern=MatchOr(
1353 patterns=[
1354 List(
1355 elts=[
1356 Name(id='x', ctx=Store())],
1357 ctx=Load()),
1358 Name(id='y', ctx=Store())]),
1359 body=[
1360 Expr(
1361 value=Constant(value=Ellipsis))])])],
1362 type_ignores=[])
1363
1364
Pablo Galindo114081f2020-03-02 03:14:06 +00001365Function and class definitions
1366^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1367
1368.. class:: FunctionDef(name, args, body, decorator_list, returns, type_comment)
1369
1370 A function definition.
1371
1372 * ``name`` is a raw string of the function name.
1373 * ``args`` is a :class:`arguments` node.
1374 * ``body`` is the list of nodes inside the function.
1375 * ``decorator_list`` is the list of decorators to be applied, stored outermost
1376 first (i.e. the first in the list will be applied last).
1377 * ``returns`` is the return annotation.
1378
1379 .. attribute:: type_comment
1380
1381 ``type_comment`` is an optional string with the type annotation as a comment.
1382
1383
1384.. class:: Lambda(args, body)
1385
1386 ``lambda`` is a minimal function definition that can be used inside an
1387 expression. Unlike :class:`FunctionDef`, ``body`` holds a single node.
1388
1389 .. doctest::
1390
Pablo Galindo02f64cb2020-03-07 18:22:58 +00001391 >>> print(ast.dump(ast.parse('lambda x,y: ...'), indent=4))
Pablo Galindo114081f2020-03-02 03:14:06 +00001392 Module(
1393 body=[
1394 Expr(
1395 value=Lambda(
1396 args=arguments(
1397 posonlyargs=[],
1398 args=[
Serhiy Storchakab7e95252020-03-10 00:07:47 +02001399 arg(arg='x'),
1400 arg(arg='y')],
Pablo Galindo114081f2020-03-02 03:14:06 +00001401 kwonlyargs=[],
1402 kw_defaults=[],
Pablo Galindo114081f2020-03-02 03:14:06 +00001403 defaults=[]),
Serhiy Storchakab7e95252020-03-10 00:07:47 +02001404 body=Constant(value=Ellipsis)))],
Pablo Galindo114081f2020-03-02 03:14:06 +00001405 type_ignores=[])
1406
1407
1408.. class:: arguments(posonlyargs, args, vararg, kwonlyargs, kw_defaults, kwarg, defaults)
1409
1410 The arguments for a function.
1411
1412 * ``posonlyargs``, ``args`` and ``kwonlyargs`` are lists of :class:`arg` nodes.
1413 * ``vararg`` and ``kwarg`` are single :class:`arg` nodes, referring to the
1414 ``*args, **kwargs`` parameters.
1415 * ``kw_defaults`` is a list of default values for keyword-only arguments. If
1416 one is ``None``, the corresponding argument is required.
1417 * ``defaults`` is a list of default values for arguments that can be passed
1418 positionally. If there are fewer defaults, they correspond to the last n
1419 arguments.
1420
1421
1422.. class:: arg(arg, annotation, type_comment)
1423
1424 A single argument in a list. ``arg`` is a raw string of the argument
1425 name, ``annotation`` is its annotation, such as a :class:`Str` or
1426 :class:`Name` node.
1427
1428 .. attribute:: type_comment
1429
1430 ``type_comment`` is an optional string with the type annotation as a comment
1431
1432 .. doctest::
1433
1434 >>> print(ast.dump(ast.parse("""\
1435 ... @decorator1
1436 ... @decorator2
1437 ... def f(a: 'annotation', b=1, c=2, *d, e, f=3, **g) -> 'return annotation':
1438 ... pass
1439 ... """), indent=4))
1440 Module(
1441 body=[
1442 FunctionDef(
1443 name='f',
1444 args=arguments(
1445 posonlyargs=[],
1446 args=[
1447 arg(
1448 arg='a',
Serhiy Storchakab7e95252020-03-10 00:07:47 +02001449 annotation=Constant(value='annotation')),
1450 arg(arg='b'),
1451 arg(arg='c')],
1452 vararg=arg(arg='d'),
Pablo Galindo114081f2020-03-02 03:14:06 +00001453 kwonlyargs=[
Serhiy Storchakab7e95252020-03-10 00:07:47 +02001454 arg(arg='e'),
1455 arg(arg='f')],
Pablo Galindo114081f2020-03-02 03:14:06 +00001456 kw_defaults=[
1457 None,
Serhiy Storchakab7e95252020-03-10 00:07:47 +02001458 Constant(value=3)],
1459 kwarg=arg(arg='g'),
Pablo Galindo114081f2020-03-02 03:14:06 +00001460 defaults=[
Serhiy Storchakab7e95252020-03-10 00:07:47 +02001461 Constant(value=1),
1462 Constant(value=2)]),
Pablo Galindo114081f2020-03-02 03:14:06 +00001463 body=[
1464 Pass()],
1465 decorator_list=[
1466 Name(id='decorator1', ctx=Load()),
1467 Name(id='decorator2', ctx=Load())],
Serhiy Storchakab7e95252020-03-10 00:07:47 +02001468 returns=Constant(value='return annotation'))],
Pablo Galindo114081f2020-03-02 03:14:06 +00001469 type_ignores=[])
1470
1471
1472.. class:: Return(value)
1473
1474 A ``return`` statement.
1475
1476 .. doctest::
1477
Pablo Galindo02f64cb2020-03-07 18:22:58 +00001478 >>> print(ast.dump(ast.parse('return 4'), indent=4))
Pablo Galindo114081f2020-03-02 03:14:06 +00001479 Module(
1480 body=[
1481 Return(
Serhiy Storchakab7e95252020-03-10 00:07:47 +02001482 value=Constant(value=4))],
Pablo Galindo114081f2020-03-02 03:14:06 +00001483 type_ignores=[])
1484
1485
1486.. class:: Yield(value)
1487 YieldFrom(value)
1488
1489 A ``yield`` or ``yield from`` expression. Because these are expressions, they
1490 must be wrapped in a :class:`Expr` node if the value sent back is not used.
1491
1492 .. doctest::
1493
Pablo Galindo02f64cb2020-03-07 18:22:58 +00001494 >>> print(ast.dump(ast.parse('yield x'), indent=4))
Pablo Galindo114081f2020-03-02 03:14:06 +00001495 Module(
1496 body=[
1497 Expr(
1498 value=Yield(
1499 value=Name(id='x', ctx=Load())))],
1500 type_ignores=[])
1501
Pablo Galindo02f64cb2020-03-07 18:22:58 +00001502 >>> print(ast.dump(ast.parse('yield from x'), indent=4))
Pablo Galindo114081f2020-03-02 03:14:06 +00001503 Module(
1504 body=[
1505 Expr(
1506 value=YieldFrom(
1507 value=Name(id='x', ctx=Load())))],
1508 type_ignores=[])
1509
1510
1511.. class:: Global(names)
1512 Nonlocal(names)
1513
1514 ``global`` and ``nonlocal`` statements. ``names`` is a list of raw strings.
1515
1516 .. doctest::
1517
Pablo Galindo02f64cb2020-03-07 18:22:58 +00001518 >>> print(ast.dump(ast.parse('global x,y,z'), indent=4))
Pablo Galindo114081f2020-03-02 03:14:06 +00001519 Module(
1520 body=[
1521 Global(
1522 names=[
1523 'x',
1524 'y',
1525 'z'])],
1526 type_ignores=[])
1527
Pablo Galindo02f64cb2020-03-07 18:22:58 +00001528 >>> print(ast.dump(ast.parse('nonlocal x,y,z'), indent=4))
Pablo Galindo114081f2020-03-02 03:14:06 +00001529 Module(
1530 body=[
1531 Nonlocal(
1532 names=[
1533 'x',
1534 'y',
1535 'z'])],
1536 type_ignores=[])
1537
1538
1539.. class:: ClassDef(name, bases, keywords, starargs, kwargs, body, decorator_list)
1540
1541 A class definition.
1542
1543 * ``name`` is a raw string for the class name
1544 * ``bases`` is a list of nodes for explicitly specified base classes.
1545 * ``keywords`` is a list of :class:`keyword` nodes, principally for 'metaclass'.
1546 Other keywords will be passed to the metaclass, as per `PEP-3115
1547 <http://www.python.org/dev/peps/pep-3115/>`_.
1548 * ``starargs`` and ``kwargs`` are each a single node, as in a function call.
1549 starargs will be expanded to join the list of base classes, and kwargs will
1550 be passed to the metaclass.
1551 * ``body`` is a list of nodes representing the code within the class
1552 definition.
1553 * ``decorator_list`` is a list of nodes, as in :class:`FunctionDef`.
1554
1555 .. doctest::
1556
1557 >>> print(ast.dump(ast.parse("""\
1558 ... @decorator1
1559 ... @decorator2
1560 ... class Foo(base1, base2, metaclass=meta):
1561 ... pass
1562 ... """), indent=4))
1563 Module(
1564 body=[
1565 ClassDef(
1566 name='Foo',
1567 bases=[
1568 Name(id='base1', ctx=Load()),
1569 Name(id='base2', ctx=Load())],
1570 keywords=[
1571 keyword(
1572 arg='metaclass',
1573 value=Name(id='meta', ctx=Load()))],
1574 body=[
1575 Pass()],
1576 decorator_list=[
1577 Name(id='decorator1', ctx=Load()),
1578 Name(id='decorator2', ctx=Load())])],
1579 type_ignores=[])
1580
1581Async and await
1582^^^^^^^^^^^^^^^
1583
1584.. class:: AsyncFunctionDef(name, args, body, decorator_list, returns, type_comment)
1585
1586 An ``async def`` function definition. Has the same fields as
1587 :class:`FunctionDef`.
1588
1589
1590.. class:: Await(value)
1591
1592 An ``await`` expression. ``value`` is what it waits for.
1593 Only valid in the body of an :class:`AsyncFunctionDef`.
1594
1595.. doctest::
1596
1597 >>> print(ast.dump(ast.parse("""\
1598 ... async def f():
1599 ... await other_func()
1600 ... """), indent=4))
1601 Module(
1602 body=[
1603 AsyncFunctionDef(
1604 name='f',
1605 args=arguments(
1606 posonlyargs=[],
1607 args=[],
Pablo Galindo114081f2020-03-02 03:14:06 +00001608 kwonlyargs=[],
1609 kw_defaults=[],
Pablo Galindo114081f2020-03-02 03:14:06 +00001610 defaults=[]),
1611 body=[
1612 Expr(
1613 value=Await(
1614 value=Call(
1615 func=Name(id='other_func', ctx=Load()),
1616 args=[],
1617 keywords=[])))],
Serhiy Storchakab7e95252020-03-10 00:07:47 +02001618 decorator_list=[])],
Pablo Galindo114081f2020-03-02 03:14:06 +00001619 type_ignores=[])
1620
1621
1622.. class:: AsyncFor(target, iter, body, orelse, type_comment)
1623 AsyncWith(items, body, type_comment)
1624
1625 ``async for`` loops and ``async with`` context managers. They have the same
1626 fields as :class:`For` and :class:`With`, respectively. Only valid in the
1627 body of an :class:`AsyncFunctionDef`.
Georg Brandl0c77a822008-06-10 16:37:50 +00001628
Batuhan Taskayab37c9942020-10-22 19:02:43 +03001629.. note::
1630 When a string is parsed by :func:`ast.parse`, operator nodes (subclasses
1631 of :class:`ast.operator`, :class:`ast.unaryop`, :class:`ast.cmpop`,
1632 :class:`ast.boolop` and :class:`ast.expr_context`) on the returned tree
1633 will be singletons. Changes to one will be reflected in all other
1634 occurrences of the same value (e.g. :class:`ast.Add`).
1635
Georg Brandl0c77a822008-06-10 16:37:50 +00001636
1637:mod:`ast` Helpers
1638------------------
1639
Martin Panter2e4571a2015-11-14 01:07:43 +00001640Apart from the node classes, the :mod:`ast` module defines these utility functions
Georg Brandl0c77a822008-06-10 16:37:50 +00001641and classes for traversing abstract syntax trees:
1642
Guido van Rossum10b55c12019-06-11 17:23:12 -07001643.. function:: parse(source, filename='<unknown>', mode='exec', *, type_comments=False, feature_version=None)
Georg Brandl0c77a822008-06-10 16:37:50 +00001644
Terry Reedyfeac6242011-01-24 21:36:03 +00001645 Parse the source into an AST node. Equivalent to ``compile(source,
Benjamin Petersonec9199b2008-11-08 17:05:00 +00001646 filename, mode, ast.PyCF_ONLY_AST)``.
Georg Brandl0c77a822008-06-10 16:37:50 +00001647
Guido van Rossumdcfcd142019-01-31 03:40:27 -08001648 If ``type_comments=True`` is given, the parser is modified to check
1649 and return type comments as specified by :pep:`484` and :pep:`526`.
1650 This is equivalent to adding :data:`ast.PyCF_TYPE_COMMENTS` to the
1651 flags passed to :func:`compile()`. This will report syntax errors
1652 for misplaced type comments. Without this flag, type comments will
1653 be ignored, and the ``type_comment`` field on selected AST nodes
1654 will always be ``None``. In addition, the locations of ``# type:
1655 ignore`` comments will be returned as the ``type_ignores``
1656 attribute of :class:`Module` (otherwise it is always an empty list).
1657
1658 In addition, if ``mode`` is ``'func_type'``, the input syntax is
1659 modified to correspond to :pep:`484` "signature type comments",
1660 e.g. ``(str, int) -> List[str]``.
1661
Guido van Rossum10b55c12019-06-11 17:23:12 -07001662 Also, setting ``feature_version`` to a tuple ``(major, minor)``
1663 will attempt to parse using that Python version's grammar.
1664 Currently ``major`` must equal to ``3``. For example, setting
1665 ``feature_version=(3, 4)`` will allow the use of ``async`` and
1666 ``await`` as variable names. The lowest supported version is
1667 ``(3, 4)``; the highest is ``sys.version_info[0:2]``.
Guido van Rossum495da292019-03-07 12:38:08 -08001668
Brett Cannon7a7f1002018-03-09 12:03:22 -08001669 .. warning::
1670 It is possible to crash the Python interpreter with a
1671 sufficiently large/complex string due to stack depth limitations
1672 in Python's AST compiler.
1673
Guido van Rossumdcfcd142019-01-31 03:40:27 -08001674 .. versionchanged:: 3.8
Guido van Rossum495da292019-03-07 12:38:08 -08001675 Added ``type_comments``, ``mode='func_type'`` and ``feature_version``.
Guido van Rossumdcfcd142019-01-31 03:40:27 -08001676
Georg Brandl48310cd2009-01-03 21:18:54 +00001677
Pablo Galindo27fc3b62019-11-24 23:02:40 +00001678.. function:: unparse(ast_obj)
1679
1680 Unparse an :class:`ast.AST` object and generate a string with code
1681 that would produce an equivalent :class:`ast.AST` object if parsed
1682 back with :func:`ast.parse`.
1683
1684 .. warning::
Gurupad Hegde6c7bb382019-12-28 17:16:02 -05001685 The produced code string will not necessarily be equal to the original
Batuhan Taskaya8df10162020-06-28 04:11:43 +03001686 code that generated the :class:`ast.AST` object (without any compiler
1687 optimizations, such as constant tuples/frozensets).
1688
1689 .. warning::
1690 Trying to unparse a highly complex expression would result with
1691 :exc:`RecursionError`.
Pablo Galindo27fc3b62019-11-24 23:02:40 +00001692
1693 .. versionadded:: 3.9
1694
1695
Georg Brandl0c77a822008-06-10 16:37:50 +00001696.. function:: literal_eval(node_or_string)
1697
Georg Brandlb9b389e2014-11-05 20:20:28 +01001698 Safely evaluate an expression node or a string containing a Python literal or
1699 container display. The string or node provided may only consist of the
1700 following Python literal structures: strings, bytes, numbers, tuples, lists,
Batuhan Taskayafbc77232020-12-22 03:15:40 +03001701 dicts, sets, booleans, ``None`` and ``Ellipsis``.
Georg Brandl0c77a822008-06-10 16:37:50 +00001702
Georg Brandlb9b389e2014-11-05 20:20:28 +01001703 This can be used for safely evaluating strings containing Python values from
1704 untrusted sources without the need to parse the values oneself. It is not
1705 capable of evaluating arbitrarily complex expressions, for example involving
1706 operators or indexing.
Georg Brandl0c77a822008-06-10 16:37:50 +00001707
Brett Cannon7a7f1002018-03-09 12:03:22 -08001708 .. warning::
1709 It is possible to crash the Python interpreter with a
1710 sufficiently large/complex string due to stack depth limitations
1711 in Python's AST compiler.
1712
Batuhan Taskayafbc77232020-12-22 03:15:40 +03001713 It can raise :exc:`ValueError`, :exc:`TypeError`, :exc:`SyntaxError`,
1714 :exc:`MemoryError` and :exc:`RecursionError` depending on the malformed
1715 input.
1716
Georg Brandl492f3fc2010-07-11 09:41:21 +00001717 .. versionchanged:: 3.2
Georg Brandl85f21772010-07-13 06:38:10 +00001718 Now allows bytes and set literals.
Georg Brandl492f3fc2010-07-11 09:41:21 +00001719
Raymond Hettinger4fcf5c12020-01-02 22:21:18 -07001720 .. versionchanged:: 3.9
1721 Now supports creating empty sets with ``'set()'``.
1722
Batuhan Taskayae799aa82020-10-04 03:46:44 +03001723 .. versionchanged:: 3.10
1724 For string inputs, leading spaces and tabs are now stripped.
1725
Georg Brandl0c77a822008-06-10 16:37:50 +00001726
Amaury Forgeot d'Arcfdfe62d2008-06-17 20:36:03 +00001727.. function:: get_docstring(node, clean=True)
Georg Brandl0c77a822008-06-10 16:37:50 +00001728
1729 Return the docstring of the given *node* (which must be a
INADA Naokicb41b272017-02-23 00:31:59 +09001730 :class:`FunctionDef`, :class:`AsyncFunctionDef`, :class:`ClassDef`,
1731 or :class:`Module` node), or ``None`` if it has no docstring.
1732 If *clean* is true, clean up the docstring's indentation with
1733 :func:`inspect.cleandoc`.
1734
1735 .. versionchanged:: 3.5
1736 :class:`AsyncFunctionDef` is now supported.
1737
Georg Brandl0c77a822008-06-10 16:37:50 +00001738
Ivan Levkivskyi9932a222019-01-22 11:18:22 +00001739.. function:: get_source_segment(source, node, *, padded=False)
1740
1741 Get source code segment of the *source* that generated *node*.
1742 If some location information (:attr:`lineno`, :attr:`end_lineno`,
1743 :attr:`col_offset`, or :attr:`end_col_offset`) is missing, return ``None``.
1744
1745 If *padded* is ``True``, the first line of a multi-line statement will
1746 be padded with spaces to match its original position.
1747
1748 .. versionadded:: 3.8
1749
1750
Georg Brandl0c77a822008-06-10 16:37:50 +00001751.. function:: fix_missing_locations(node)
1752
1753 When you compile a node tree with :func:`compile`, the compiler expects
1754 :attr:`lineno` and :attr:`col_offset` attributes for every node that supports
1755 them. This is rather tedious to fill in for generated nodes, so this helper
1756 adds these attributes recursively where not already set, by setting them to
1757 the values of the parent node. It works recursively starting at *node*.
1758
1759
1760.. function:: increment_lineno(node, n=1)
1761
Ivan Levkivskyi9932a222019-01-22 11:18:22 +00001762 Increment the line number and end line number of each node in the tree
1763 starting at *node* by *n*. This is useful to "move code" to a different
1764 location in a file.
Georg Brandl0c77a822008-06-10 16:37:50 +00001765
1766
1767.. function:: copy_location(new_node, old_node)
1768
Ivan Levkivskyi9932a222019-01-22 11:18:22 +00001769 Copy source location (:attr:`lineno`, :attr:`col_offset`, :attr:`end_lineno`,
1770 and :attr:`end_col_offset`) from *old_node* to *new_node* if possible,
1771 and return *new_node*.
Georg Brandl0c77a822008-06-10 16:37:50 +00001772
1773
1774.. function:: iter_fields(node)
1775
1776 Yield a tuple of ``(fieldname, value)`` for each field in ``node._fields``
1777 that is present on *node*.
1778
1779
1780.. function:: iter_child_nodes(node)
1781
1782 Yield all direct child nodes of *node*, that is, all fields that are nodes
1783 and all items of fields that are lists of nodes.
1784
1785
1786.. function:: walk(node)
1787
Georg Brandl619e7ba2011-01-09 07:38:51 +00001788 Recursively yield all descendant nodes in the tree starting at *node*
1789 (including *node* itself), in no specified order. This is useful if you only
1790 want to modify nodes in place and don't care about the context.
Georg Brandl0c77a822008-06-10 16:37:50 +00001791
1792
1793.. class:: NodeVisitor()
1794
1795 A node visitor base class that walks the abstract syntax tree and calls a
1796 visitor function for every node found. This function may return a value
Georg Brandl36ab1ef2009-01-03 21:17:04 +00001797 which is forwarded by the :meth:`visit` method.
Georg Brandl0c77a822008-06-10 16:37:50 +00001798
1799 This class is meant to be subclassed, with the subclass adding visitor
1800 methods.
1801
1802 .. method:: visit(node)
1803
1804 Visit a node. The default implementation calls the method called
1805 :samp:`self.visit_{classname}` where *classname* is the name of the node
1806 class, or :meth:`generic_visit` if that method doesn't exist.
1807
1808 .. method:: generic_visit(node)
1809
1810 This visitor calls :meth:`visit` on all children of the node.
Georg Brandl48310cd2009-01-03 21:18:54 +00001811
Georg Brandl0c77a822008-06-10 16:37:50 +00001812 Note that child nodes of nodes that have a custom visitor method won't be
1813 visited unless the visitor calls :meth:`generic_visit` or visits them
1814 itself.
1815
1816 Don't use the :class:`NodeVisitor` if you want to apply changes to nodes
1817 during traversal. For this a special visitor exists
1818 (:class:`NodeTransformer`) that allows modifications.
1819
Serhiy Storchakac3ea41e2019-08-26 10:13:19 +03001820 .. deprecated:: 3.8
1821
1822 Methods :meth:`visit_Num`, :meth:`visit_Str`, :meth:`visit_Bytes`,
1823 :meth:`visit_NameConstant` and :meth:`visit_Ellipsis` are deprecated
1824 now and will not be called in future Python versions. Add the
1825 :meth:`visit_Constant` method to handle all constant nodes.
1826
Georg Brandl0c77a822008-06-10 16:37:50 +00001827
1828.. class:: NodeTransformer()
1829
1830 A :class:`NodeVisitor` subclass that walks the abstract syntax tree and
1831 allows modification of nodes.
1832
Georg Brandl36ab1ef2009-01-03 21:17:04 +00001833 The :class:`NodeTransformer` will walk the AST and use the return value of
1834 the visitor methods to replace or remove the old node. If the return value
1835 of the visitor method is ``None``, the node will be removed from its
1836 location, otherwise it is replaced with the return value. The return value
1837 may be the original node in which case no replacement takes place.
Georg Brandl0c77a822008-06-10 16:37:50 +00001838
1839 Here is an example transformer that rewrites all occurrences of name lookups
1840 (``foo``) to ``data['foo']``::
1841
1842 class RewriteName(NodeTransformer):
1843
1844 def visit_Name(self, node):
Batuhan Taşkaya6680f4a2020-01-12 23:38:53 +03001845 return Subscript(
Georg Brandl0c77a822008-06-10 16:37:50 +00001846 value=Name(id='data', ctx=Load()),
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02001847 slice=Constant(value=node.id),
Georg Brandl0c77a822008-06-10 16:37:50 +00001848 ctx=node.ctx
Pablo Galindoc00c86b2020-03-12 00:48:19 +00001849 )
Georg Brandl0c77a822008-06-10 16:37:50 +00001850
1851 Keep in mind that if the node you're operating on has child nodes you must
1852 either transform the child nodes yourself or call the :meth:`generic_visit`
1853 method for the node first.
1854
1855 For nodes that were part of a collection of statements (that applies to all
1856 statement nodes), the visitor may also return a list of nodes rather than
1857 just a single node.
1858
Batuhan Taşkaya6680f4a2020-01-12 23:38:53 +03001859 If :class:`NodeTransformer` introduces new nodes (that weren't part of
1860 original tree) without giving them location information (such as
1861 :attr:`lineno`), :func:`fix_missing_locations` should be called with
1862 the new sub-tree to recalculate the location information::
1863
1864 tree = ast.parse('foo', mode='eval')
1865 new_tree = fix_missing_locations(RewriteName().visit(tree))
1866
Georg Brandl0c77a822008-06-10 16:37:50 +00001867 Usually you use the transformer like this::
1868
1869 node = YourTransformer().visit(node)
1870
1871
Serhiy Storchaka850573b2019-09-09 19:33:13 +03001872.. function:: dump(node, annotate_fields=True, include_attributes=False, *, indent=None)
Georg Brandl0c77a822008-06-10 16:37:50 +00001873
1874 Return a formatted dump of the tree in *node*. This is mainly useful for
Serhiy Storchakae64f9482019-08-29 09:30:23 +03001875 debugging purposes. If *annotate_fields* is true (by default),
1876 the returned string will show the names and the values for fields.
1877 If *annotate_fields* is false, the result string will be more compact by
1878 omitting unambiguous field names. Attributes such as line
Benjamin Petersondcf97b92008-07-02 17:30:14 +00001879 numbers and column offsets are not dumped by default. If this is wanted,
Serhiy Storchakae64f9482019-08-29 09:30:23 +03001880 *include_attributes* can be set to true.
Senthil Kumaranf3695bf2016-01-06 21:26:53 -08001881
Serhiy Storchaka850573b2019-09-09 19:33:13 +03001882 If *indent* is a non-negative integer or string, then the tree will be
1883 pretty-printed with that indent level. An indent level
1884 of 0, negative, or ``""`` will only insert newlines. ``None`` (the default)
1885 selects the single line representation. Using a positive integer indent
1886 indents that many spaces per level. If *indent* is a string (such as ``"\t"``),
1887 that string is used to indent each level.
1888
1889 .. versionchanged:: 3.9
1890 Added the *indent* option.
1891
1892
Batuhan Taskaya15593892020-10-19 04:14:11 +03001893.. _ast-compiler-flags:
1894
1895Compiler Flags
1896--------------
1897
1898The following flags may be passed to :func:`compile` in order to change
1899effects on the compilation of a program:
1900
1901.. data:: PyCF_ALLOW_TOP_LEVEL_AWAIT
1902
1903 Enables support for top-level ``await``, ``async for``, ``async with``
1904 and async comprehensions.
1905
1906 .. versionadded:: 3.8
1907
1908.. data:: PyCF_ONLY_AST
1909
1910 Generates and returns an abstract syntax tree instead of returning a
1911 compiled code object.
1912
1913.. data:: PyCF_TYPE_COMMENTS
1914
1915 Enables support for :pep:`484` and :pep:`526` style type comments
1916 (``# type: <type>``, ``# type: ignore <stuff>``).
1917
1918 .. versionadded:: 3.8
1919
1920
Serhiy Storchaka832e8642019-09-09 23:36:13 +03001921.. _ast-cli:
1922
1923Command-Line Usage
1924------------------
1925
1926.. versionadded:: 3.9
1927
1928The :mod:`ast` module can be executed as a script from the command line.
1929It is as simple as:
1930
1931.. code-block:: sh
1932
1933 python -m ast [-m <mode>] [-a] [infile]
1934
1935The following options are accepted:
1936
1937.. program:: ast
1938
1939.. cmdoption:: -h, --help
1940
1941 Show the help message and exit.
1942
1943.. cmdoption:: -m <mode>
1944 --mode <mode>
1945
1946 Specify what kind of code must be compiled, like the *mode* argument
1947 in :func:`parse`.
1948
Batuhan Taşkaya814d6872019-12-16 21:23:27 +03001949.. cmdoption:: --no-type-comments
1950
1951 Don't parse type comments.
1952
Serhiy Storchaka832e8642019-09-09 23:36:13 +03001953.. cmdoption:: -a, --include-attributes
1954
1955 Include attributes such as line numbers and column offsets.
1956
Batuhan Taşkaya814d6872019-12-16 21:23:27 +03001957.. cmdoption:: -i <indent>
1958 --indent <indent>
1959
1960 Indentation of nodes in AST (number of spaces).
1961
Serhiy Storchaka832e8642019-09-09 23:36:13 +03001962If :file:`infile` is specified its contents are parsed to AST and dumped
1963to stdout. Otherwise, the content is read from stdin.
1964
1965
Senthil Kumaranf3695bf2016-01-06 21:26:53 -08001966.. seealso::
1967
Edward K. Reame3c971c2020-08-11 09:07:49 -05001968 `Green Tree Snakes <https://greentreesnakes.readthedocs.io/>`_, an external
1969 documentation resource, has good details on working with Python ASTs.
1970
1971 `ASTTokens <https://asttokens.readthedocs.io/en/latest/user-guide.html>`_
1972 annotates Python ASTs with the positions of tokens and text in the source
1973 code that generated them. This is helpful for tools that make source code
1974 transformations.
1975
1976 `leoAst.py <http://leoeditor.com/appendices.html#leoast-py>`_ unifies the
1977 token-based and parse-tree-based views of python programs by inserting
1978 two-way links between tokens and ast nodes.
1979
1980 `LibCST <https://libcst.readthedocs.io/>`_ parses code as a Concrete Syntax
1981 Tree that looks like an ast tree and keeps all formatting details. It's
1982 useful for building automated refactoring (codemod) applications and
1983 linters.
1984
1985 `Parso <https://parso.readthedocs.io>`_ is a Python parser that supports
1986 error recovery and round-trip parsing for different Python versions (in
1987 multiple Python versions). Parso is also able to list multiple syntax errors
Batuhan Taskayae799aa82020-10-04 03:46:44 +03001988 in your python file.