Alexander Belopolsky | f0a0d14 | 2010-10-27 03:06:43 +0000 | [diff] [blame] | 1 | :mod:`ast` --- Abstract Syntax Trees |
| 2 | ==================================== |
Georg Brandl | 0c77a82 | 2008-06-10 16:37:50 +0000 | [diff] [blame] | 3 | |
| 4 | .. module:: ast |
| 5 | :synopsis: Abstract Syntax Tree classes and manipulation. |
| 6 | |
| 7 | .. sectionauthor:: Martin v. Löwis <martin@v.loewis.de> |
| 8 | .. sectionauthor:: Georg Brandl <georg@python.org> |
| 9 | |
Pablo Galindo | 114081f | 2020-03-02 03:14:06 +0000 | [diff] [blame] | 10 | .. testsetup:: |
| 11 | |
| 12 | import ast |
| 13 | |
Raymond Hettinger | 1048094 | 2011-01-10 03:26:08 +0000 | [diff] [blame] | 14 | **Source code:** :source:`Lib/ast.py` |
Georg Brandl | 0c77a82 | 2008-06-10 16:37:50 +0000 | [diff] [blame] | 15 | |
Raymond Hettinger | 4f707fd | 2011-01-10 19:54:11 +0000 | [diff] [blame] | 16 | -------------- |
| 17 | |
Georg Brandl | 0c77a82 | 2008-06-10 16:37:50 +0000 | [diff] [blame] | 18 | The :mod:`ast` module helps Python applications to process trees of the Python |
| 19 | abstract syntax grammar. The abstract syntax itself might change with each |
| 20 | Python release; this module helps to find out programmatically what the current |
| 21 | grammar looks like. |
| 22 | |
Benjamin Peterson | ec9199b | 2008-11-08 17:05:00 +0000 | [diff] [blame] | 23 | An abstract syntax tree can be generated by passing :data:`ast.PyCF_ONLY_AST` as |
Georg Brandl | 22b3431 | 2009-07-26 14:54:51 +0000 | [diff] [blame] | 24 | a flag to the :func:`compile` built-in function, or using the :func:`parse` |
Georg Brandl | 0c77a82 | 2008-06-10 16:37:50 +0000 | [diff] [blame] | 25 | helper provided in this module. The result will be a tree of objects whose |
Benjamin Peterson | ec9199b | 2008-11-08 17:05:00 +0000 | [diff] [blame] | 26 | classes all inherit from :class:`ast.AST`. An abstract syntax tree can be |
| 27 | compiled into a Python code object using the built-in :func:`compile` function. |
Georg Brandl | 0c77a82 | 2008-06-10 16:37:50 +0000 | [diff] [blame] | 28 | |
Georg Brandl | 0c77a82 | 2008-06-10 16:37:50 +0000 | [diff] [blame] | 29 | |
Pablo Galindo | 114081f | 2020-03-02 03:14:06 +0000 | [diff] [blame] | 30 | .. _abstract-grammar: |
| 31 | |
| 32 | Abstract Grammar |
| 33 | ---------------- |
| 34 | |
| 35 | The abstract grammar is currently defined as follows: |
| 36 | |
| 37 | .. literalinclude:: ../../Parser/Python.asdl |
Batuhan Taskaya | b7a78ca | 2020-05-07 23:57:26 +0300 | [diff] [blame] | 38 | :language: asdl |
Pablo Galindo | 114081f | 2020-03-02 03:14:06 +0000 | [diff] [blame] | 39 | |
| 40 | |
Georg Brandl | 0c77a82 | 2008-06-10 16:37:50 +0000 | [diff] [blame] | 41 | Node classes |
| 42 | ------------ |
| 43 | |
| 44 | .. class:: AST |
| 45 | |
| 46 | This is the base of all AST node classes. The actual node classes are |
| 47 | derived from the :file:`Parser/Python.asdl` file, which is reproduced |
| 48 | :ref:`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 Storchaka | 913876d | 2018-10-28 13:41:26 +0200 | [diff] [blame] | 59 | .. index:: single: ? (question mark); in AST grammar |
| 60 | .. index:: single: * (asterisk); in AST grammar |
| 61 | |
Georg Brandl | 0c77a82 | 2008-06-10 16:37:50 +0000 | [diff] [blame] | 62 | .. attribute:: _fields |
| 63 | |
| 64 | Each concrete class has an attribute :attr:`_fields` which gives the names |
| 65 | of all child nodes. |
| 66 | |
| 67 | Each instance of a concrete class has one attribute for each child node, |
| 68 | of the type as defined in the grammar. For example, :class:`ast.BinOp` |
| 69 | instances have an attribute :attr:`left` of type :class:`ast.expr`. |
| 70 | |
| 71 | If these attributes are marked as optional in the grammar (using a |
| 72 | question mark), the value might be ``None``. If the attributes can have |
| 73 | zero-or-more values (marked with an asterisk), the values are represented |
| 74 | as Python lists. All possible attributes must be present and have valid |
| 75 | values when compiling an AST with :func:`compile`. |
| 76 | |
| 77 | .. attribute:: lineno |
| 78 | col_offset |
Ivan Levkivskyi | 9932a22 | 2019-01-22 11:18:22 +0000 | [diff] [blame] | 79 | end_lineno |
| 80 | end_col_offset |
Georg Brandl | 0c77a82 | 2008-06-10 16:37:50 +0000 | [diff] [blame] | 81 | |
| 82 | Instances of :class:`ast.expr` and :class:`ast.stmt` subclasses have |
Matthew Suozzo | bffb137 | 2020-11-03 16:28:42 -0500 | [diff] [blame] | 83 | :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 Levkivskyi | 9932a22 | 2019-01-22 11:18:22 +0000 | [diff] [blame] | 90 | |
| 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 Brandl | 0c77a82 | 2008-06-10 16:37:50 +0000 | [diff] [blame] | 95 | |
| 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 Storchaka | 3f22811 | 2018-09-27 17:42:37 +0300 | [diff] [blame] | 108 | node.operand = ast.Constant() |
| 109 | node.operand.value = 5 |
Georg Brandl | 0c77a82 | 2008-06-10 16:37:50 +0000 | [diff] [blame] | 110 | 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 Storchaka | 3f22811 | 2018-09-27 17:42:37 +0300 | [diff] [blame] | 117 | node = ast.UnaryOp(ast.USub(), ast.Constant(5, lineno=0, col_offset=0), |
Georg Brandl | 0c77a82 | 2008-06-10 16:37:50 +0000 | [diff] [blame] | 118 | lineno=0, col_offset=0) |
| 119 | |
Serhiy Storchaka | 85a2eef | 2020-02-17 11:03:00 +0200 | [diff] [blame] | 120 | .. versionchanged:: 3.8 |
| 121 | |
| 122 | Class :class:`ast.Constant` is now used for all constants. |
| 123 | |
Serhiy Storchaka | 13d52c2 | 2020-03-10 18:52:34 +0200 | [diff] [blame] | 124 | .. versionchanged:: 3.9 |
| 125 | |
| 126 | Simple indices are represented by their value, extended slices are |
| 127 | represented as tuples. |
| 128 | |
Serhiy Storchaka | 3f22811 | 2018-09-27 17:42:37 +0300 | [diff] [blame] | 129 | .. deprecated:: 3.8 |
| 130 | |
Serhiy Storchaka | 85a2eef | 2020-02-17 11:03:00 +0200 | [diff] [blame] | 131 | Old classes :class:`ast.Num`, :class:`ast.Str`, :class:`ast.Bytes`, |
Serhiy Storchaka | 3f22811 | 2018-09-27 17:42:37 +0300 | [diff] [blame] | 132 | :class:`ast.NameConstant` and :class:`ast.Ellipsis` are still available, |
Serhiy Storchaka | 13d52c2 | 2020-03-10 18:52:34 +0200 | [diff] [blame] | 133 | but they will be removed in future Python releases. In the meantime, |
Serhiy Storchaka | 85a2eef | 2020-02-17 11:03:00 +0200 | [diff] [blame] | 134 | instantiating them will return an instance of a different class. |
Serhiy Storchaka | 3f22811 | 2018-09-27 17:42:37 +0300 | [diff] [blame] | 135 | |
Serhiy Storchaka | 13d52c2 | 2020-03-10 18:52:34 +0200 | [diff] [blame] | 136 | .. 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 Galindo | 114081f | 2020-03-02 03:14:06 +0000 | [diff] [blame] | 144 | Literals |
| 145 | ^^^^^^^^ |
Georg Brandl | 0c77a82 | 2008-06-10 16:37:50 +0000 | [diff] [blame] | 146 | |
Pablo Galindo | 114081f | 2020-03-02 03:14:06 +0000 | [diff] [blame] | 147 | .. class:: Constant(value) |
Georg Brandl | 0c77a82 | 2008-06-10 16:37:50 +0000 | [diff] [blame] | 148 | |
Pablo Galindo | 114081f | 2020-03-02 03:14:06 +0000 | [diff] [blame] | 149 | 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 Brandl | 0c77a82 | 2008-06-10 16:37:50 +0000 | [diff] [blame] | 153 | |
Pablo Galindo | 114081f | 2020-03-02 03:14:06 +0000 | [diff] [blame] | 154 | .. doctest:: |
Georg Brandl | 0c77a82 | 2008-06-10 16:37:50 +0000 | [diff] [blame] | 155 | |
Pablo Galindo | 02f64cb | 2020-03-07 18:22:58 +0000 | [diff] [blame] | 156 | >>> print(ast.dump(ast.parse('123', mode='eval'), indent=4)) |
| 157 | Expression( |
Serhiy Storchaka | b7e9525 | 2020-03-10 00:07:47 +0200 | [diff] [blame] | 158 | body=Constant(value=123)) |
Pablo Galindo | 114081f | 2020-03-02 03:14:06 +0000 | [diff] [blame] | 159 | |
| 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 Galindo | 02f64cb | 2020-03-07 18:22:58 +0000 | [diff] [blame] | 188 | >>> print(ast.dump(ast.parse('f"sin({a}) is {sin(a):.3}"', mode='eval'), indent=4)) |
| 189 | Expression( |
| 190 | body=JoinedStr( |
| 191 | values=[ |
Serhiy Storchaka | b7e9525 | 2020-03-10 00:07:47 +0200 | [diff] [blame] | 192 | Constant(value='sin('), |
Pablo Galindo | 02f64cb | 2020-03-07 18:22:58 +0000 | [diff] [blame] | 193 | FormattedValue( |
| 194 | value=Name(id='a', ctx=Load()), |
Serhiy Storchaka | b7e9525 | 2020-03-10 00:07:47 +0200 | [diff] [blame] | 195 | conversion=-1), |
| 196 | Constant(value=') is '), |
Pablo Galindo | 02f64cb | 2020-03-07 18:22:58 +0000 | [diff] [blame] | 197 | 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 Storchaka | b7e9525 | 2020-03-10 00:07:47 +0200 | [diff] [blame] | 206 | Constant(value='.3')]))])) |
Pablo Galindo | 114081f | 2020-03-02 03:14:06 +0000 | [diff] [blame] | 207 | |
| 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 Galindo | 02f64cb | 2020-03-07 18:22:58 +0000 | [diff] [blame] | 218 | >>> print(ast.dump(ast.parse('[1, 2, 3]', mode='eval'), indent=4)) |
| 219 | Expression( |
| 220 | body=List( |
| 221 | elts=[ |
Serhiy Storchaka | b7e9525 | 2020-03-10 00:07:47 +0200 | [diff] [blame] | 222 | Constant(value=1), |
| 223 | Constant(value=2), |
| 224 | Constant(value=3)], |
Pablo Galindo | 02f64cb | 2020-03-07 18:22:58 +0000 | [diff] [blame] | 225 | ctx=Load())) |
| 226 | >>> print(ast.dump(ast.parse('(1, 2, 3)', mode='eval'), indent=4)) |
| 227 | Expression( |
| 228 | body=Tuple( |
| 229 | elts=[ |
Serhiy Storchaka | b7e9525 | 2020-03-10 00:07:47 +0200 | [diff] [blame] | 230 | Constant(value=1), |
| 231 | Constant(value=2), |
| 232 | Constant(value=3)], |
Pablo Galindo | 02f64cb | 2020-03-07 18:22:58 +0000 | [diff] [blame] | 233 | ctx=Load())) |
Pablo Galindo | 114081f | 2020-03-02 03:14:06 +0000 | [diff] [blame] | 234 | |
| 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 Galindo | 02f64cb | 2020-03-07 18:22:58 +0000 | [diff] [blame] | 242 | >>> print(ast.dump(ast.parse('{1, 2, 3}', mode='eval'), indent=4)) |
| 243 | Expression( |
| 244 | body=Set( |
| 245 | elts=[ |
Serhiy Storchaka | b7e9525 | 2020-03-10 00:07:47 +0200 | [diff] [blame] | 246 | Constant(value=1), |
| 247 | Constant(value=2), |
| 248 | Constant(value=3)])) |
Pablo Galindo | 114081f | 2020-03-02 03:14:06 +0000 | [diff] [blame] | 249 | |
| 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 Galindo | 02f64cb | 2020-03-07 18:22:58 +0000 | [diff] [blame] | 263 | >>> print(ast.dump(ast.parse('{"a":1, **d}', mode='eval'), indent=4)) |
| 264 | Expression( |
| 265 | body=Dict( |
| 266 | keys=[ |
Serhiy Storchaka | b7e9525 | 2020-03-10 00:07:47 +0200 | [diff] [blame] | 267 | Constant(value='a'), |
Pablo Galindo | 02f64cb | 2020-03-07 18:22:58 +0000 | [diff] [blame] | 268 | None], |
| 269 | values=[ |
Serhiy Storchaka | b7e9525 | 2020-03-10 00:07:47 +0200 | [diff] [blame] | 270 | Constant(value=1), |
Pablo Galindo | 02f64cb | 2020-03-07 18:22:58 +0000 | [diff] [blame] | 271 | Name(id='d', ctx=Load())])) |
Pablo Galindo | 114081f | 2020-03-02 03:14:06 +0000 | [diff] [blame] | 272 | |
| 273 | |
| 274 | Variables |
| 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 Storchaka | b7e9525 | 2020-03-10 00:07:47 +0200 | [diff] [blame] | 306 | value=Constant(value=1))], |
Pablo Galindo | 114081f | 2020-03-02 03:14:06 +0000 | [diff] [blame] | 307 | 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 Storchaka | b7e9525 | 2020-03-10 00:07:47 +0200 | [diff] [blame] | 338 | value=Name(id='it', ctx=Load()))], |
Pablo Galindo | 114081f | 2020-03-02 03:14:06 +0000 | [diff] [blame] | 339 | type_ignores=[]) |
| 340 | |
| 341 | |
| 342 | Expressions |
| 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 Galindo | 02f64cb | 2020-03-07 18:22:58 +0000 | [diff] [blame] | 380 | >>> 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 Galindo | 114081f | 2020-03-02 03:14:06 +0000 | [diff] [blame] | 385 | |
| 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 Galindo | 02f64cb | 2020-03-07 18:22:58 +0000 | [diff] [blame] | 394 | >>> 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 Galindo | 114081f | 2020-03-02 03:14:06 +0000 | [diff] [blame] | 400 | |
| 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 Galindo | 02f64cb | 2020-03-07 18:22:58 +0000 | [diff] [blame] | 430 | >>> 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 Galindo | 114081f | 2020-03-02 03:14:06 +0000 | [diff] [blame] | 437 | |
| 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 Galindo | 02f64cb | 2020-03-07 18:22:58 +0000 | [diff] [blame] | 453 | >>> print(ast.dump(ast.parse('1 <= a < 10', mode='eval'), indent=4)) |
| 454 | Expression( |
| 455 | body=Compare( |
Serhiy Storchaka | b7e9525 | 2020-03-10 00:07:47 +0200 | [diff] [blame] | 456 | left=Constant(value=1), |
Pablo Galindo | 02f64cb | 2020-03-07 18:22:58 +0000 | [diff] [blame] | 457 | ops=[ |
| 458 | LtE(), |
| 459 | Lt()], |
| 460 | comparators=[ |
| 461 | Name(id='a', ctx=Load()), |
Serhiy Storchaka | b7e9525 | 2020-03-10 00:07:47 +0200 | [diff] [blame] | 462 | Constant(value=10)])) |
Pablo Galindo | 114081f | 2020-03-02 03:14:06 +0000 | [diff] [blame] | 463 | |
| 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 Galindo | 02f64cb | 2020-03-07 18:22:58 +0000 | [diff] [blame] | 493 | >>> 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 Galindo | 02f64cb | 2020-03-07 18:22:58 +0000 | [diff] [blame] | 507 | value=Name(id='e', ctx=Load()))])) |
Pablo Galindo | 114081f | 2020-03-02 03:14:06 +0000 | [diff] [blame] | 508 | |
| 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 Galindo | 02f64cb | 2020-03-07 18:22:58 +0000 | [diff] [blame] | 523 | >>> 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 Galindo | 114081f | 2020-03-02 03:14:06 +0000 | [diff] [blame] | 529 | |
| 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 Galindo | 02f64cb | 2020-03-07 18:22:58 +0000 | [diff] [blame] | 540 | >>> 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 Galindo | 114081f | 2020-03-02 03:14:06 +0000 | [diff] [blame] | 546 | |
| 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 Galindo | 02f64cb | 2020-03-07 18:22:58 +0000 | [diff] [blame] | 557 | >>> print(ast.dump(ast.parse('(x := 4)', mode='eval'), indent=4)) |
| 558 | Expression( |
| 559 | body=NamedExpr( |
| 560 | target=Name(id='x', ctx=Store()), |
Serhiy Storchaka | b7e9525 | 2020-03-10 00:07:47 +0200 | [diff] [blame] | 561 | value=Constant(value=4))) |
Pablo Galindo | 114081f | 2020-03-02 03:14:06 +0000 | [diff] [blame] | 562 | |
| 563 | |
| 564 | Subscripting |
| 565 | ~~~~~~~~~~~~ |
| 566 | |
| 567 | .. class:: Subscript(value, slice, ctx) |
| 568 | |
Serhiy Storchaka | 13d52c2 | 2020-03-10 18:52:34 +0200 | [diff] [blame] | 569 | 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 Galindo | 114081f | 2020-03-02 03:14:06 +0000 | [diff] [blame] | 573 | according to the action performed with the subscript. |
| 574 | |
Pablo Galindo | 114081f | 2020-03-02 03:14:06 +0000 | [diff] [blame] | 575 | .. doctest:: |
| 576 | |
Serhiy Storchaka | 13d52c2 | 2020-03-10 18:52:34 +0200 | [diff] [blame] | 577 | >>> print(ast.dump(ast.parse('l[1:2, 3]', mode='eval'), indent=4)) |
Pablo Galindo | 02f64cb | 2020-03-07 18:22:58 +0000 | [diff] [blame] | 578 | Expression( |
| 579 | body=Subscript( |
| 580 | value=Name(id='l', ctx=Load()), |
Serhiy Storchaka | 13d52c2 | 2020-03-10 18:52:34 +0200 | [diff] [blame] | 581 | slice=Tuple( |
| 582 | elts=[ |
| 583 | Slice( |
| 584 | lower=Constant(value=1), |
| 585 | upper=Constant(value=2)), |
| 586 | Constant(value=3)], |
| 587 | ctx=Load()), |
Pablo Galindo | 02f64cb | 2020-03-07 18:22:58 +0000 | [diff] [blame] | 588 | ctx=Load())) |
Pablo Galindo | 114081f | 2020-03-02 03:14:06 +0000 | [diff] [blame] | 589 | |
| 590 | |
| 591 | .. class:: Slice(lower, upper, step) |
| 592 | |
Serhiy Storchaka | 13d52c2 | 2020-03-10 18:52:34 +0200 | [diff] [blame] | 593 | 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 Galindo | 114081f | 2020-03-02 03:14:06 +0000 | [diff] [blame] | 596 | |
| 597 | .. doctest:: |
| 598 | |
Pablo Galindo | 02f64cb | 2020-03-07 18:22:58 +0000 | [diff] [blame] | 599 | >>> 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 Storchaka | b7e9525 | 2020-03-10 00:07:47 +0200 | [diff] [blame] | 604 | lower=Constant(value=1), |
| 605 | upper=Constant(value=2)), |
Pablo Galindo | 02f64cb | 2020-03-07 18:22:58 +0000 | [diff] [blame] | 606 | ctx=Load())) |
Pablo Galindo | 114081f | 2020-03-02 03:14:06 +0000 | [diff] [blame] | 607 | |
| 608 | |
Pablo Galindo | 114081f | 2020-03-02 03:14:06 +0000 | [diff] [blame] | 609 | Comprehensions |
| 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 Galindo | 02f64cb | 2020-03-07 18:22:58 +0000 | [diff] [blame] | 625 | >>> 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 Storchaka | b7e9525 | 2020-03-10 00:07:47 +0200 | [diff] [blame] | 642 | right=Constant(value=2)), |
Pablo Galindo | 02f64cb | 2020-03-07 18:22:58 +0000 | [diff] [blame] | 643 | 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 Galindo | 114081f | 2020-03-02 03:14:06 +0000 | [diff] [blame] | 659 | |
| 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 Galindo | 02f64cb | 2020-03-07 18:22:58 +0000 | [diff] [blame] | 673 | >>> print(ast.dump(ast.parse('[ord(c) for line in file for c in line]', mode='eval'), |
Pablo Galindo | 114081f | 2020-03-02 03:14:06 +0000 | [diff] [blame] | 674 | ... 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 Galindo | 02f64cb | 2020-03-07 18:22:58 +0000 | [diff] [blame] | 694 | >>> print(ast.dump(ast.parse('(n**2 for n in it if n>5 if n<10)', mode='eval'), |
Pablo Galindo | 114081f | 2020-03-02 03:14:06 +0000 | [diff] [blame] | 695 | ... indent=4)) # generator comprehension |
| 696 | Expression( |
| 697 | body=GeneratorExp( |
| 698 | elt=BinOp( |
| 699 | left=Name(id='n', ctx=Load()), |
| 700 | op=Pow(), |
Serhiy Storchaka | b7e9525 | 2020-03-10 00:07:47 +0200 | [diff] [blame] | 701 | right=Constant(value=2)), |
Pablo Galindo | 114081f | 2020-03-02 03:14:06 +0000 | [diff] [blame] | 702 | 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 Storchaka | b7e9525 | 2020-03-10 00:07:47 +0200 | [diff] [blame] | 712 | Constant(value=5)]), |
Pablo Galindo | 114081f | 2020-03-02 03:14:06 +0000 | [diff] [blame] | 713 | Compare( |
| 714 | left=Name(id='n', ctx=Load()), |
| 715 | ops=[ |
| 716 | Lt()], |
| 717 | comparators=[ |
Serhiy Storchaka | b7e9525 | 2020-03-10 00:07:47 +0200 | [diff] [blame] | 718 | Constant(value=10)])], |
Pablo Galindo | 114081f | 2020-03-02 03:14:06 +0000 | [diff] [blame] | 719 | is_async=0)])) |
| 720 | |
Pablo Galindo | 02f64cb | 2020-03-07 18:22:58 +0000 | [diff] [blame] | 721 | >>> print(ast.dump(ast.parse('[i async for i in soc]', mode='eval'), |
Pablo Galindo | 114081f | 2020-03-02 03:14:06 +0000 | [diff] [blame] | 722 | ... indent=4)) # Async comprehension |
Pablo Galindo | 02f64cb | 2020-03-07 18:22:58 +0000 | [diff] [blame] | 723 | 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 Galindo | 114081f | 2020-03-02 03:14:06 +0000 | [diff] [blame] | 732 | |
| 733 | Statements |
| 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 Galindo | 02f64cb | 2020-03-07 18:22:58 +0000 | [diff] [blame] | 750 | >>> print(ast.dump(ast.parse('a = b = 1'), indent=4)) # Multiple assignment |
Pablo Galindo | 114081f | 2020-03-02 03:14:06 +0000 | [diff] [blame] | 751 | Module( |
| 752 | body=[ |
| 753 | Assign( |
| 754 | targets=[ |
| 755 | Name(id='a', ctx=Store()), |
| 756 | Name(id='b', ctx=Store())], |
Serhiy Storchaka | b7e9525 | 2020-03-10 00:07:47 +0200 | [diff] [blame] | 757 | value=Constant(value=1))], |
Pablo Galindo | 114081f | 2020-03-02 03:14:06 +0000 | [diff] [blame] | 758 | type_ignores=[]) |
| 759 | |
Pablo Galindo | 02f64cb | 2020-03-07 18:22:58 +0000 | [diff] [blame] | 760 | >>> print(ast.dump(ast.parse('a,b = c'), indent=4)) # Unpacking |
Pablo Galindo | 114081f | 2020-03-02 03:14:06 +0000 | [diff] [blame] | 761 | 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 Storchaka | b7e9525 | 2020-03-10 00:07:47 +0200 | [diff] [blame] | 770 | value=Name(id='c', ctx=Load()))], |
Pablo Galindo | 114081f | 2020-03-02 03:14:06 +0000 | [diff] [blame] | 771 | 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 Galindo | 02f64cb | 2020-03-07 18:22:58 +0000 | [diff] [blame] | 785 | >>> print(ast.dump(ast.parse('c: int'), indent=4)) |
Pablo Galindo | 114081f | 2020-03-02 03:14:06 +0000 | [diff] [blame] | 786 | Module( |
| 787 | body=[ |
| 788 | AnnAssign( |
| 789 | target=Name(id='c', ctx=Store()), |
| 790 | annotation=Name(id='int', ctx=Load()), |
Pablo Galindo | 114081f | 2020-03-02 03:14:06 +0000 | [diff] [blame] | 791 | simple=1)], |
| 792 | type_ignores=[]) |
| 793 | |
Pablo Galindo | 02f64cb | 2020-03-07 18:22:58 +0000 | [diff] [blame] | 794 | >>> print(ast.dump(ast.parse('(a): int = 1'), indent=4)) # Annotation with parenthesis |
Pablo Galindo | 114081f | 2020-03-02 03:14:06 +0000 | [diff] [blame] | 795 | Module( |
| 796 | body=[ |
| 797 | AnnAssign( |
| 798 | target=Name(id='a', ctx=Store()), |
| 799 | annotation=Name(id='int', ctx=Load()), |
Serhiy Storchaka | b7e9525 | 2020-03-10 00:07:47 +0200 | [diff] [blame] | 800 | value=Constant(value=1), |
Pablo Galindo | 114081f | 2020-03-02 03:14:06 +0000 | [diff] [blame] | 801 | simple=0)], |
| 802 | type_ignores=[]) |
| 803 | |
Pablo Galindo | 02f64cb | 2020-03-07 18:22:58 +0000 | [diff] [blame] | 804 | >>> print(ast.dump(ast.parse('a.b: int'), indent=4)) # Attribute annotation |
Pablo Galindo | 114081f | 2020-03-02 03:14:06 +0000 | [diff] [blame] | 805 | 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 Galindo | 114081f | 2020-03-02 03:14:06 +0000 | [diff] [blame] | 813 | simple=0)], |
| 814 | type_ignores=[]) |
| 815 | |
Pablo Galindo | 02f64cb | 2020-03-07 18:22:58 +0000 | [diff] [blame] | 816 | >>> print(ast.dump(ast.parse('a[1]: int'), indent=4)) # Subscript annotation |
Pablo Galindo | 114081f | 2020-03-02 03:14:06 +0000 | [diff] [blame] | 817 | Module( |
| 818 | body=[ |
| 819 | AnnAssign( |
| 820 | target=Subscript( |
| 821 | value=Name(id='a', ctx=Load()), |
Serhiy Storchaka | 13d52c2 | 2020-03-10 18:52:34 +0200 | [diff] [blame] | 822 | slice=Constant(value=1), |
Pablo Galindo | 114081f | 2020-03-02 03:14:06 +0000 | [diff] [blame] | 823 | ctx=Store()), |
| 824 | annotation=Name(id='int', ctx=Load()), |
Pablo Galindo | 114081f | 2020-03-02 03:14:06 +0000 | [diff] [blame] | 825 | 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 Galindo | 02f64cb | 2020-03-07 18:22:58 +0000 | [diff] [blame] | 841 | >>> print(ast.dump(ast.parse('x += 2'), indent=4)) |
Pablo Galindo | 114081f | 2020-03-02 03:14:06 +0000 | [diff] [blame] | 842 | Module( |
| 843 | body=[ |
| 844 | AugAssign( |
| 845 | target=Name(id='x', ctx=Store()), |
| 846 | op=Add(), |
Serhiy Storchaka | b7e9525 | 2020-03-10 00:07:47 +0200 | [diff] [blame] | 847 | value=Constant(value=2))], |
Pablo Galindo | 114081f | 2020-03-02 03:14:06 +0000 | [diff] [blame] | 848 | 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 Galindo | 02f64cb | 2020-03-07 18:22:58 +0000 | [diff] [blame] | 859 | >>> print(ast.dump(ast.parse('raise x from y'), indent=4)) |
Pablo Galindo | 114081f | 2020-03-02 03:14:06 +0000 | [diff] [blame] | 860 | 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 Galindo | 02f64cb | 2020-03-07 18:22:58 +0000 | [diff] [blame] | 875 | >>> print(ast.dump(ast.parse('assert x,y'), indent=4)) |
Pablo Galindo | 114081f | 2020-03-02 03:14:06 +0000 | [diff] [blame] | 876 | 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 Galindo | 02f64cb | 2020-03-07 18:22:58 +0000 | [diff] [blame] | 891 | >>> print(ast.dump(ast.parse('del x,y,z'), indent=4)) |
Pablo Galindo | 114081f | 2020-03-02 03:14:06 +0000 | [diff] [blame] | 892 | 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 Galindo | 02f64cb | 2020-03-07 18:22:58 +0000 | [diff] [blame] | 908 | >>> print(ast.dump(ast.parse('pass'), indent=4)) |
Pablo Galindo | 114081f | 2020-03-02 03:14:06 +0000 | [diff] [blame] | 909 | Module( |
| 910 | body=[ |
| 911 | Pass()], |
| 912 | type_ignores=[]) |
| 913 | |
| 914 | |
| 915 | Other statements which are only applicable inside functions or loops are |
| 916 | described in other sections. |
| 917 | |
| 918 | Imports |
| 919 | ~~~~~~~ |
| 920 | |
| 921 | .. class:: Import(names) |
| 922 | |
| 923 | An import statement. ``names`` is a list of :class:`alias` nodes. |
| 924 | |
| 925 | .. doctest:: |
| 926 | |
Pablo Galindo | 02f64cb | 2020-03-07 18:22:58 +0000 | [diff] [blame] | 927 | >>> print(ast.dump(ast.parse('import x,y,z'), indent=4)) |
Pablo Galindo | 114081f | 2020-03-02 03:14:06 +0000 | [diff] [blame] | 928 | Module( |
| 929 | body=[ |
| 930 | Import( |
| 931 | names=[ |
Serhiy Storchaka | b7e9525 | 2020-03-10 00:07:47 +0200 | [diff] [blame] | 932 | alias(name='x'), |
| 933 | alias(name='y'), |
| 934 | alias(name='z')])], |
Pablo Galindo | 114081f | 2020-03-02 03:14:06 +0000 | [diff] [blame] | 935 | 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 Galindo | 02f64cb | 2020-03-07 18:22:58 +0000 | [diff] [blame] | 947 | >>> print(ast.dump(ast.parse('from y import x,y,z'), indent=4)) |
Pablo Galindo | 114081f | 2020-03-02 03:14:06 +0000 | [diff] [blame] | 948 | Module( |
| 949 | body=[ |
| 950 | ImportFrom( |
| 951 | module='y', |
| 952 | names=[ |
Serhiy Storchaka | b7e9525 | 2020-03-10 00:07:47 +0200 | [diff] [blame] | 953 | alias(name='x'), |
| 954 | alias(name='y'), |
| 955 | alias(name='z')], |
Pablo Galindo | 114081f | 2020-03-02 03:14:06 +0000 | [diff] [blame] | 956 | 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 Galindo | 02f64cb | 2020-03-07 18:22:58 +0000 | [diff] [blame] | 967 | >>> print(ast.dump(ast.parse('from ..foo.bar import a as b, c'), indent=4)) |
Pablo Galindo | 114081f | 2020-03-02 03:14:06 +0000 | [diff] [blame] | 968 | Module( |
| 969 | body=[ |
| 970 | ImportFrom( |
| 971 | module='foo.bar', |
| 972 | names=[ |
| 973 | alias(name='a', asname='b'), |
Serhiy Storchaka | b7e9525 | 2020-03-10 00:07:47 +0200 | [diff] [blame] | 974 | alias(name='c')], |
Pablo Galindo | 114081f | 2020-03-02 03:14:06 +0000 | [diff] [blame] | 975 | level=2)], |
| 976 | type_ignores=[]) |
| 977 | |
| 978 | Control 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 Storchaka | b7e9525 | 2020-03-10 00:07:47 +0200 | [diff] [blame] | 1010 | value=Constant(value=Ellipsis))], |
Pablo Galindo | 114081f | 2020-03-02 03:14:06 +0000 | [diff] [blame] | 1011 | orelse=[ |
| 1012 | If( |
| 1013 | test=Name(id='y', ctx=Load()), |
| 1014 | body=[ |
| 1015 | Expr( |
Serhiy Storchaka | b7e9525 | 2020-03-10 00:07:47 +0200 | [diff] [blame] | 1016 | value=Constant(value=Ellipsis))], |
Pablo Galindo | 114081f | 2020-03-02 03:14:06 +0000 | [diff] [blame] | 1017 | orelse=[ |
| 1018 | Expr( |
Serhiy Storchaka | b7e9525 | 2020-03-10 00:07:47 +0200 | [diff] [blame] | 1019 | value=Constant(value=Ellipsis))])])], |
Pablo Galindo | 114081f | 2020-03-02 03:14:06 +0000 | [diff] [blame] | 1020 | 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 Storchaka | b7e9525 | 2020-03-10 00:07:47 +0200 | [diff] [blame] | 1050 | value=Constant(value=Ellipsis))], |
Pablo Galindo | 114081f | 2020-03-02 03:14:06 +0000 | [diff] [blame] | 1051 | orelse=[ |
| 1052 | Expr( |
Serhiy Storchaka | b7e9525 | 2020-03-10 00:07:47 +0200 | [diff] [blame] | 1053 | value=Constant(value=Ellipsis))])], |
Pablo Galindo | 114081f | 2020-03-02 03:14:06 +0000 | [diff] [blame] | 1054 | 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 Storchaka | b7e9525 | 2020-03-10 00:07:47 +0200 | [diff] [blame] | 1076 | value=Constant(value=Ellipsis))], |
Pablo Galindo | 114081f | 2020-03-02 03:14:06 +0000 | [diff] [blame] | 1077 | orelse=[ |
| 1078 | Expr( |
Serhiy Storchaka | b7e9525 | 2020-03-10 00:07:47 +0200 | [diff] [blame] | 1079 | value=Constant(value=Ellipsis))])], |
Pablo Galindo | 114081f | 2020-03-02 03:14:06 +0000 | [diff] [blame] | 1080 | 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 Storchaka | b7e9525 | 2020-03-10 00:07:47 +0200 | [diff] [blame] | 1110 | Constant(value=5)]), |
Pablo Galindo | 114081f | 2020-03-02 03:14:06 +0000 | [diff] [blame] | 1111 | body=[ |
| 1112 | Break()], |
| 1113 | orelse=[ |
| 1114 | Continue()])], |
Serhiy Storchaka | b7e9525 | 2020-03-10 00:07:47 +0200 | [diff] [blame] | 1115 | orelse=[])], |
Pablo Galindo | 114081f | 2020-03-02 03:14:06 +0000 | [diff] [blame] | 1116 | 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 Storchaka | b7e9525 | 2020-03-10 00:07:47 +0200 | [diff] [blame] | 1143 | value=Constant(value=Ellipsis))], |
Pablo Galindo | 114081f | 2020-03-02 03:14:06 +0000 | [diff] [blame] | 1144 | handlers=[ |
| 1145 | ExceptHandler( |
| 1146 | type=Name(id='Exception', ctx=Load()), |
Pablo Galindo | 114081f | 2020-03-02 03:14:06 +0000 | [diff] [blame] | 1147 | body=[ |
| 1148 | Expr( |
Serhiy Storchaka | b7e9525 | 2020-03-10 00:07:47 +0200 | [diff] [blame] | 1149 | value=Constant(value=Ellipsis))]), |
Pablo Galindo | 114081f | 2020-03-02 03:14:06 +0000 | [diff] [blame] | 1150 | ExceptHandler( |
| 1151 | type=Name(id='OtherException', ctx=Load()), |
| 1152 | name='e', |
| 1153 | body=[ |
| 1154 | Expr( |
Serhiy Storchaka | b7e9525 | 2020-03-10 00:07:47 +0200 | [diff] [blame] | 1155 | value=Constant(value=Ellipsis))])], |
Pablo Galindo | 114081f | 2020-03-02 03:14:06 +0000 | [diff] [blame] | 1156 | orelse=[ |
| 1157 | Expr( |
Serhiy Storchaka | b7e9525 | 2020-03-10 00:07:47 +0200 | [diff] [blame] | 1158 | value=Constant(value=Ellipsis))], |
Pablo Galindo | 114081f | 2020-03-02 03:14:06 +0000 | [diff] [blame] | 1159 | finalbody=[ |
| 1160 | Expr( |
Serhiy Storchaka | b7e9525 | 2020-03-10 00:07:47 +0200 | [diff] [blame] | 1161 | value=Constant(value=Ellipsis))])], |
Pablo Galindo | 114081f | 2020-03-02 03:14:06 +0000 | [diff] [blame] | 1162 | 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 Storchaka | b7e9525 | 2020-03-10 00:07:47 +0200 | [diff] [blame] | 1188 | right=Constant(value=1)))], |
Pablo Galindo | 114081f | 2020-03-02 03:14:06 +0000 | [diff] [blame] | 1189 | handlers=[ |
| 1190 | ExceptHandler( |
| 1191 | type=Name(id='TypeError', ctx=Load()), |
Pablo Galindo | 114081f | 2020-03-02 03:14:06 +0000 | [diff] [blame] | 1192 | 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 Storchaka | b7e9525 | 2020-03-10 00:07:47 +0200 | [diff] [blame] | 1239 | keywords=[]))])], |
Pablo Galindo | 114081f | 2020-03-02 03:14:06 +0000 | [diff] [blame] | 1240 | type_ignores=[]) |
| 1241 | |
| 1242 | |
| 1243 | Function and class definitions |
| 1244 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 1245 | |
| 1246 | .. class:: FunctionDef(name, args, body, decorator_list, returns, type_comment) |
| 1247 | |
| 1248 | A function definition. |
| 1249 | |
| 1250 | * ``name`` is a raw string of the function name. |
| 1251 | * ``args`` is a :class:`arguments` node. |
| 1252 | * ``body`` is the list of nodes inside the function. |
| 1253 | * ``decorator_list`` is the list of decorators to be applied, stored outermost |
| 1254 | first (i.e. the first in the list will be applied last). |
| 1255 | * ``returns`` is the return annotation. |
| 1256 | |
| 1257 | .. attribute:: type_comment |
| 1258 | |
| 1259 | ``type_comment`` is an optional string with the type annotation as a comment. |
| 1260 | |
| 1261 | |
| 1262 | .. class:: Lambda(args, body) |
| 1263 | |
| 1264 | ``lambda`` is a minimal function definition that can be used inside an |
| 1265 | expression. Unlike :class:`FunctionDef`, ``body`` holds a single node. |
| 1266 | |
| 1267 | .. doctest:: |
| 1268 | |
Pablo Galindo | 02f64cb | 2020-03-07 18:22:58 +0000 | [diff] [blame] | 1269 | >>> print(ast.dump(ast.parse('lambda x,y: ...'), indent=4)) |
Pablo Galindo | 114081f | 2020-03-02 03:14:06 +0000 | [diff] [blame] | 1270 | Module( |
| 1271 | body=[ |
| 1272 | Expr( |
| 1273 | value=Lambda( |
| 1274 | args=arguments( |
| 1275 | posonlyargs=[], |
| 1276 | args=[ |
Serhiy Storchaka | b7e9525 | 2020-03-10 00:07:47 +0200 | [diff] [blame] | 1277 | arg(arg='x'), |
| 1278 | arg(arg='y')], |
Pablo Galindo | 114081f | 2020-03-02 03:14:06 +0000 | [diff] [blame] | 1279 | kwonlyargs=[], |
| 1280 | kw_defaults=[], |
Pablo Galindo | 114081f | 2020-03-02 03:14:06 +0000 | [diff] [blame] | 1281 | defaults=[]), |
Serhiy Storchaka | b7e9525 | 2020-03-10 00:07:47 +0200 | [diff] [blame] | 1282 | body=Constant(value=Ellipsis)))], |
Pablo Galindo | 114081f | 2020-03-02 03:14:06 +0000 | [diff] [blame] | 1283 | type_ignores=[]) |
| 1284 | |
| 1285 | |
| 1286 | .. class:: arguments(posonlyargs, args, vararg, kwonlyargs, kw_defaults, kwarg, defaults) |
| 1287 | |
| 1288 | The arguments for a function. |
| 1289 | |
| 1290 | * ``posonlyargs``, ``args`` and ``kwonlyargs`` are lists of :class:`arg` nodes. |
| 1291 | * ``vararg`` and ``kwarg`` are single :class:`arg` nodes, referring to the |
| 1292 | ``*args, **kwargs`` parameters. |
| 1293 | * ``kw_defaults`` is a list of default values for keyword-only arguments. If |
| 1294 | one is ``None``, the corresponding argument is required. |
| 1295 | * ``defaults`` is a list of default values for arguments that can be passed |
| 1296 | positionally. If there are fewer defaults, they correspond to the last n |
| 1297 | arguments. |
| 1298 | |
| 1299 | |
| 1300 | .. class:: arg(arg, annotation, type_comment) |
| 1301 | |
| 1302 | A single argument in a list. ``arg`` is a raw string of the argument |
| 1303 | name, ``annotation`` is its annotation, such as a :class:`Str` or |
| 1304 | :class:`Name` node. |
| 1305 | |
| 1306 | .. attribute:: type_comment |
| 1307 | |
| 1308 | ``type_comment`` is an optional string with the type annotation as a comment |
| 1309 | |
| 1310 | .. doctest:: |
| 1311 | |
| 1312 | >>> print(ast.dump(ast.parse("""\ |
| 1313 | ... @decorator1 |
| 1314 | ... @decorator2 |
| 1315 | ... def f(a: 'annotation', b=1, c=2, *d, e, f=3, **g) -> 'return annotation': |
| 1316 | ... pass |
| 1317 | ... """), indent=4)) |
| 1318 | Module( |
| 1319 | body=[ |
| 1320 | FunctionDef( |
| 1321 | name='f', |
| 1322 | args=arguments( |
| 1323 | posonlyargs=[], |
| 1324 | args=[ |
| 1325 | arg( |
| 1326 | arg='a', |
Serhiy Storchaka | b7e9525 | 2020-03-10 00:07:47 +0200 | [diff] [blame] | 1327 | annotation=Constant(value='annotation')), |
| 1328 | arg(arg='b'), |
| 1329 | arg(arg='c')], |
| 1330 | vararg=arg(arg='d'), |
Pablo Galindo | 114081f | 2020-03-02 03:14:06 +0000 | [diff] [blame] | 1331 | kwonlyargs=[ |
Serhiy Storchaka | b7e9525 | 2020-03-10 00:07:47 +0200 | [diff] [blame] | 1332 | arg(arg='e'), |
| 1333 | arg(arg='f')], |
Pablo Galindo | 114081f | 2020-03-02 03:14:06 +0000 | [diff] [blame] | 1334 | kw_defaults=[ |
| 1335 | None, |
Serhiy Storchaka | b7e9525 | 2020-03-10 00:07:47 +0200 | [diff] [blame] | 1336 | Constant(value=3)], |
| 1337 | kwarg=arg(arg='g'), |
Pablo Galindo | 114081f | 2020-03-02 03:14:06 +0000 | [diff] [blame] | 1338 | defaults=[ |
Serhiy Storchaka | b7e9525 | 2020-03-10 00:07:47 +0200 | [diff] [blame] | 1339 | Constant(value=1), |
| 1340 | Constant(value=2)]), |
Pablo Galindo | 114081f | 2020-03-02 03:14:06 +0000 | [diff] [blame] | 1341 | body=[ |
| 1342 | Pass()], |
| 1343 | decorator_list=[ |
| 1344 | Name(id='decorator1', ctx=Load()), |
| 1345 | Name(id='decorator2', ctx=Load())], |
Serhiy Storchaka | b7e9525 | 2020-03-10 00:07:47 +0200 | [diff] [blame] | 1346 | returns=Constant(value='return annotation'))], |
Pablo Galindo | 114081f | 2020-03-02 03:14:06 +0000 | [diff] [blame] | 1347 | type_ignores=[]) |
| 1348 | |
| 1349 | |
| 1350 | .. class:: Return(value) |
| 1351 | |
| 1352 | A ``return`` statement. |
| 1353 | |
| 1354 | .. doctest:: |
| 1355 | |
Pablo Galindo | 02f64cb | 2020-03-07 18:22:58 +0000 | [diff] [blame] | 1356 | >>> print(ast.dump(ast.parse('return 4'), indent=4)) |
Pablo Galindo | 114081f | 2020-03-02 03:14:06 +0000 | [diff] [blame] | 1357 | Module( |
| 1358 | body=[ |
| 1359 | Return( |
Serhiy Storchaka | b7e9525 | 2020-03-10 00:07:47 +0200 | [diff] [blame] | 1360 | value=Constant(value=4))], |
Pablo Galindo | 114081f | 2020-03-02 03:14:06 +0000 | [diff] [blame] | 1361 | type_ignores=[]) |
| 1362 | |
| 1363 | |
| 1364 | .. class:: Yield(value) |
| 1365 | YieldFrom(value) |
| 1366 | |
| 1367 | A ``yield`` or ``yield from`` expression. Because these are expressions, they |
| 1368 | must be wrapped in a :class:`Expr` node if the value sent back is not used. |
| 1369 | |
| 1370 | .. doctest:: |
| 1371 | |
Pablo Galindo | 02f64cb | 2020-03-07 18:22:58 +0000 | [diff] [blame] | 1372 | >>> print(ast.dump(ast.parse('yield x'), indent=4)) |
Pablo Galindo | 114081f | 2020-03-02 03:14:06 +0000 | [diff] [blame] | 1373 | Module( |
| 1374 | body=[ |
| 1375 | Expr( |
| 1376 | value=Yield( |
| 1377 | value=Name(id='x', ctx=Load())))], |
| 1378 | type_ignores=[]) |
| 1379 | |
Pablo Galindo | 02f64cb | 2020-03-07 18:22:58 +0000 | [diff] [blame] | 1380 | >>> print(ast.dump(ast.parse('yield from x'), indent=4)) |
Pablo Galindo | 114081f | 2020-03-02 03:14:06 +0000 | [diff] [blame] | 1381 | Module( |
| 1382 | body=[ |
| 1383 | Expr( |
| 1384 | value=YieldFrom( |
| 1385 | value=Name(id='x', ctx=Load())))], |
| 1386 | type_ignores=[]) |
| 1387 | |
| 1388 | |
| 1389 | .. class:: Global(names) |
| 1390 | Nonlocal(names) |
| 1391 | |
| 1392 | ``global`` and ``nonlocal`` statements. ``names`` is a list of raw strings. |
| 1393 | |
| 1394 | .. doctest:: |
| 1395 | |
Pablo Galindo | 02f64cb | 2020-03-07 18:22:58 +0000 | [diff] [blame] | 1396 | >>> print(ast.dump(ast.parse('global x,y,z'), indent=4)) |
Pablo Galindo | 114081f | 2020-03-02 03:14:06 +0000 | [diff] [blame] | 1397 | Module( |
| 1398 | body=[ |
| 1399 | Global( |
| 1400 | names=[ |
| 1401 | 'x', |
| 1402 | 'y', |
| 1403 | 'z'])], |
| 1404 | type_ignores=[]) |
| 1405 | |
Pablo Galindo | 02f64cb | 2020-03-07 18:22:58 +0000 | [diff] [blame] | 1406 | >>> print(ast.dump(ast.parse('nonlocal x,y,z'), indent=4)) |
Pablo Galindo | 114081f | 2020-03-02 03:14:06 +0000 | [diff] [blame] | 1407 | Module( |
| 1408 | body=[ |
| 1409 | Nonlocal( |
| 1410 | names=[ |
| 1411 | 'x', |
| 1412 | 'y', |
| 1413 | 'z'])], |
| 1414 | type_ignores=[]) |
| 1415 | |
| 1416 | |
| 1417 | .. class:: ClassDef(name, bases, keywords, starargs, kwargs, body, decorator_list) |
| 1418 | |
| 1419 | A class definition. |
| 1420 | |
| 1421 | * ``name`` is a raw string for the class name |
| 1422 | * ``bases`` is a list of nodes for explicitly specified base classes. |
| 1423 | * ``keywords`` is a list of :class:`keyword` nodes, principally for 'metaclass'. |
| 1424 | Other keywords will be passed to the metaclass, as per `PEP-3115 |
| 1425 | <http://www.python.org/dev/peps/pep-3115/>`_. |
| 1426 | * ``starargs`` and ``kwargs`` are each a single node, as in a function call. |
| 1427 | starargs will be expanded to join the list of base classes, and kwargs will |
| 1428 | be passed to the metaclass. |
| 1429 | * ``body`` is a list of nodes representing the code within the class |
| 1430 | definition. |
| 1431 | * ``decorator_list`` is a list of nodes, as in :class:`FunctionDef`. |
| 1432 | |
| 1433 | .. doctest:: |
| 1434 | |
| 1435 | >>> print(ast.dump(ast.parse("""\ |
| 1436 | ... @decorator1 |
| 1437 | ... @decorator2 |
| 1438 | ... class Foo(base1, base2, metaclass=meta): |
| 1439 | ... pass |
| 1440 | ... """), indent=4)) |
| 1441 | Module( |
| 1442 | body=[ |
| 1443 | ClassDef( |
| 1444 | name='Foo', |
| 1445 | bases=[ |
| 1446 | Name(id='base1', ctx=Load()), |
| 1447 | Name(id='base2', ctx=Load())], |
| 1448 | keywords=[ |
| 1449 | keyword( |
| 1450 | arg='metaclass', |
| 1451 | value=Name(id='meta', ctx=Load()))], |
| 1452 | body=[ |
| 1453 | Pass()], |
| 1454 | decorator_list=[ |
| 1455 | Name(id='decorator1', ctx=Load()), |
| 1456 | Name(id='decorator2', ctx=Load())])], |
| 1457 | type_ignores=[]) |
| 1458 | |
| 1459 | Async and await |
| 1460 | ^^^^^^^^^^^^^^^ |
| 1461 | |
| 1462 | .. class:: AsyncFunctionDef(name, args, body, decorator_list, returns, type_comment) |
| 1463 | |
| 1464 | An ``async def`` function definition. Has the same fields as |
| 1465 | :class:`FunctionDef`. |
| 1466 | |
| 1467 | |
| 1468 | .. class:: Await(value) |
| 1469 | |
| 1470 | An ``await`` expression. ``value`` is what it waits for. |
| 1471 | Only valid in the body of an :class:`AsyncFunctionDef`. |
| 1472 | |
| 1473 | .. doctest:: |
| 1474 | |
| 1475 | >>> print(ast.dump(ast.parse("""\ |
| 1476 | ... async def f(): |
| 1477 | ... await other_func() |
| 1478 | ... """), indent=4)) |
| 1479 | Module( |
| 1480 | body=[ |
| 1481 | AsyncFunctionDef( |
| 1482 | name='f', |
| 1483 | args=arguments( |
| 1484 | posonlyargs=[], |
| 1485 | args=[], |
Pablo Galindo | 114081f | 2020-03-02 03:14:06 +0000 | [diff] [blame] | 1486 | kwonlyargs=[], |
| 1487 | kw_defaults=[], |
Pablo Galindo | 114081f | 2020-03-02 03:14:06 +0000 | [diff] [blame] | 1488 | defaults=[]), |
| 1489 | body=[ |
| 1490 | Expr( |
| 1491 | value=Await( |
| 1492 | value=Call( |
| 1493 | func=Name(id='other_func', ctx=Load()), |
| 1494 | args=[], |
| 1495 | keywords=[])))], |
Serhiy Storchaka | b7e9525 | 2020-03-10 00:07:47 +0200 | [diff] [blame] | 1496 | decorator_list=[])], |
Pablo Galindo | 114081f | 2020-03-02 03:14:06 +0000 | [diff] [blame] | 1497 | type_ignores=[]) |
| 1498 | |
| 1499 | |
| 1500 | .. class:: AsyncFor(target, iter, body, orelse, type_comment) |
| 1501 | AsyncWith(items, body, type_comment) |
| 1502 | |
| 1503 | ``async for`` loops and ``async with`` context managers. They have the same |
| 1504 | fields as :class:`For` and :class:`With`, respectively. Only valid in the |
| 1505 | body of an :class:`AsyncFunctionDef`. |
Georg Brandl | 0c77a82 | 2008-06-10 16:37:50 +0000 | [diff] [blame] | 1506 | |
Batuhan Taskaya | b37c994 | 2020-10-22 19:02:43 +0300 | [diff] [blame] | 1507 | .. note:: |
| 1508 | When a string is parsed by :func:`ast.parse`, operator nodes (subclasses |
| 1509 | of :class:`ast.operator`, :class:`ast.unaryop`, :class:`ast.cmpop`, |
| 1510 | :class:`ast.boolop` and :class:`ast.expr_context`) on the returned tree |
| 1511 | will be singletons. Changes to one will be reflected in all other |
| 1512 | occurrences of the same value (e.g. :class:`ast.Add`). |
| 1513 | |
Georg Brandl | 0c77a82 | 2008-06-10 16:37:50 +0000 | [diff] [blame] | 1514 | |
| 1515 | :mod:`ast` Helpers |
| 1516 | ------------------ |
| 1517 | |
Martin Panter | 2e4571a | 2015-11-14 01:07:43 +0000 | [diff] [blame] | 1518 | Apart from the node classes, the :mod:`ast` module defines these utility functions |
Georg Brandl | 0c77a82 | 2008-06-10 16:37:50 +0000 | [diff] [blame] | 1519 | and classes for traversing abstract syntax trees: |
| 1520 | |
Guido van Rossum | 10b55c1 | 2019-06-11 17:23:12 -0700 | [diff] [blame] | 1521 | .. function:: parse(source, filename='<unknown>', mode='exec', *, type_comments=False, feature_version=None) |
Georg Brandl | 0c77a82 | 2008-06-10 16:37:50 +0000 | [diff] [blame] | 1522 | |
Terry Reedy | feac624 | 2011-01-24 21:36:03 +0000 | [diff] [blame] | 1523 | Parse the source into an AST node. Equivalent to ``compile(source, |
Benjamin Peterson | ec9199b | 2008-11-08 17:05:00 +0000 | [diff] [blame] | 1524 | filename, mode, ast.PyCF_ONLY_AST)``. |
Georg Brandl | 0c77a82 | 2008-06-10 16:37:50 +0000 | [diff] [blame] | 1525 | |
Guido van Rossum | dcfcd14 | 2019-01-31 03:40:27 -0800 | [diff] [blame] | 1526 | If ``type_comments=True`` is given, the parser is modified to check |
| 1527 | and return type comments as specified by :pep:`484` and :pep:`526`. |
| 1528 | This is equivalent to adding :data:`ast.PyCF_TYPE_COMMENTS` to the |
| 1529 | flags passed to :func:`compile()`. This will report syntax errors |
| 1530 | for misplaced type comments. Without this flag, type comments will |
| 1531 | be ignored, and the ``type_comment`` field on selected AST nodes |
| 1532 | will always be ``None``. In addition, the locations of ``# type: |
| 1533 | ignore`` comments will be returned as the ``type_ignores`` |
| 1534 | attribute of :class:`Module` (otherwise it is always an empty list). |
| 1535 | |
| 1536 | In addition, if ``mode`` is ``'func_type'``, the input syntax is |
| 1537 | modified to correspond to :pep:`484` "signature type comments", |
| 1538 | e.g. ``(str, int) -> List[str]``. |
| 1539 | |
Guido van Rossum | 10b55c1 | 2019-06-11 17:23:12 -0700 | [diff] [blame] | 1540 | Also, setting ``feature_version`` to a tuple ``(major, minor)`` |
| 1541 | will attempt to parse using that Python version's grammar. |
| 1542 | Currently ``major`` must equal to ``3``. For example, setting |
| 1543 | ``feature_version=(3, 4)`` will allow the use of ``async`` and |
| 1544 | ``await`` as variable names. The lowest supported version is |
| 1545 | ``(3, 4)``; the highest is ``sys.version_info[0:2]``. |
Guido van Rossum | 495da29 | 2019-03-07 12:38:08 -0800 | [diff] [blame] | 1546 | |
Brett Cannon | 7a7f100 | 2018-03-09 12:03:22 -0800 | [diff] [blame] | 1547 | .. warning:: |
| 1548 | It is possible to crash the Python interpreter with a |
| 1549 | sufficiently large/complex string due to stack depth limitations |
| 1550 | in Python's AST compiler. |
| 1551 | |
Guido van Rossum | dcfcd14 | 2019-01-31 03:40:27 -0800 | [diff] [blame] | 1552 | .. versionchanged:: 3.8 |
Guido van Rossum | 495da29 | 2019-03-07 12:38:08 -0800 | [diff] [blame] | 1553 | Added ``type_comments``, ``mode='func_type'`` and ``feature_version``. |
Guido van Rossum | dcfcd14 | 2019-01-31 03:40:27 -0800 | [diff] [blame] | 1554 | |
Georg Brandl | 48310cd | 2009-01-03 21:18:54 +0000 | [diff] [blame] | 1555 | |
Pablo Galindo | 27fc3b6 | 2019-11-24 23:02:40 +0000 | [diff] [blame] | 1556 | .. function:: unparse(ast_obj) |
| 1557 | |
| 1558 | Unparse an :class:`ast.AST` object and generate a string with code |
| 1559 | that would produce an equivalent :class:`ast.AST` object if parsed |
| 1560 | back with :func:`ast.parse`. |
| 1561 | |
| 1562 | .. warning:: |
Gurupad Hegde | 6c7bb38 | 2019-12-28 17:16:02 -0500 | [diff] [blame] | 1563 | The produced code string will not necessarily be equal to the original |
Batuhan Taskaya | 8df1016 | 2020-06-28 04:11:43 +0300 | [diff] [blame] | 1564 | code that generated the :class:`ast.AST` object (without any compiler |
| 1565 | optimizations, such as constant tuples/frozensets). |
| 1566 | |
| 1567 | .. warning:: |
| 1568 | Trying to unparse a highly complex expression would result with |
| 1569 | :exc:`RecursionError`. |
Pablo Galindo | 27fc3b6 | 2019-11-24 23:02:40 +0000 | [diff] [blame] | 1570 | |
| 1571 | .. versionadded:: 3.9 |
| 1572 | |
| 1573 | |
Georg Brandl | 0c77a82 | 2008-06-10 16:37:50 +0000 | [diff] [blame] | 1574 | .. function:: literal_eval(node_or_string) |
| 1575 | |
Georg Brandl | b9b389e | 2014-11-05 20:20:28 +0100 | [diff] [blame] | 1576 | Safely evaluate an expression node or a string containing a Python literal or |
| 1577 | container display. The string or node provided may only consist of the |
| 1578 | following Python literal structures: strings, bytes, numbers, tuples, lists, |
| 1579 | dicts, sets, booleans, and ``None``. |
Georg Brandl | 0c77a82 | 2008-06-10 16:37:50 +0000 | [diff] [blame] | 1580 | |
Georg Brandl | b9b389e | 2014-11-05 20:20:28 +0100 | [diff] [blame] | 1581 | This can be used for safely evaluating strings containing Python values from |
| 1582 | untrusted sources without the need to parse the values oneself. It is not |
| 1583 | capable of evaluating arbitrarily complex expressions, for example involving |
| 1584 | operators or indexing. |
Georg Brandl | 0c77a82 | 2008-06-10 16:37:50 +0000 | [diff] [blame] | 1585 | |
Brett Cannon | 7a7f100 | 2018-03-09 12:03:22 -0800 | [diff] [blame] | 1586 | .. warning:: |
| 1587 | It is possible to crash the Python interpreter with a |
| 1588 | sufficiently large/complex string due to stack depth limitations |
| 1589 | in Python's AST compiler. |
| 1590 | |
Georg Brandl | 492f3fc | 2010-07-11 09:41:21 +0000 | [diff] [blame] | 1591 | .. versionchanged:: 3.2 |
Georg Brandl | 85f2177 | 2010-07-13 06:38:10 +0000 | [diff] [blame] | 1592 | Now allows bytes and set literals. |
Georg Brandl | 492f3fc | 2010-07-11 09:41:21 +0000 | [diff] [blame] | 1593 | |
Raymond Hettinger | 4fcf5c1 | 2020-01-02 22:21:18 -0700 | [diff] [blame] | 1594 | .. versionchanged:: 3.9 |
| 1595 | Now supports creating empty sets with ``'set()'``. |
| 1596 | |
Batuhan Taskaya | e799aa8 | 2020-10-04 03:46:44 +0300 | [diff] [blame] | 1597 | .. versionchanged:: 3.10 |
| 1598 | For string inputs, leading spaces and tabs are now stripped. |
| 1599 | |
Georg Brandl | 0c77a82 | 2008-06-10 16:37:50 +0000 | [diff] [blame] | 1600 | |
Amaury Forgeot d'Arc | fdfe62d | 2008-06-17 20:36:03 +0000 | [diff] [blame] | 1601 | .. function:: get_docstring(node, clean=True) |
Georg Brandl | 0c77a82 | 2008-06-10 16:37:50 +0000 | [diff] [blame] | 1602 | |
| 1603 | Return the docstring of the given *node* (which must be a |
INADA Naoki | cb41b27 | 2017-02-23 00:31:59 +0900 | [diff] [blame] | 1604 | :class:`FunctionDef`, :class:`AsyncFunctionDef`, :class:`ClassDef`, |
| 1605 | or :class:`Module` node), or ``None`` if it has no docstring. |
| 1606 | If *clean* is true, clean up the docstring's indentation with |
| 1607 | :func:`inspect.cleandoc`. |
| 1608 | |
| 1609 | .. versionchanged:: 3.5 |
| 1610 | :class:`AsyncFunctionDef` is now supported. |
| 1611 | |
Georg Brandl | 0c77a82 | 2008-06-10 16:37:50 +0000 | [diff] [blame] | 1612 | |
Ivan Levkivskyi | 9932a22 | 2019-01-22 11:18:22 +0000 | [diff] [blame] | 1613 | .. function:: get_source_segment(source, node, *, padded=False) |
| 1614 | |
| 1615 | Get source code segment of the *source* that generated *node*. |
| 1616 | If some location information (:attr:`lineno`, :attr:`end_lineno`, |
| 1617 | :attr:`col_offset`, or :attr:`end_col_offset`) is missing, return ``None``. |
| 1618 | |
| 1619 | If *padded* is ``True``, the first line of a multi-line statement will |
| 1620 | be padded with spaces to match its original position. |
| 1621 | |
| 1622 | .. versionadded:: 3.8 |
| 1623 | |
| 1624 | |
Georg Brandl | 0c77a82 | 2008-06-10 16:37:50 +0000 | [diff] [blame] | 1625 | .. function:: fix_missing_locations(node) |
| 1626 | |
| 1627 | When you compile a node tree with :func:`compile`, the compiler expects |
| 1628 | :attr:`lineno` and :attr:`col_offset` attributes for every node that supports |
| 1629 | them. This is rather tedious to fill in for generated nodes, so this helper |
| 1630 | adds these attributes recursively where not already set, by setting them to |
| 1631 | the values of the parent node. It works recursively starting at *node*. |
| 1632 | |
| 1633 | |
| 1634 | .. function:: increment_lineno(node, n=1) |
| 1635 | |
Ivan Levkivskyi | 9932a22 | 2019-01-22 11:18:22 +0000 | [diff] [blame] | 1636 | Increment the line number and end line number of each node in the tree |
| 1637 | starting at *node* by *n*. This is useful to "move code" to a different |
| 1638 | location in a file. |
Georg Brandl | 0c77a82 | 2008-06-10 16:37:50 +0000 | [diff] [blame] | 1639 | |
| 1640 | |
| 1641 | .. function:: copy_location(new_node, old_node) |
| 1642 | |
Ivan Levkivskyi | 9932a22 | 2019-01-22 11:18:22 +0000 | [diff] [blame] | 1643 | Copy source location (:attr:`lineno`, :attr:`col_offset`, :attr:`end_lineno`, |
| 1644 | and :attr:`end_col_offset`) from *old_node* to *new_node* if possible, |
| 1645 | and return *new_node*. |
Georg Brandl | 0c77a82 | 2008-06-10 16:37:50 +0000 | [diff] [blame] | 1646 | |
| 1647 | |
| 1648 | .. function:: iter_fields(node) |
| 1649 | |
| 1650 | Yield a tuple of ``(fieldname, value)`` for each field in ``node._fields`` |
| 1651 | that is present on *node*. |
| 1652 | |
| 1653 | |
| 1654 | .. function:: iter_child_nodes(node) |
| 1655 | |
| 1656 | Yield all direct child nodes of *node*, that is, all fields that are nodes |
| 1657 | and all items of fields that are lists of nodes. |
| 1658 | |
| 1659 | |
| 1660 | .. function:: walk(node) |
| 1661 | |
Georg Brandl | 619e7ba | 2011-01-09 07:38:51 +0000 | [diff] [blame] | 1662 | Recursively yield all descendant nodes in the tree starting at *node* |
| 1663 | (including *node* itself), in no specified order. This is useful if you only |
| 1664 | want to modify nodes in place and don't care about the context. |
Georg Brandl | 0c77a82 | 2008-06-10 16:37:50 +0000 | [diff] [blame] | 1665 | |
| 1666 | |
| 1667 | .. class:: NodeVisitor() |
| 1668 | |
| 1669 | A node visitor base class that walks the abstract syntax tree and calls a |
| 1670 | visitor function for every node found. This function may return a value |
Georg Brandl | 36ab1ef | 2009-01-03 21:17:04 +0000 | [diff] [blame] | 1671 | which is forwarded by the :meth:`visit` method. |
Georg Brandl | 0c77a82 | 2008-06-10 16:37:50 +0000 | [diff] [blame] | 1672 | |
| 1673 | This class is meant to be subclassed, with the subclass adding visitor |
| 1674 | methods. |
| 1675 | |
| 1676 | .. method:: visit(node) |
| 1677 | |
| 1678 | Visit a node. The default implementation calls the method called |
| 1679 | :samp:`self.visit_{classname}` where *classname* is the name of the node |
| 1680 | class, or :meth:`generic_visit` if that method doesn't exist. |
| 1681 | |
| 1682 | .. method:: generic_visit(node) |
| 1683 | |
| 1684 | This visitor calls :meth:`visit` on all children of the node. |
Georg Brandl | 48310cd | 2009-01-03 21:18:54 +0000 | [diff] [blame] | 1685 | |
Georg Brandl | 0c77a82 | 2008-06-10 16:37:50 +0000 | [diff] [blame] | 1686 | Note that child nodes of nodes that have a custom visitor method won't be |
| 1687 | visited unless the visitor calls :meth:`generic_visit` or visits them |
| 1688 | itself. |
| 1689 | |
| 1690 | Don't use the :class:`NodeVisitor` if you want to apply changes to nodes |
| 1691 | during traversal. For this a special visitor exists |
| 1692 | (:class:`NodeTransformer`) that allows modifications. |
| 1693 | |
Serhiy Storchaka | c3ea41e | 2019-08-26 10:13:19 +0300 | [diff] [blame] | 1694 | .. deprecated:: 3.8 |
| 1695 | |
| 1696 | Methods :meth:`visit_Num`, :meth:`visit_Str`, :meth:`visit_Bytes`, |
| 1697 | :meth:`visit_NameConstant` and :meth:`visit_Ellipsis` are deprecated |
| 1698 | now and will not be called in future Python versions. Add the |
| 1699 | :meth:`visit_Constant` method to handle all constant nodes. |
| 1700 | |
Georg Brandl | 0c77a82 | 2008-06-10 16:37:50 +0000 | [diff] [blame] | 1701 | |
| 1702 | .. class:: NodeTransformer() |
| 1703 | |
| 1704 | A :class:`NodeVisitor` subclass that walks the abstract syntax tree and |
| 1705 | allows modification of nodes. |
| 1706 | |
Georg Brandl | 36ab1ef | 2009-01-03 21:17:04 +0000 | [diff] [blame] | 1707 | The :class:`NodeTransformer` will walk the AST and use the return value of |
| 1708 | the visitor methods to replace or remove the old node. If the return value |
| 1709 | of the visitor method is ``None``, the node will be removed from its |
| 1710 | location, otherwise it is replaced with the return value. The return value |
| 1711 | may be the original node in which case no replacement takes place. |
Georg Brandl | 0c77a82 | 2008-06-10 16:37:50 +0000 | [diff] [blame] | 1712 | |
| 1713 | Here is an example transformer that rewrites all occurrences of name lookups |
| 1714 | (``foo``) to ``data['foo']``:: |
| 1715 | |
| 1716 | class RewriteName(NodeTransformer): |
| 1717 | |
| 1718 | def visit_Name(self, node): |
Batuhan Taşkaya | 6680f4a | 2020-01-12 23:38:53 +0300 | [diff] [blame] | 1719 | return Subscript( |
Georg Brandl | 0c77a82 | 2008-06-10 16:37:50 +0000 | [diff] [blame] | 1720 | value=Name(id='data', ctx=Load()), |
Serhiy Storchaka | 13d52c2 | 2020-03-10 18:52:34 +0200 | [diff] [blame] | 1721 | slice=Constant(value=node.id), |
Georg Brandl | 0c77a82 | 2008-06-10 16:37:50 +0000 | [diff] [blame] | 1722 | ctx=node.ctx |
Pablo Galindo | c00c86b | 2020-03-12 00:48:19 +0000 | [diff] [blame] | 1723 | ) |
Georg Brandl | 0c77a82 | 2008-06-10 16:37:50 +0000 | [diff] [blame] | 1724 | |
| 1725 | Keep in mind that if the node you're operating on has child nodes you must |
| 1726 | either transform the child nodes yourself or call the :meth:`generic_visit` |
| 1727 | method for the node first. |
| 1728 | |
| 1729 | For nodes that were part of a collection of statements (that applies to all |
| 1730 | statement nodes), the visitor may also return a list of nodes rather than |
| 1731 | just a single node. |
| 1732 | |
Batuhan Taşkaya | 6680f4a | 2020-01-12 23:38:53 +0300 | [diff] [blame] | 1733 | If :class:`NodeTransformer` introduces new nodes (that weren't part of |
| 1734 | original tree) without giving them location information (such as |
| 1735 | :attr:`lineno`), :func:`fix_missing_locations` should be called with |
| 1736 | the new sub-tree to recalculate the location information:: |
| 1737 | |
| 1738 | tree = ast.parse('foo', mode='eval') |
| 1739 | new_tree = fix_missing_locations(RewriteName().visit(tree)) |
| 1740 | |
Georg Brandl | 0c77a82 | 2008-06-10 16:37:50 +0000 | [diff] [blame] | 1741 | Usually you use the transformer like this:: |
| 1742 | |
| 1743 | node = YourTransformer().visit(node) |
| 1744 | |
| 1745 | |
Serhiy Storchaka | 850573b | 2019-09-09 19:33:13 +0300 | [diff] [blame] | 1746 | .. function:: dump(node, annotate_fields=True, include_attributes=False, *, indent=None) |
Georg Brandl | 0c77a82 | 2008-06-10 16:37:50 +0000 | [diff] [blame] | 1747 | |
| 1748 | Return a formatted dump of the tree in *node*. This is mainly useful for |
Serhiy Storchaka | e64f948 | 2019-08-29 09:30:23 +0300 | [diff] [blame] | 1749 | debugging purposes. If *annotate_fields* is true (by default), |
| 1750 | the returned string will show the names and the values for fields. |
| 1751 | If *annotate_fields* is false, the result string will be more compact by |
| 1752 | omitting unambiguous field names. Attributes such as line |
Benjamin Peterson | dcf97b9 | 2008-07-02 17:30:14 +0000 | [diff] [blame] | 1753 | numbers and column offsets are not dumped by default. If this is wanted, |
Serhiy Storchaka | e64f948 | 2019-08-29 09:30:23 +0300 | [diff] [blame] | 1754 | *include_attributes* can be set to true. |
Senthil Kumaran | f3695bf | 2016-01-06 21:26:53 -0800 | [diff] [blame] | 1755 | |
Serhiy Storchaka | 850573b | 2019-09-09 19:33:13 +0300 | [diff] [blame] | 1756 | If *indent* is a non-negative integer or string, then the tree will be |
| 1757 | pretty-printed with that indent level. An indent level |
| 1758 | of 0, negative, or ``""`` will only insert newlines. ``None`` (the default) |
| 1759 | selects the single line representation. Using a positive integer indent |
| 1760 | indents that many spaces per level. If *indent* is a string (such as ``"\t"``), |
| 1761 | that string is used to indent each level. |
| 1762 | |
| 1763 | .. versionchanged:: 3.9 |
| 1764 | Added the *indent* option. |
| 1765 | |
| 1766 | |
Batuhan Taskaya | 1559389 | 2020-10-19 04:14:11 +0300 | [diff] [blame] | 1767 | .. _ast-compiler-flags: |
| 1768 | |
| 1769 | Compiler Flags |
| 1770 | -------------- |
| 1771 | |
| 1772 | The following flags may be passed to :func:`compile` in order to change |
| 1773 | effects on the compilation of a program: |
| 1774 | |
| 1775 | .. data:: PyCF_ALLOW_TOP_LEVEL_AWAIT |
| 1776 | |
| 1777 | Enables support for top-level ``await``, ``async for``, ``async with`` |
| 1778 | and async comprehensions. |
| 1779 | |
| 1780 | .. versionadded:: 3.8 |
| 1781 | |
| 1782 | .. data:: PyCF_ONLY_AST |
| 1783 | |
| 1784 | Generates and returns an abstract syntax tree instead of returning a |
| 1785 | compiled code object. |
| 1786 | |
| 1787 | .. data:: PyCF_TYPE_COMMENTS |
| 1788 | |
| 1789 | Enables support for :pep:`484` and :pep:`526` style type comments |
| 1790 | (``# type: <type>``, ``# type: ignore <stuff>``). |
| 1791 | |
| 1792 | .. versionadded:: 3.8 |
| 1793 | |
| 1794 | |
Serhiy Storchaka | 832e864 | 2019-09-09 23:36:13 +0300 | [diff] [blame] | 1795 | .. _ast-cli: |
| 1796 | |
| 1797 | Command-Line Usage |
| 1798 | ------------------ |
| 1799 | |
| 1800 | .. versionadded:: 3.9 |
| 1801 | |
| 1802 | The :mod:`ast` module can be executed as a script from the command line. |
| 1803 | It is as simple as: |
| 1804 | |
| 1805 | .. code-block:: sh |
| 1806 | |
| 1807 | python -m ast [-m <mode>] [-a] [infile] |
| 1808 | |
| 1809 | The following options are accepted: |
| 1810 | |
| 1811 | .. program:: ast |
| 1812 | |
| 1813 | .. cmdoption:: -h, --help |
| 1814 | |
| 1815 | Show the help message and exit. |
| 1816 | |
| 1817 | .. cmdoption:: -m <mode> |
| 1818 | --mode <mode> |
| 1819 | |
| 1820 | Specify what kind of code must be compiled, like the *mode* argument |
| 1821 | in :func:`parse`. |
| 1822 | |
Batuhan Taşkaya | 814d687 | 2019-12-16 21:23:27 +0300 | [diff] [blame] | 1823 | .. cmdoption:: --no-type-comments |
| 1824 | |
| 1825 | Don't parse type comments. |
| 1826 | |
Serhiy Storchaka | 832e864 | 2019-09-09 23:36:13 +0300 | [diff] [blame] | 1827 | .. cmdoption:: -a, --include-attributes |
| 1828 | |
| 1829 | Include attributes such as line numbers and column offsets. |
| 1830 | |
Batuhan Taşkaya | 814d687 | 2019-12-16 21:23:27 +0300 | [diff] [blame] | 1831 | .. cmdoption:: -i <indent> |
| 1832 | --indent <indent> |
| 1833 | |
| 1834 | Indentation of nodes in AST (number of spaces). |
| 1835 | |
Serhiy Storchaka | 832e864 | 2019-09-09 23:36:13 +0300 | [diff] [blame] | 1836 | If :file:`infile` is specified its contents are parsed to AST and dumped |
| 1837 | to stdout. Otherwise, the content is read from stdin. |
| 1838 | |
| 1839 | |
Senthil Kumaran | f3695bf | 2016-01-06 21:26:53 -0800 | [diff] [blame] | 1840 | .. seealso:: |
| 1841 | |
Edward K. Ream | e3c971c | 2020-08-11 09:07:49 -0500 | [diff] [blame] | 1842 | `Green Tree Snakes <https://greentreesnakes.readthedocs.io/>`_, an external |
| 1843 | documentation resource, has good details on working with Python ASTs. |
| 1844 | |
| 1845 | `ASTTokens <https://asttokens.readthedocs.io/en/latest/user-guide.html>`_ |
| 1846 | annotates Python ASTs with the positions of tokens and text in the source |
| 1847 | code that generated them. This is helpful for tools that make source code |
| 1848 | transformations. |
| 1849 | |
| 1850 | `leoAst.py <http://leoeditor.com/appendices.html#leoast-py>`_ unifies the |
| 1851 | token-based and parse-tree-based views of python programs by inserting |
| 1852 | two-way links between tokens and ast nodes. |
| 1853 | |
| 1854 | `LibCST <https://libcst.readthedocs.io/>`_ parses code as a Concrete Syntax |
| 1855 | Tree that looks like an ast tree and keeps all formatting details. It's |
| 1856 | useful for building automated refactoring (codemod) applications and |
| 1857 | linters. |
| 1858 | |
| 1859 | `Parso <https://parso.readthedocs.io>`_ is a Python parser that supports |
| 1860 | error recovery and round-trip parsing for different Python versions (in |
| 1861 | multiple Python versions). Parso is also able to list multiple syntax errors |
Batuhan Taskaya | e799aa8 | 2020-10-04 03:46:44 +0300 | [diff] [blame] | 1862 | in your python file. |