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 |
Ivan Levkivskyi | 9932a22 | 2019-01-22 11:18:22 +0000 | [diff] [blame] | 83 | :attr:`lineno`, :attr:`col_offset`, :attr:`lineno`, and :attr:`col_offset` |
| 84 | attributes. The :attr:`lineno` and :attr:`end_lineno` are the first and |
| 85 | last line numbers of source text span (1-indexed so the first line is line 1) |
| 86 | and the :attr:`col_offset` and :attr:`end_col_offset` are the corresponding |
| 87 | UTF-8 byte offsets of the first and last tokens that generated the node. |
| 88 | The UTF-8 offset is recorded because the parser uses UTF-8 internally. |
| 89 | |
| 90 | Note that the end positions are not required by the compiler and are |
| 91 | therefore optional. The end offset is *after* the last symbol, for example |
| 92 | one can get the source segment of a one-line expression node using |
| 93 | ``source_line[node.col_offset : node.end_col_offset]``. |
Georg Brandl | 0c77a82 | 2008-06-10 16:37:50 +0000 | [diff] [blame] | 94 | |
| 95 | The constructor of a class :class:`ast.T` parses its arguments as follows: |
| 96 | |
| 97 | * If there are positional arguments, there must be as many as there are items |
| 98 | in :attr:`T._fields`; they will be assigned as attributes of these names. |
| 99 | * If there are keyword arguments, they will set the attributes of the same |
| 100 | names to the given values. |
| 101 | |
| 102 | For example, to create and populate an :class:`ast.UnaryOp` node, you could |
| 103 | use :: |
| 104 | |
| 105 | node = ast.UnaryOp() |
| 106 | node.op = ast.USub() |
Serhiy Storchaka | 3f22811 | 2018-09-27 17:42:37 +0300 | [diff] [blame] | 107 | node.operand = ast.Constant() |
| 108 | node.operand.value = 5 |
Georg Brandl | 0c77a82 | 2008-06-10 16:37:50 +0000 | [diff] [blame] | 109 | node.operand.lineno = 0 |
| 110 | node.operand.col_offset = 0 |
| 111 | node.lineno = 0 |
| 112 | node.col_offset = 0 |
| 113 | |
| 114 | or the more compact :: |
| 115 | |
Serhiy Storchaka | 3f22811 | 2018-09-27 17:42:37 +0300 | [diff] [blame] | 116 | 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] | 117 | lineno=0, col_offset=0) |
| 118 | |
Serhiy Storchaka | 85a2eef | 2020-02-17 11:03:00 +0200 | [diff] [blame] | 119 | .. versionchanged:: 3.8 |
| 120 | |
| 121 | Class :class:`ast.Constant` is now used for all constants. |
| 122 | |
Serhiy Storchaka | 13d52c2 | 2020-03-10 18:52:34 +0200 | [diff] [blame] | 123 | .. versionchanged:: 3.9 |
| 124 | |
| 125 | Simple indices are represented by their value, extended slices are |
| 126 | represented as tuples. |
| 127 | |
Serhiy Storchaka | 3f22811 | 2018-09-27 17:42:37 +0300 | [diff] [blame] | 128 | .. deprecated:: 3.8 |
| 129 | |
Serhiy Storchaka | 85a2eef | 2020-02-17 11:03:00 +0200 | [diff] [blame] | 130 | Old classes :class:`ast.Num`, :class:`ast.Str`, :class:`ast.Bytes`, |
Serhiy Storchaka | 3f22811 | 2018-09-27 17:42:37 +0300 | [diff] [blame] | 131 | :class:`ast.NameConstant` and :class:`ast.Ellipsis` are still available, |
Serhiy Storchaka | 13d52c2 | 2020-03-10 18:52:34 +0200 | [diff] [blame] | 132 | but they will be removed in future Python releases. In the meantime, |
Serhiy Storchaka | 85a2eef | 2020-02-17 11:03:00 +0200 | [diff] [blame] | 133 | instantiating them will return an instance of a different class. |
Serhiy Storchaka | 3f22811 | 2018-09-27 17:42:37 +0300 | [diff] [blame] | 134 | |
Serhiy Storchaka | 13d52c2 | 2020-03-10 18:52:34 +0200 | [diff] [blame] | 135 | .. deprecated:: 3.9 |
| 136 | |
| 137 | Old classes :class:`ast.Index` and :class:`ast.ExtSlice` are still |
| 138 | available, but they will be removed in future Python releases. |
| 139 | In the meantime, instantiating them will return an instance of |
| 140 | a different class. |
| 141 | |
| 142 | |
Pablo Galindo | 114081f | 2020-03-02 03:14:06 +0000 | [diff] [blame] | 143 | Literals |
| 144 | ^^^^^^^^ |
Georg Brandl | 0c77a82 | 2008-06-10 16:37:50 +0000 | [diff] [blame] | 145 | |
Pablo Galindo | 114081f | 2020-03-02 03:14:06 +0000 | [diff] [blame] | 146 | .. class:: Constant(value) |
Georg Brandl | 0c77a82 | 2008-06-10 16:37:50 +0000 | [diff] [blame] | 147 | |
Pablo Galindo | 114081f | 2020-03-02 03:14:06 +0000 | [diff] [blame] | 148 | A constant value. The ``value`` attribute of the ``Constant`` literal contains the |
| 149 | Python object it represents. The values represented can be simple types |
| 150 | such as a number, string or ``None``, but also immutable container types |
| 151 | (tuples and frozensets) if all of their elements are constant. |
Georg Brandl | 0c77a82 | 2008-06-10 16:37:50 +0000 | [diff] [blame] | 152 | |
Pablo Galindo | 114081f | 2020-03-02 03:14:06 +0000 | [diff] [blame] | 153 | .. doctest:: |
Georg Brandl | 0c77a82 | 2008-06-10 16:37:50 +0000 | [diff] [blame] | 154 | |
Pablo Galindo | 02f64cb | 2020-03-07 18:22:58 +0000 | [diff] [blame] | 155 | >>> print(ast.dump(ast.parse('123', mode='eval'), indent=4)) |
| 156 | Expression( |
Serhiy Storchaka | b7e9525 | 2020-03-10 00:07:47 +0200 | [diff] [blame] | 157 | body=Constant(value=123)) |
Pablo Galindo | 114081f | 2020-03-02 03:14:06 +0000 | [diff] [blame] | 158 | |
| 159 | |
| 160 | .. class:: FormattedValue(value, conversion, format_spec) |
| 161 | |
| 162 | Node representing a single formatting field in an f-string. If the string |
| 163 | contains a single formatting field and nothing else the node can be |
| 164 | isolated otherwise it appears in :class:`JoinedStr`. |
| 165 | |
| 166 | * ``value`` is any expression node (such as a literal, a variable, or a |
| 167 | function call). |
| 168 | * ``conversion`` is an integer: |
| 169 | |
| 170 | * -1: no formatting |
| 171 | * 115: ``!s`` string formatting |
| 172 | * 114: ``!r`` repr formatting |
| 173 | * 97: ``!a`` ascii formatting |
| 174 | |
| 175 | * ``format_spec`` is a :class:`JoinedStr` node representing the formatting |
| 176 | of the value, or ``None`` if no format was specified. Both |
| 177 | ``conversion`` and ``format_spec`` can be set at the same time. |
| 178 | |
| 179 | |
| 180 | .. class:: JoinedStr(values) |
| 181 | |
| 182 | An f-string, comprising a series of :class:`FormattedValue` and :class:`Constant` |
| 183 | nodes. |
| 184 | |
| 185 | .. doctest:: |
| 186 | |
Pablo Galindo | 02f64cb | 2020-03-07 18:22:58 +0000 | [diff] [blame] | 187 | >>> print(ast.dump(ast.parse('f"sin({a}) is {sin(a):.3}"', mode='eval'), indent=4)) |
| 188 | Expression( |
| 189 | body=JoinedStr( |
| 190 | values=[ |
Serhiy Storchaka | b7e9525 | 2020-03-10 00:07:47 +0200 | [diff] [blame] | 191 | Constant(value='sin('), |
Pablo Galindo | 02f64cb | 2020-03-07 18:22:58 +0000 | [diff] [blame] | 192 | FormattedValue( |
| 193 | value=Name(id='a', ctx=Load()), |
Serhiy Storchaka | b7e9525 | 2020-03-10 00:07:47 +0200 | [diff] [blame] | 194 | conversion=-1), |
| 195 | Constant(value=') is '), |
Pablo Galindo | 02f64cb | 2020-03-07 18:22:58 +0000 | [diff] [blame] | 196 | FormattedValue( |
| 197 | value=Call( |
| 198 | func=Name(id='sin', ctx=Load()), |
| 199 | args=[ |
| 200 | Name(id='a', ctx=Load())], |
| 201 | keywords=[]), |
| 202 | conversion=-1, |
| 203 | format_spec=JoinedStr( |
| 204 | values=[ |
Serhiy Storchaka | b7e9525 | 2020-03-10 00:07:47 +0200 | [diff] [blame] | 205 | Constant(value='.3')]))])) |
Pablo Galindo | 114081f | 2020-03-02 03:14:06 +0000 | [diff] [blame] | 206 | |
| 207 | |
| 208 | .. class:: List(elts, ctx) |
| 209 | Tuple(elts, ctx) |
| 210 | |
| 211 | A list or tuple. ``elts`` holds a list of nodes representing the elements. |
| 212 | ``ctx`` is :class:`Store` if the container is an assignment target (i.e. |
| 213 | ``(x,y)=something``), and :class:`Load` otherwise. |
| 214 | |
| 215 | .. doctest:: |
| 216 | |
Pablo Galindo | 02f64cb | 2020-03-07 18:22:58 +0000 | [diff] [blame] | 217 | >>> print(ast.dump(ast.parse('[1, 2, 3]', mode='eval'), indent=4)) |
| 218 | Expression( |
| 219 | body=List( |
| 220 | elts=[ |
Serhiy Storchaka | b7e9525 | 2020-03-10 00:07:47 +0200 | [diff] [blame] | 221 | Constant(value=1), |
| 222 | Constant(value=2), |
| 223 | Constant(value=3)], |
Pablo Galindo | 02f64cb | 2020-03-07 18:22:58 +0000 | [diff] [blame] | 224 | ctx=Load())) |
| 225 | >>> print(ast.dump(ast.parse('(1, 2, 3)', mode='eval'), indent=4)) |
| 226 | Expression( |
| 227 | body=Tuple( |
| 228 | elts=[ |
Serhiy Storchaka | b7e9525 | 2020-03-10 00:07:47 +0200 | [diff] [blame] | 229 | Constant(value=1), |
| 230 | Constant(value=2), |
| 231 | Constant(value=3)], |
Pablo Galindo | 02f64cb | 2020-03-07 18:22:58 +0000 | [diff] [blame] | 232 | ctx=Load())) |
Pablo Galindo | 114081f | 2020-03-02 03:14:06 +0000 | [diff] [blame] | 233 | |
| 234 | |
| 235 | .. class:: Set(elts) |
| 236 | |
| 237 | A set. ``elts`` holds a list of nodes representing the set's elements. |
| 238 | |
| 239 | .. doctest:: |
| 240 | |
Pablo Galindo | 02f64cb | 2020-03-07 18:22:58 +0000 | [diff] [blame] | 241 | >>> print(ast.dump(ast.parse('{1, 2, 3}', mode='eval'), indent=4)) |
| 242 | Expression( |
| 243 | body=Set( |
| 244 | elts=[ |
Serhiy Storchaka | b7e9525 | 2020-03-10 00:07:47 +0200 | [diff] [blame] | 245 | Constant(value=1), |
| 246 | Constant(value=2), |
| 247 | Constant(value=3)])) |
Pablo Galindo | 114081f | 2020-03-02 03:14:06 +0000 | [diff] [blame] | 248 | |
| 249 | |
| 250 | .. class:: Dict(keys, values) |
| 251 | |
| 252 | A dictionary. ``keys`` and ``values`` hold lists of nodes representing the |
| 253 | keys and the values respectively, in matching order (what would be returned |
| 254 | when calling :code:`dictionary.keys()` and :code:`dictionary.values()`). |
| 255 | |
| 256 | When doing dictionary unpacking using dictionary literals the expression to be |
| 257 | expanded goes in the ``values`` list, with a ``None`` at the corresponding |
| 258 | position in ``keys``. |
| 259 | |
| 260 | .. doctest:: |
| 261 | |
Pablo Galindo | 02f64cb | 2020-03-07 18:22:58 +0000 | [diff] [blame] | 262 | >>> print(ast.dump(ast.parse('{"a":1, **d}', mode='eval'), indent=4)) |
| 263 | Expression( |
| 264 | body=Dict( |
| 265 | keys=[ |
Serhiy Storchaka | b7e9525 | 2020-03-10 00:07:47 +0200 | [diff] [blame] | 266 | Constant(value='a'), |
Pablo Galindo | 02f64cb | 2020-03-07 18:22:58 +0000 | [diff] [blame] | 267 | None], |
| 268 | values=[ |
Serhiy Storchaka | b7e9525 | 2020-03-10 00:07:47 +0200 | [diff] [blame] | 269 | Constant(value=1), |
Pablo Galindo | 02f64cb | 2020-03-07 18:22:58 +0000 | [diff] [blame] | 270 | Name(id='d', ctx=Load())])) |
Pablo Galindo | 114081f | 2020-03-02 03:14:06 +0000 | [diff] [blame] | 271 | |
| 272 | |
| 273 | Variables |
| 274 | ^^^^^^^^^ |
| 275 | |
| 276 | .. class:: Name(id, ctx) |
| 277 | |
| 278 | A variable name. ``id`` holds the name as a string, and ``ctx`` is one of |
| 279 | the following types. |
| 280 | |
| 281 | |
| 282 | .. class:: Load() |
| 283 | Store() |
| 284 | Del() |
| 285 | |
| 286 | Variable references can be used to load the value of a variable, to assign |
| 287 | a new value to it, or to delete it. Variable references are given a context |
| 288 | to distinguish these cases. |
| 289 | |
| 290 | .. doctest:: |
| 291 | |
| 292 | >>> print(ast.dump(ast.parse('a'), indent=4)) |
| 293 | Module( |
| 294 | body=[ |
| 295 | Expr( |
| 296 | value=Name(id='a', ctx=Load()))], |
| 297 | type_ignores=[]) |
| 298 | |
| 299 | >>> print(ast.dump(ast.parse('a = 1'), indent=4)) |
| 300 | Module( |
| 301 | body=[ |
| 302 | Assign( |
| 303 | targets=[ |
| 304 | Name(id='a', ctx=Store())], |
Serhiy Storchaka | b7e9525 | 2020-03-10 00:07:47 +0200 | [diff] [blame] | 305 | value=Constant(value=1))], |
Pablo Galindo | 114081f | 2020-03-02 03:14:06 +0000 | [diff] [blame] | 306 | type_ignores=[]) |
| 307 | |
| 308 | >>> print(ast.dump(ast.parse('del a'), indent=4)) |
| 309 | Module( |
| 310 | body=[ |
| 311 | Delete( |
| 312 | targets=[ |
| 313 | Name(id='a', ctx=Del())])], |
| 314 | type_ignores=[]) |
| 315 | |
| 316 | |
| 317 | .. class:: Starred(value, ctx) |
| 318 | |
| 319 | A ``*var`` variable reference. ``value`` holds the variable, typically a |
| 320 | :class:`Name` node. This type must be used when building a :class:`Call` |
| 321 | node with ``*args``. |
| 322 | |
| 323 | .. doctest:: |
| 324 | |
| 325 | >>> print(ast.dump(ast.parse('a, *b = it'), indent=4)) |
| 326 | Module( |
| 327 | body=[ |
| 328 | Assign( |
| 329 | targets=[ |
| 330 | Tuple( |
| 331 | elts=[ |
| 332 | Name(id='a', ctx=Store()), |
| 333 | Starred( |
| 334 | value=Name(id='b', ctx=Store()), |
| 335 | ctx=Store())], |
| 336 | ctx=Store())], |
Serhiy Storchaka | b7e9525 | 2020-03-10 00:07:47 +0200 | [diff] [blame] | 337 | value=Name(id='it', ctx=Load()))], |
Pablo Galindo | 114081f | 2020-03-02 03:14:06 +0000 | [diff] [blame] | 338 | type_ignores=[]) |
| 339 | |
| 340 | |
| 341 | Expressions |
| 342 | ^^^^^^^^^^^ |
| 343 | |
| 344 | .. class:: Expr(value) |
| 345 | |
| 346 | When an expression, such as a function call, appears as a statement by itself |
| 347 | with its return value not used or stored, it is wrapped in this container. |
| 348 | ``value`` holds one of the other nodes in this section, a :class:`Constant`, a |
| 349 | :class:`Name`, a :class:`Lambda`, a :class:`Yield` or :class:`YieldFrom` node. |
| 350 | |
| 351 | .. doctest:: |
| 352 | |
| 353 | >>> print(ast.dump(ast.parse('-a'), indent=4)) |
| 354 | Module( |
| 355 | body=[ |
| 356 | Expr( |
| 357 | value=UnaryOp( |
| 358 | op=USub(), |
| 359 | operand=Name(id='a', ctx=Load())))], |
| 360 | type_ignores=[]) |
| 361 | |
| 362 | |
| 363 | .. class:: UnaryOp(op, operand) |
| 364 | |
| 365 | A unary operation. ``op`` is the operator, and ``operand`` any expression |
| 366 | node. |
| 367 | |
| 368 | |
| 369 | .. class:: UAdd |
| 370 | USub |
| 371 | Not |
| 372 | Invert |
| 373 | |
| 374 | Unary operator tokens. :class:`Not` is the ``not`` keyword, :class:`Invert` |
| 375 | is the ``~`` operator. |
| 376 | |
| 377 | .. doctest:: |
| 378 | |
Pablo Galindo | 02f64cb | 2020-03-07 18:22:58 +0000 | [diff] [blame] | 379 | >>> print(ast.dump(ast.parse('not x', mode='eval'), indent=4)) |
| 380 | Expression( |
| 381 | body=UnaryOp( |
| 382 | op=Not(), |
| 383 | operand=Name(id='x', ctx=Load()))) |
Pablo Galindo | 114081f | 2020-03-02 03:14:06 +0000 | [diff] [blame] | 384 | |
| 385 | |
| 386 | .. class:: BinOp(left, op, right) |
| 387 | |
| 388 | A binary operation (like addition or division). ``op`` is the operator, and |
| 389 | ``left`` and ``right`` are any expression nodes. |
| 390 | |
| 391 | .. doctest:: |
| 392 | |
Pablo Galindo | 02f64cb | 2020-03-07 18:22:58 +0000 | [diff] [blame] | 393 | >>> print(ast.dump(ast.parse('x + y', mode='eval'), indent=4)) |
| 394 | Expression( |
| 395 | body=BinOp( |
| 396 | left=Name(id='x', ctx=Load()), |
| 397 | op=Add(), |
| 398 | right=Name(id='y', ctx=Load()))) |
Pablo Galindo | 114081f | 2020-03-02 03:14:06 +0000 | [diff] [blame] | 399 | |
| 400 | |
| 401 | .. class:: Add |
| 402 | Sub |
| 403 | Mult |
| 404 | Div |
| 405 | FloorDiv |
| 406 | Mod |
| 407 | Pow |
| 408 | LShift |
| 409 | RShift |
| 410 | BitOr |
| 411 | BitXor |
| 412 | BitAnd |
| 413 | MatMult |
| 414 | |
| 415 | Binary operator tokens. |
| 416 | |
| 417 | |
| 418 | .. class:: BoolOp(op, values) |
| 419 | |
| 420 | A boolean operation, 'or' or 'and'. ``op`` is :class:`Or` or :class:`And`. |
| 421 | ``values`` are the values involved. Consecutive operations with the same |
| 422 | operator, such as ``a or b or c``, are collapsed into one node with several |
| 423 | values. |
| 424 | |
| 425 | This doesn't include ``not``, which is a :class:`UnaryOp`. |
| 426 | |
| 427 | .. doctest:: |
| 428 | |
Pablo Galindo | 02f64cb | 2020-03-07 18:22:58 +0000 | [diff] [blame] | 429 | >>> print(ast.dump(ast.parse('x or y', mode='eval'), indent=4)) |
| 430 | Expression( |
| 431 | body=BoolOp( |
| 432 | op=Or(), |
| 433 | values=[ |
| 434 | Name(id='x', ctx=Load()), |
| 435 | Name(id='y', ctx=Load())])) |
Pablo Galindo | 114081f | 2020-03-02 03:14:06 +0000 | [diff] [blame] | 436 | |
| 437 | |
| 438 | .. class:: And |
| 439 | Or |
| 440 | |
| 441 | Boolean operator tokens. |
| 442 | |
| 443 | |
| 444 | .. class:: Compare(left, ops, comparators) |
| 445 | |
| 446 | A comparison of two or more values. ``left`` is the first value in the |
| 447 | comparison, ``ops`` the list of operators, and ``comparators`` the list |
| 448 | of values after the first element in the comparison. |
| 449 | |
| 450 | .. doctest:: |
| 451 | |
Pablo Galindo | 02f64cb | 2020-03-07 18:22:58 +0000 | [diff] [blame] | 452 | >>> print(ast.dump(ast.parse('1 <= a < 10', mode='eval'), indent=4)) |
| 453 | Expression( |
| 454 | body=Compare( |
Serhiy Storchaka | b7e9525 | 2020-03-10 00:07:47 +0200 | [diff] [blame] | 455 | left=Constant(value=1), |
Pablo Galindo | 02f64cb | 2020-03-07 18:22:58 +0000 | [diff] [blame] | 456 | ops=[ |
| 457 | LtE(), |
| 458 | Lt()], |
| 459 | comparators=[ |
| 460 | Name(id='a', ctx=Load()), |
Serhiy Storchaka | b7e9525 | 2020-03-10 00:07:47 +0200 | [diff] [blame] | 461 | Constant(value=10)])) |
Pablo Galindo | 114081f | 2020-03-02 03:14:06 +0000 | [diff] [blame] | 462 | |
| 463 | |
| 464 | .. class:: Eq |
| 465 | NotEq |
| 466 | Lt |
| 467 | LtE |
| 468 | Gt |
| 469 | GtE |
| 470 | Is |
| 471 | IsNot |
| 472 | In |
| 473 | NotIn |
| 474 | |
| 475 | Comparison operator tokens. |
| 476 | |
| 477 | |
| 478 | .. class:: Call(func, args, keywords, starargs, kwargs) |
| 479 | |
| 480 | A function call. ``func`` is the function, which will often be a |
| 481 | :class:`Name` or :class:`Attribute` object. Of the arguments: |
| 482 | |
| 483 | * ``args`` holds a list of the arguments passed by position. |
| 484 | * ``keywords`` holds a list of :class:`keyword` objects representing |
| 485 | arguments passed by keyword. |
| 486 | |
| 487 | When creating a ``Call`` node, ``args`` and ``keywords`` are required, but |
| 488 | they can be empty lists. ``starargs`` and ``kwargs`` are optional. |
| 489 | |
| 490 | .. doctest:: |
| 491 | |
Pablo Galindo | 02f64cb | 2020-03-07 18:22:58 +0000 | [diff] [blame] | 492 | >>> print(ast.dump(ast.parse('func(a, b=c, *d, **e)', mode='eval'), indent=4)) |
| 493 | Expression( |
| 494 | body=Call( |
| 495 | func=Name(id='func', ctx=Load()), |
| 496 | args=[ |
| 497 | Name(id='a', ctx=Load()), |
| 498 | Starred( |
| 499 | value=Name(id='d', ctx=Load()), |
| 500 | ctx=Load())], |
| 501 | keywords=[ |
| 502 | keyword( |
| 503 | arg='b', |
| 504 | value=Name(id='c', ctx=Load())), |
| 505 | keyword( |
Pablo Galindo | 02f64cb | 2020-03-07 18:22:58 +0000 | [diff] [blame] | 506 | value=Name(id='e', ctx=Load()))])) |
Pablo Galindo | 114081f | 2020-03-02 03:14:06 +0000 | [diff] [blame] | 507 | |
| 508 | |
| 509 | .. class:: keyword(arg, value) |
| 510 | |
| 511 | A keyword argument to a function call or class definition. ``arg`` is a raw |
| 512 | string of the parameter name, ``value`` is a node to pass in. |
| 513 | |
| 514 | |
| 515 | .. class:: IfExp(test, body, orelse) |
| 516 | |
| 517 | An expression such as ``a if b else c``. Each field holds a single node, so |
| 518 | in the following example, all three are :class:`Name` nodes. |
| 519 | |
| 520 | .. doctest:: |
| 521 | |
Pablo Galindo | 02f64cb | 2020-03-07 18:22:58 +0000 | [diff] [blame] | 522 | >>> print(ast.dump(ast.parse('a if b else c', mode='eval'), indent=4)) |
| 523 | Expression( |
| 524 | body=IfExp( |
| 525 | test=Name(id='b', ctx=Load()), |
| 526 | body=Name(id='a', ctx=Load()), |
| 527 | orelse=Name(id='c', ctx=Load()))) |
Pablo Galindo | 114081f | 2020-03-02 03:14:06 +0000 | [diff] [blame] | 528 | |
| 529 | |
| 530 | .. class:: Attribute(value, attr, ctx) |
| 531 | |
| 532 | Attribute access, e.g. ``d.keys``. ``value`` is a node, typically a |
| 533 | :class:`Name`. ``attr`` is a bare string giving the name of the attribute, |
| 534 | and ``ctx`` is :class:`Load`, :class:`Store` or :class:`Del` according to how |
| 535 | the attribute is acted on. |
| 536 | |
| 537 | .. doctest:: |
| 538 | |
Pablo Galindo | 02f64cb | 2020-03-07 18:22:58 +0000 | [diff] [blame] | 539 | >>> print(ast.dump(ast.parse('snake.colour', mode='eval'), indent=4)) |
| 540 | Expression( |
| 541 | body=Attribute( |
| 542 | value=Name(id='snake', ctx=Load()), |
| 543 | attr='colour', |
| 544 | ctx=Load())) |
Pablo Galindo | 114081f | 2020-03-02 03:14:06 +0000 | [diff] [blame] | 545 | |
| 546 | |
| 547 | .. class:: NamedExpr(target, value) |
| 548 | |
| 549 | A named expression. This AST node is produced by the assignment expressions |
| 550 | operator (also known as the walrus operator). As opposed to the :class:`Assign` |
| 551 | node in which the first argument can be multiple nodes, in this case both |
| 552 | ``target`` and ``value`` must be single nodes. |
| 553 | |
| 554 | .. doctest:: |
| 555 | |
Pablo Galindo | 02f64cb | 2020-03-07 18:22:58 +0000 | [diff] [blame] | 556 | >>> print(ast.dump(ast.parse('(x := 4)', mode='eval'), indent=4)) |
| 557 | Expression( |
| 558 | body=NamedExpr( |
| 559 | target=Name(id='x', ctx=Store()), |
Serhiy Storchaka | b7e9525 | 2020-03-10 00:07:47 +0200 | [diff] [blame] | 560 | value=Constant(value=4))) |
Pablo Galindo | 114081f | 2020-03-02 03:14:06 +0000 | [diff] [blame] | 561 | |
| 562 | |
| 563 | Subscripting |
| 564 | ~~~~~~~~~~~~ |
| 565 | |
| 566 | .. class:: Subscript(value, slice, ctx) |
| 567 | |
Serhiy Storchaka | 13d52c2 | 2020-03-10 18:52:34 +0200 | [diff] [blame] | 568 | A subscript, such as ``l[1]``. ``value`` is the subscripted object |
| 569 | (usually sequence or mapping). ``slice`` is an index, slice or key. |
| 570 | It can be a :class:`Tuple` and contain a :class:`Slice`. |
| 571 | ``ctx`` is :class:`Load`, :class:`Store` or :class:`Del` |
Pablo Galindo | 114081f | 2020-03-02 03:14:06 +0000 | [diff] [blame] | 572 | according to the action performed with the subscript. |
| 573 | |
Pablo Galindo | 114081f | 2020-03-02 03:14:06 +0000 | [diff] [blame] | 574 | .. doctest:: |
| 575 | |
Serhiy Storchaka | 13d52c2 | 2020-03-10 18:52:34 +0200 | [diff] [blame] | 576 | >>> 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] | 577 | Expression( |
| 578 | body=Subscript( |
| 579 | value=Name(id='l', ctx=Load()), |
Serhiy Storchaka | 13d52c2 | 2020-03-10 18:52:34 +0200 | [diff] [blame] | 580 | slice=Tuple( |
| 581 | elts=[ |
| 582 | Slice( |
| 583 | lower=Constant(value=1), |
| 584 | upper=Constant(value=2)), |
| 585 | Constant(value=3)], |
| 586 | ctx=Load()), |
Pablo Galindo | 02f64cb | 2020-03-07 18:22:58 +0000 | [diff] [blame] | 587 | ctx=Load())) |
Pablo Galindo | 114081f | 2020-03-02 03:14:06 +0000 | [diff] [blame] | 588 | |
| 589 | |
| 590 | .. class:: Slice(lower, upper, step) |
| 591 | |
Serhiy Storchaka | 13d52c2 | 2020-03-10 18:52:34 +0200 | [diff] [blame] | 592 | Regular slicing (on the form ``lower:upper`` or ``lower:upper:step``). |
| 593 | Can occur only inside the *slice* field of :class:`Subscript`, either |
| 594 | directly or as an element of :class:`Tuple`. |
Pablo Galindo | 114081f | 2020-03-02 03:14:06 +0000 | [diff] [blame] | 595 | |
| 596 | .. doctest:: |
| 597 | |
Pablo Galindo | 02f64cb | 2020-03-07 18:22:58 +0000 | [diff] [blame] | 598 | >>> print(ast.dump(ast.parse('l[1:2]', mode='eval'), indent=4)) |
| 599 | Expression( |
| 600 | body=Subscript( |
| 601 | value=Name(id='l', ctx=Load()), |
| 602 | slice=Slice( |
Serhiy Storchaka | b7e9525 | 2020-03-10 00:07:47 +0200 | [diff] [blame] | 603 | lower=Constant(value=1), |
| 604 | upper=Constant(value=2)), |
Pablo Galindo | 02f64cb | 2020-03-07 18:22:58 +0000 | [diff] [blame] | 605 | ctx=Load())) |
Pablo Galindo | 114081f | 2020-03-02 03:14:06 +0000 | [diff] [blame] | 606 | |
| 607 | |
Pablo Galindo | 114081f | 2020-03-02 03:14:06 +0000 | [diff] [blame] | 608 | Comprehensions |
| 609 | ~~~~~~~~~~~~~~ |
| 610 | |
| 611 | .. class:: ListComp(elt, generators) |
| 612 | SetComp(elt, generators) |
| 613 | GeneratorExp(elt, generators) |
| 614 | DictComp(key, value, generators) |
| 615 | |
| 616 | List and set comprehensions, generator expressions, and dictionary |
| 617 | comprehensions. ``elt`` (or ``key`` and ``value``) is a single node |
| 618 | representing the part that will be evaluated for each item. |
| 619 | |
| 620 | ``generators`` is a list of :class:`comprehension` nodes. |
| 621 | |
| 622 | .. doctest:: |
| 623 | |
Pablo Galindo | 02f64cb | 2020-03-07 18:22:58 +0000 | [diff] [blame] | 624 | >>> print(ast.dump(ast.parse('[x for x in numbers]', mode='eval'), indent=4)) |
| 625 | Expression( |
| 626 | body=ListComp( |
| 627 | elt=Name(id='x', ctx=Load()), |
| 628 | generators=[ |
| 629 | comprehension( |
| 630 | target=Name(id='x', ctx=Store()), |
| 631 | iter=Name(id='numbers', ctx=Load()), |
| 632 | ifs=[], |
| 633 | is_async=0)])) |
| 634 | >>> print(ast.dump(ast.parse('{x: x**2 for x in numbers}', mode='eval'), indent=4)) |
| 635 | Expression( |
| 636 | body=DictComp( |
| 637 | key=Name(id='x', ctx=Load()), |
| 638 | value=BinOp( |
| 639 | left=Name(id='x', ctx=Load()), |
| 640 | op=Pow(), |
Serhiy Storchaka | b7e9525 | 2020-03-10 00:07:47 +0200 | [diff] [blame] | 641 | right=Constant(value=2)), |
Pablo Galindo | 02f64cb | 2020-03-07 18:22:58 +0000 | [diff] [blame] | 642 | generators=[ |
| 643 | comprehension( |
| 644 | target=Name(id='x', ctx=Store()), |
| 645 | iter=Name(id='numbers', ctx=Load()), |
| 646 | ifs=[], |
| 647 | is_async=0)])) |
| 648 | >>> print(ast.dump(ast.parse('{x for x in numbers}', mode='eval'), indent=4)) |
| 649 | Expression( |
| 650 | body=SetComp( |
| 651 | elt=Name(id='x', ctx=Load()), |
| 652 | generators=[ |
| 653 | comprehension( |
| 654 | target=Name(id='x', ctx=Store()), |
| 655 | iter=Name(id='numbers', ctx=Load()), |
| 656 | ifs=[], |
| 657 | is_async=0)])) |
Pablo Galindo | 114081f | 2020-03-02 03:14:06 +0000 | [diff] [blame] | 658 | |
| 659 | |
| 660 | .. class:: comprehension(target, iter, ifs, is_async) |
| 661 | |
| 662 | One ``for`` clause in a comprehension. ``target`` is the reference to use for |
| 663 | each element - typically a :class:`Name` or :class:`Tuple` node. ``iter`` |
| 664 | is the object to iterate over. ``ifs`` is a list of test expressions: each |
| 665 | ``for`` clause can have multiple ``ifs``. |
| 666 | |
| 667 | ``is_async`` indicates a comprehension is asynchronous (using an |
| 668 | ``async for`` instead of ``for``). The value is an integer (0 or 1). |
| 669 | |
| 670 | .. doctest:: |
| 671 | |
Pablo Galindo | 02f64cb | 2020-03-07 18:22:58 +0000 | [diff] [blame] | 672 | >>> 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] | 673 | ... indent=4)) # Multiple comprehensions in one. |
| 674 | Expression( |
| 675 | body=ListComp( |
| 676 | elt=Call( |
| 677 | func=Name(id='ord', ctx=Load()), |
| 678 | args=[ |
| 679 | Name(id='c', ctx=Load())], |
| 680 | keywords=[]), |
| 681 | generators=[ |
| 682 | comprehension( |
| 683 | target=Name(id='line', ctx=Store()), |
| 684 | iter=Name(id='file', ctx=Load()), |
| 685 | ifs=[], |
| 686 | is_async=0), |
| 687 | comprehension( |
| 688 | target=Name(id='c', ctx=Store()), |
| 689 | iter=Name(id='line', ctx=Load()), |
| 690 | ifs=[], |
| 691 | is_async=0)])) |
| 692 | |
Pablo Galindo | 02f64cb | 2020-03-07 18:22:58 +0000 | [diff] [blame] | 693 | >>> 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] | 694 | ... indent=4)) # generator comprehension |
| 695 | Expression( |
| 696 | body=GeneratorExp( |
| 697 | elt=BinOp( |
| 698 | left=Name(id='n', ctx=Load()), |
| 699 | op=Pow(), |
Serhiy Storchaka | b7e9525 | 2020-03-10 00:07:47 +0200 | [diff] [blame] | 700 | right=Constant(value=2)), |
Pablo Galindo | 114081f | 2020-03-02 03:14:06 +0000 | [diff] [blame] | 701 | generators=[ |
| 702 | comprehension( |
| 703 | target=Name(id='n', ctx=Store()), |
| 704 | iter=Name(id='it', ctx=Load()), |
| 705 | ifs=[ |
| 706 | Compare( |
| 707 | left=Name(id='n', ctx=Load()), |
| 708 | ops=[ |
| 709 | Gt()], |
| 710 | comparators=[ |
Serhiy Storchaka | b7e9525 | 2020-03-10 00:07:47 +0200 | [diff] [blame] | 711 | Constant(value=5)]), |
Pablo Galindo | 114081f | 2020-03-02 03:14:06 +0000 | [diff] [blame] | 712 | Compare( |
| 713 | left=Name(id='n', ctx=Load()), |
| 714 | ops=[ |
| 715 | Lt()], |
| 716 | comparators=[ |
Serhiy Storchaka | b7e9525 | 2020-03-10 00:07:47 +0200 | [diff] [blame] | 717 | Constant(value=10)])], |
Pablo Galindo | 114081f | 2020-03-02 03:14:06 +0000 | [diff] [blame] | 718 | is_async=0)])) |
| 719 | |
Pablo Galindo | 02f64cb | 2020-03-07 18:22:58 +0000 | [diff] [blame] | 720 | >>> 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] | 721 | ... indent=4)) # Async comprehension |
Pablo Galindo | 02f64cb | 2020-03-07 18:22:58 +0000 | [diff] [blame] | 722 | Expression( |
| 723 | body=ListComp( |
| 724 | elt=Name(id='i', ctx=Load()), |
| 725 | generators=[ |
| 726 | comprehension( |
| 727 | target=Name(id='i', ctx=Store()), |
| 728 | iter=Name(id='soc', ctx=Load()), |
| 729 | ifs=[], |
| 730 | is_async=1)])) |
Pablo Galindo | 114081f | 2020-03-02 03:14:06 +0000 | [diff] [blame] | 731 | |
| 732 | Statements |
| 733 | ^^^^^^^^^^ |
| 734 | |
| 735 | .. class:: Assign(targets, value, type_comment) |
| 736 | |
| 737 | An assignment. ``targets`` is a list of nodes, and ``value`` is a single node. |
| 738 | |
| 739 | Multiple nodes in ``targets`` represents assigning the same value to each. |
| 740 | Unpacking is represented by putting a :class:`Tuple` or :class:`List` |
| 741 | within ``targets``. |
| 742 | |
| 743 | .. attribute:: type_comment |
| 744 | |
| 745 | ``type_comment`` is an optional string with the type annotation as a comment. |
| 746 | |
| 747 | .. doctest:: |
| 748 | |
Pablo Galindo | 02f64cb | 2020-03-07 18:22:58 +0000 | [diff] [blame] | 749 | >>> print(ast.dump(ast.parse('a = b = 1'), indent=4)) # Multiple assignment |
Pablo Galindo | 114081f | 2020-03-02 03:14:06 +0000 | [diff] [blame] | 750 | Module( |
| 751 | body=[ |
| 752 | Assign( |
| 753 | targets=[ |
| 754 | Name(id='a', ctx=Store()), |
| 755 | Name(id='b', ctx=Store())], |
Serhiy Storchaka | b7e9525 | 2020-03-10 00:07:47 +0200 | [diff] [blame] | 756 | value=Constant(value=1))], |
Pablo Galindo | 114081f | 2020-03-02 03:14:06 +0000 | [diff] [blame] | 757 | type_ignores=[]) |
| 758 | |
Pablo Galindo | 02f64cb | 2020-03-07 18:22:58 +0000 | [diff] [blame] | 759 | >>> print(ast.dump(ast.parse('a,b = c'), indent=4)) # Unpacking |
Pablo Galindo | 114081f | 2020-03-02 03:14:06 +0000 | [diff] [blame] | 760 | Module( |
| 761 | body=[ |
| 762 | Assign( |
| 763 | targets=[ |
| 764 | Tuple( |
| 765 | elts=[ |
| 766 | Name(id='a', ctx=Store()), |
| 767 | Name(id='b', ctx=Store())], |
| 768 | ctx=Store())], |
Serhiy Storchaka | b7e9525 | 2020-03-10 00:07:47 +0200 | [diff] [blame] | 769 | value=Name(id='c', ctx=Load()))], |
Pablo Galindo | 114081f | 2020-03-02 03:14:06 +0000 | [diff] [blame] | 770 | type_ignores=[]) |
| 771 | |
| 772 | |
| 773 | .. class:: AnnAssign(target, annotation, value, simple) |
| 774 | |
| 775 | An assignment with a type annotation. ``target`` is a single node and can |
| 776 | be a :class:`Name`, a :class:`Attribute` or a :class:`Subscript`. |
| 777 | ``annotation`` is the annotation, such as a :class:`Constant` or :class:`Name` |
| 778 | node. ``value`` is a single optional node. ``simple`` is a boolean integer |
| 779 | set to True for a :class:`Name` node in ``target`` that do not appear in |
| 780 | between parenthesis and are hence pure names and not expressions. |
| 781 | |
| 782 | .. doctest:: |
| 783 | |
Pablo Galindo | 02f64cb | 2020-03-07 18:22:58 +0000 | [diff] [blame] | 784 | >>> print(ast.dump(ast.parse('c: int'), indent=4)) |
Pablo Galindo | 114081f | 2020-03-02 03:14:06 +0000 | [diff] [blame] | 785 | Module( |
| 786 | body=[ |
| 787 | AnnAssign( |
| 788 | target=Name(id='c', ctx=Store()), |
| 789 | annotation=Name(id='int', ctx=Load()), |
Pablo Galindo | 114081f | 2020-03-02 03:14:06 +0000 | [diff] [blame] | 790 | simple=1)], |
| 791 | type_ignores=[]) |
| 792 | |
Pablo Galindo | 02f64cb | 2020-03-07 18:22:58 +0000 | [diff] [blame] | 793 | >>> 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] | 794 | Module( |
| 795 | body=[ |
| 796 | AnnAssign( |
| 797 | target=Name(id='a', ctx=Store()), |
| 798 | annotation=Name(id='int', ctx=Load()), |
Serhiy Storchaka | b7e9525 | 2020-03-10 00:07:47 +0200 | [diff] [blame] | 799 | value=Constant(value=1), |
Pablo Galindo | 114081f | 2020-03-02 03:14:06 +0000 | [diff] [blame] | 800 | simple=0)], |
| 801 | type_ignores=[]) |
| 802 | |
Pablo Galindo | 02f64cb | 2020-03-07 18:22:58 +0000 | [diff] [blame] | 803 | >>> print(ast.dump(ast.parse('a.b: int'), indent=4)) # Attribute annotation |
Pablo Galindo | 114081f | 2020-03-02 03:14:06 +0000 | [diff] [blame] | 804 | Module( |
| 805 | body=[ |
| 806 | AnnAssign( |
| 807 | target=Attribute( |
| 808 | value=Name(id='a', ctx=Load()), |
| 809 | attr='b', |
| 810 | ctx=Store()), |
| 811 | annotation=Name(id='int', ctx=Load()), |
Pablo Galindo | 114081f | 2020-03-02 03:14:06 +0000 | [diff] [blame] | 812 | simple=0)], |
| 813 | type_ignores=[]) |
| 814 | |
Pablo Galindo | 02f64cb | 2020-03-07 18:22:58 +0000 | [diff] [blame] | 815 | >>> print(ast.dump(ast.parse('a[1]: int'), indent=4)) # Subscript annotation |
Pablo Galindo | 114081f | 2020-03-02 03:14:06 +0000 | [diff] [blame] | 816 | Module( |
| 817 | body=[ |
| 818 | AnnAssign( |
| 819 | target=Subscript( |
| 820 | value=Name(id='a', ctx=Load()), |
Serhiy Storchaka | 13d52c2 | 2020-03-10 18:52:34 +0200 | [diff] [blame] | 821 | slice=Constant(value=1), |
Pablo Galindo | 114081f | 2020-03-02 03:14:06 +0000 | [diff] [blame] | 822 | ctx=Store()), |
| 823 | annotation=Name(id='int', ctx=Load()), |
Pablo Galindo | 114081f | 2020-03-02 03:14:06 +0000 | [diff] [blame] | 824 | simple=0)], |
| 825 | type_ignores=[]) |
| 826 | |
| 827 | |
| 828 | .. class:: AugAssign(target, op, value) |
| 829 | |
| 830 | Augmented assignment, such as ``a += 1``. In the following example, |
| 831 | ``target`` is a :class:`Name` node for ``x`` (with the :class:`Store` |
| 832 | context), ``op`` is :class:`Add`, and ``value`` is a :class:`Constant` with |
| 833 | value for 1. |
| 834 | |
| 835 | The ``target`` attribute connot be of class :class:`Tuple` or :class:`List`, |
| 836 | unlike the targets of :class:`Assign`. |
| 837 | |
| 838 | .. doctest:: |
| 839 | |
Pablo Galindo | 02f64cb | 2020-03-07 18:22:58 +0000 | [diff] [blame] | 840 | >>> print(ast.dump(ast.parse('x += 2'), indent=4)) |
Pablo Galindo | 114081f | 2020-03-02 03:14:06 +0000 | [diff] [blame] | 841 | Module( |
| 842 | body=[ |
| 843 | AugAssign( |
| 844 | target=Name(id='x', ctx=Store()), |
| 845 | op=Add(), |
Serhiy Storchaka | b7e9525 | 2020-03-10 00:07:47 +0200 | [diff] [blame] | 846 | value=Constant(value=2))], |
Pablo Galindo | 114081f | 2020-03-02 03:14:06 +0000 | [diff] [blame] | 847 | type_ignores=[]) |
| 848 | |
| 849 | |
| 850 | .. class:: Raise(exc, cause) |
| 851 | |
| 852 | A ``raise`` statement. ``exc`` is the exception object to be raised, normally a |
| 853 | :class:`Call` or :class:`Name`, or ``None`` for a standalone ``raise``. |
| 854 | ``cause`` is the optional part for ``y`` in ``raise x from y``. |
| 855 | |
| 856 | .. doctest:: |
| 857 | |
Pablo Galindo | 02f64cb | 2020-03-07 18:22:58 +0000 | [diff] [blame] | 858 | >>> print(ast.dump(ast.parse('raise x from y'), indent=4)) |
Pablo Galindo | 114081f | 2020-03-02 03:14:06 +0000 | [diff] [blame] | 859 | Module( |
| 860 | body=[ |
| 861 | Raise( |
| 862 | exc=Name(id='x', ctx=Load()), |
| 863 | cause=Name(id='y', ctx=Load()))], |
| 864 | type_ignores=[]) |
| 865 | |
| 866 | |
| 867 | .. class:: Assert(test, msg) |
| 868 | |
| 869 | An assertion. ``test`` holds the condition, such as a :class:`Compare` node. |
| 870 | ``msg`` holds the failure message. |
| 871 | |
| 872 | .. doctest:: |
| 873 | |
Pablo Galindo | 02f64cb | 2020-03-07 18:22:58 +0000 | [diff] [blame] | 874 | >>> print(ast.dump(ast.parse('assert x,y'), indent=4)) |
Pablo Galindo | 114081f | 2020-03-02 03:14:06 +0000 | [diff] [blame] | 875 | Module( |
| 876 | body=[ |
| 877 | Assert( |
| 878 | test=Name(id='x', ctx=Load()), |
| 879 | msg=Name(id='y', ctx=Load()))], |
| 880 | type_ignores=[]) |
| 881 | |
| 882 | |
| 883 | .. class:: Delete(targets) |
| 884 | |
| 885 | Represents a ``del`` statement. ``targets`` is a list of nodes, such as |
| 886 | :class:`Name`, :class:`Attribute` or :class:`Subscript` nodes. |
| 887 | |
| 888 | .. doctest:: |
| 889 | |
Pablo Galindo | 02f64cb | 2020-03-07 18:22:58 +0000 | [diff] [blame] | 890 | >>> print(ast.dump(ast.parse('del x,y,z'), indent=4)) |
Pablo Galindo | 114081f | 2020-03-02 03:14:06 +0000 | [diff] [blame] | 891 | Module( |
| 892 | body=[ |
| 893 | Delete( |
| 894 | targets=[ |
| 895 | Name(id='x', ctx=Del()), |
| 896 | Name(id='y', ctx=Del()), |
| 897 | Name(id='z', ctx=Del())])], |
| 898 | type_ignores=[]) |
| 899 | |
| 900 | |
| 901 | .. class:: Pass() |
| 902 | |
| 903 | A ``pass`` statement. |
| 904 | |
| 905 | .. doctest:: |
| 906 | |
Pablo Galindo | 02f64cb | 2020-03-07 18:22:58 +0000 | [diff] [blame] | 907 | >>> print(ast.dump(ast.parse('pass'), indent=4)) |
Pablo Galindo | 114081f | 2020-03-02 03:14:06 +0000 | [diff] [blame] | 908 | Module( |
| 909 | body=[ |
| 910 | Pass()], |
| 911 | type_ignores=[]) |
| 912 | |
| 913 | |
| 914 | Other statements which are only applicable inside functions or loops are |
| 915 | described in other sections. |
| 916 | |
| 917 | Imports |
| 918 | ~~~~~~~ |
| 919 | |
| 920 | .. class:: Import(names) |
| 921 | |
| 922 | An import statement. ``names`` is a list of :class:`alias` nodes. |
| 923 | |
| 924 | .. doctest:: |
| 925 | |
Pablo Galindo | 02f64cb | 2020-03-07 18:22:58 +0000 | [diff] [blame] | 926 | >>> print(ast.dump(ast.parse('import x,y,z'), indent=4)) |
Pablo Galindo | 114081f | 2020-03-02 03:14:06 +0000 | [diff] [blame] | 927 | Module( |
| 928 | body=[ |
| 929 | Import( |
| 930 | names=[ |
Serhiy Storchaka | b7e9525 | 2020-03-10 00:07:47 +0200 | [diff] [blame] | 931 | alias(name='x'), |
| 932 | alias(name='y'), |
| 933 | alias(name='z')])], |
Pablo Galindo | 114081f | 2020-03-02 03:14:06 +0000 | [diff] [blame] | 934 | type_ignores=[]) |
| 935 | |
| 936 | |
| 937 | .. class:: ImportFrom(module, names, level) |
| 938 | |
| 939 | Represents ``from x import y``. ``module`` is a raw string of the 'from' name, |
| 940 | without any leading dots, or ``None`` for statements such as ``from . import foo``. |
| 941 | ``level`` is an integer holding the level of the relative import (0 means |
| 942 | absolute import). |
| 943 | |
| 944 | .. doctest:: |
| 945 | |
Pablo Galindo | 02f64cb | 2020-03-07 18:22:58 +0000 | [diff] [blame] | 946 | >>> 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] | 947 | Module( |
| 948 | body=[ |
| 949 | ImportFrom( |
| 950 | module='y', |
| 951 | names=[ |
Serhiy Storchaka | b7e9525 | 2020-03-10 00:07:47 +0200 | [diff] [blame] | 952 | alias(name='x'), |
| 953 | alias(name='y'), |
| 954 | alias(name='z')], |
Pablo Galindo | 114081f | 2020-03-02 03:14:06 +0000 | [diff] [blame] | 955 | level=0)], |
| 956 | type_ignores=[]) |
| 957 | |
| 958 | |
| 959 | .. class:: alias(name, asname) |
| 960 | |
| 961 | Both parameters are raw strings of the names. ``asname`` can be ``None`` if |
| 962 | the regular name is to be used. |
| 963 | |
| 964 | .. doctest:: |
| 965 | |
Pablo Galindo | 02f64cb | 2020-03-07 18:22:58 +0000 | [diff] [blame] | 966 | >>> 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] | 967 | Module( |
| 968 | body=[ |
| 969 | ImportFrom( |
| 970 | module='foo.bar', |
| 971 | names=[ |
| 972 | alias(name='a', asname='b'), |
Serhiy Storchaka | b7e9525 | 2020-03-10 00:07:47 +0200 | [diff] [blame] | 973 | alias(name='c')], |
Pablo Galindo | 114081f | 2020-03-02 03:14:06 +0000 | [diff] [blame] | 974 | level=2)], |
| 975 | type_ignores=[]) |
| 976 | |
| 977 | Control flow |
| 978 | ^^^^^^^^^^^^ |
| 979 | |
| 980 | .. note:: |
| 981 | Optional clauses such as ``else`` are stored as an empty list if they're |
| 982 | not present. |
| 983 | |
| 984 | .. class:: If(test, body, orelse) |
| 985 | |
| 986 | An ``if`` statement. ``test`` holds a single node, such as a :class:`Compare` |
| 987 | node. ``body`` and ``orelse`` each hold a list of nodes. |
| 988 | |
| 989 | ``elif`` clauses don't have a special representation in the AST, but rather |
| 990 | appear as extra :class:`If` nodes within the ``orelse`` section of the |
| 991 | previous one. |
| 992 | |
| 993 | .. doctest:: |
| 994 | |
| 995 | >>> print(ast.dump(ast.parse(""" |
| 996 | ... if x: |
| 997 | ... ... |
| 998 | ... elif y: |
| 999 | ... ... |
| 1000 | ... else: |
| 1001 | ... ... |
| 1002 | ... """), indent=4)) |
| 1003 | Module( |
| 1004 | body=[ |
| 1005 | If( |
| 1006 | test=Name(id='x', ctx=Load()), |
| 1007 | body=[ |
| 1008 | Expr( |
Serhiy Storchaka | b7e9525 | 2020-03-10 00:07:47 +0200 | [diff] [blame] | 1009 | value=Constant(value=Ellipsis))], |
Pablo Galindo | 114081f | 2020-03-02 03:14:06 +0000 | [diff] [blame] | 1010 | orelse=[ |
| 1011 | If( |
| 1012 | test=Name(id='y', ctx=Load()), |
| 1013 | body=[ |
| 1014 | Expr( |
Serhiy Storchaka | b7e9525 | 2020-03-10 00:07:47 +0200 | [diff] [blame] | 1015 | value=Constant(value=Ellipsis))], |
Pablo Galindo | 114081f | 2020-03-02 03:14:06 +0000 | [diff] [blame] | 1016 | orelse=[ |
| 1017 | Expr( |
Serhiy Storchaka | b7e9525 | 2020-03-10 00:07:47 +0200 | [diff] [blame] | 1018 | value=Constant(value=Ellipsis))])])], |
Pablo Galindo | 114081f | 2020-03-02 03:14:06 +0000 | [diff] [blame] | 1019 | type_ignores=[]) |
| 1020 | |
| 1021 | |
| 1022 | .. class:: For(target, iter, body, orelse, type_comment) |
| 1023 | |
| 1024 | A ``for`` loop. ``target`` holds the variable(s) the loop assigns to, as a |
| 1025 | single :class:`Name`, :class:`Tuple` or :class:`List` node. ``iter`` holds |
| 1026 | the item to be looped over, again as a single node. ``body`` and ``orelse`` |
| 1027 | contain lists of nodes to execute. Those in ``orelse`` are executed if the |
| 1028 | loop finishes normally, rather than via a ``break`` statement. |
| 1029 | |
| 1030 | .. attribute:: type_comment |
| 1031 | |
| 1032 | ``type_comment`` is an optional string with the type annotation as a comment. |
| 1033 | |
| 1034 | .. doctest:: |
| 1035 | |
| 1036 | >>> print(ast.dump(ast.parse(""" |
| 1037 | ... for x in y: |
| 1038 | ... ... |
| 1039 | ... else: |
| 1040 | ... ... |
| 1041 | ... """), indent=4)) |
| 1042 | Module( |
| 1043 | body=[ |
| 1044 | For( |
| 1045 | target=Name(id='x', ctx=Store()), |
| 1046 | iter=Name(id='y', ctx=Load()), |
| 1047 | body=[ |
| 1048 | Expr( |
Serhiy Storchaka | b7e9525 | 2020-03-10 00:07:47 +0200 | [diff] [blame] | 1049 | value=Constant(value=Ellipsis))], |
Pablo Galindo | 114081f | 2020-03-02 03:14:06 +0000 | [diff] [blame] | 1050 | orelse=[ |
| 1051 | Expr( |
Serhiy Storchaka | b7e9525 | 2020-03-10 00:07:47 +0200 | [diff] [blame] | 1052 | value=Constant(value=Ellipsis))])], |
Pablo Galindo | 114081f | 2020-03-02 03:14:06 +0000 | [diff] [blame] | 1053 | type_ignores=[]) |
| 1054 | |
| 1055 | |
| 1056 | .. class:: While(test, body, orelse) |
| 1057 | |
| 1058 | A ``while`` loop. ``test`` holds the condition, such as a :class:`Compare` |
| 1059 | node. |
| 1060 | |
| 1061 | .. doctest:: |
| 1062 | |
| 1063 | >> print(ast.dump(ast.parse(""" |
| 1064 | ... while x: |
| 1065 | ... ... |
| 1066 | ... else: |
| 1067 | ... ... |
| 1068 | ... """), indent=4)) |
| 1069 | Module( |
| 1070 | body=[ |
| 1071 | While( |
| 1072 | test=Name(id='x', ctx=Load()), |
| 1073 | body=[ |
| 1074 | Expr( |
Serhiy Storchaka | b7e9525 | 2020-03-10 00:07:47 +0200 | [diff] [blame] | 1075 | value=Constant(value=Ellipsis))], |
Pablo Galindo | 114081f | 2020-03-02 03:14:06 +0000 | [diff] [blame] | 1076 | orelse=[ |
| 1077 | Expr( |
Serhiy Storchaka | b7e9525 | 2020-03-10 00:07:47 +0200 | [diff] [blame] | 1078 | value=Constant(value=Ellipsis))])], |
Pablo Galindo | 114081f | 2020-03-02 03:14:06 +0000 | [diff] [blame] | 1079 | type_ignores=[]) |
| 1080 | |
| 1081 | |
| 1082 | .. class:: Break |
| 1083 | Continue |
| 1084 | |
| 1085 | The ``break`` and ``continue`` statements. |
| 1086 | |
| 1087 | .. doctest:: |
| 1088 | |
| 1089 | >>> print(ast.dump(ast.parse("""\ |
| 1090 | ... for a in b: |
| 1091 | ... if a > 5: |
| 1092 | ... break |
| 1093 | ... else: |
| 1094 | ... continue |
| 1095 | ... |
| 1096 | ... """), indent=4)) |
| 1097 | Module( |
| 1098 | body=[ |
| 1099 | For( |
| 1100 | target=Name(id='a', ctx=Store()), |
| 1101 | iter=Name(id='b', ctx=Load()), |
| 1102 | body=[ |
| 1103 | If( |
| 1104 | test=Compare( |
| 1105 | left=Name(id='a', ctx=Load()), |
| 1106 | ops=[ |
| 1107 | Gt()], |
| 1108 | comparators=[ |
Serhiy Storchaka | b7e9525 | 2020-03-10 00:07:47 +0200 | [diff] [blame] | 1109 | Constant(value=5)]), |
Pablo Galindo | 114081f | 2020-03-02 03:14:06 +0000 | [diff] [blame] | 1110 | body=[ |
| 1111 | Break()], |
| 1112 | orelse=[ |
| 1113 | Continue()])], |
Serhiy Storchaka | b7e9525 | 2020-03-10 00:07:47 +0200 | [diff] [blame] | 1114 | orelse=[])], |
Pablo Galindo | 114081f | 2020-03-02 03:14:06 +0000 | [diff] [blame] | 1115 | type_ignores=[]) |
| 1116 | |
| 1117 | |
| 1118 | .. class:: Try(body, handlers, orelse, finalbody) |
| 1119 | |
| 1120 | ``try`` blocks. All attributes are list of nodes to execute, except for |
| 1121 | ``handlers``, which is a list of :class:`ExceptHandler` nodes. |
| 1122 | |
| 1123 | .. doctest:: |
| 1124 | |
| 1125 | >>> print(ast.dump(ast.parse(""" |
| 1126 | ... try: |
| 1127 | ... ... |
| 1128 | ... except Exception: |
| 1129 | ... ... |
| 1130 | ... except OtherException as e: |
| 1131 | ... ... |
| 1132 | ... else: |
| 1133 | ... ... |
| 1134 | ... finally: |
| 1135 | ... ... |
| 1136 | ... """), indent=4)) |
| 1137 | Module( |
| 1138 | body=[ |
| 1139 | Try( |
| 1140 | body=[ |
| 1141 | Expr( |
Serhiy Storchaka | b7e9525 | 2020-03-10 00:07:47 +0200 | [diff] [blame] | 1142 | value=Constant(value=Ellipsis))], |
Pablo Galindo | 114081f | 2020-03-02 03:14:06 +0000 | [diff] [blame] | 1143 | handlers=[ |
| 1144 | ExceptHandler( |
| 1145 | type=Name(id='Exception', ctx=Load()), |
Pablo Galindo | 114081f | 2020-03-02 03:14:06 +0000 | [diff] [blame] | 1146 | body=[ |
| 1147 | Expr( |
Serhiy Storchaka | b7e9525 | 2020-03-10 00:07:47 +0200 | [diff] [blame] | 1148 | value=Constant(value=Ellipsis))]), |
Pablo Galindo | 114081f | 2020-03-02 03:14:06 +0000 | [diff] [blame] | 1149 | ExceptHandler( |
| 1150 | type=Name(id='OtherException', ctx=Load()), |
| 1151 | name='e', |
| 1152 | body=[ |
| 1153 | Expr( |
Serhiy Storchaka | b7e9525 | 2020-03-10 00:07:47 +0200 | [diff] [blame] | 1154 | value=Constant(value=Ellipsis))])], |
Pablo Galindo | 114081f | 2020-03-02 03:14:06 +0000 | [diff] [blame] | 1155 | orelse=[ |
| 1156 | Expr( |
Serhiy Storchaka | b7e9525 | 2020-03-10 00:07:47 +0200 | [diff] [blame] | 1157 | value=Constant(value=Ellipsis))], |
Pablo Galindo | 114081f | 2020-03-02 03:14:06 +0000 | [diff] [blame] | 1158 | finalbody=[ |
| 1159 | Expr( |
Serhiy Storchaka | b7e9525 | 2020-03-10 00:07:47 +0200 | [diff] [blame] | 1160 | value=Constant(value=Ellipsis))])], |
Pablo Galindo | 114081f | 2020-03-02 03:14:06 +0000 | [diff] [blame] | 1161 | type_ignores=[]) |
| 1162 | |
| 1163 | |
| 1164 | .. class:: ExceptHandler(type, name, body) |
| 1165 | |
| 1166 | A single ``except`` clause. ``type`` is the exception type it will match, |
| 1167 | typically a :class:`Name` node (or ``None`` for a catch-all ``except:`` clause). |
| 1168 | ``name`` is a raw string for the name to hold the exception, or ``None`` if |
| 1169 | the clause doesn't have ``as foo``. ``body`` is a list of nodes. |
| 1170 | |
| 1171 | .. doctest:: |
| 1172 | |
| 1173 | >>> print(ast.dump(ast.parse("""\ |
| 1174 | ... try: |
| 1175 | ... a + 1 |
| 1176 | ... except TypeError: |
| 1177 | ... pass |
| 1178 | ... """), indent=4)) |
| 1179 | Module( |
| 1180 | body=[ |
| 1181 | Try( |
| 1182 | body=[ |
| 1183 | Expr( |
| 1184 | value=BinOp( |
| 1185 | left=Name(id='a', ctx=Load()), |
| 1186 | op=Add(), |
Serhiy Storchaka | b7e9525 | 2020-03-10 00:07:47 +0200 | [diff] [blame] | 1187 | right=Constant(value=1)))], |
Pablo Galindo | 114081f | 2020-03-02 03:14:06 +0000 | [diff] [blame] | 1188 | handlers=[ |
| 1189 | ExceptHandler( |
| 1190 | type=Name(id='TypeError', ctx=Load()), |
Pablo Galindo | 114081f | 2020-03-02 03:14:06 +0000 | [diff] [blame] | 1191 | body=[ |
| 1192 | Pass()])], |
| 1193 | orelse=[], |
| 1194 | finalbody=[])], |
| 1195 | type_ignores=[]) |
| 1196 | |
| 1197 | |
| 1198 | .. class:: With(items, body, type_comment) |
| 1199 | |
| 1200 | A ``with`` block. ``items`` is a list of :class:`withitem` nodes representing |
| 1201 | the context managers, and ``body`` is the indented block inside the context. |
| 1202 | |
| 1203 | .. attribute:: type_comment |
| 1204 | |
| 1205 | ``type_comment`` is an optional string with the type annotation as a comment. |
| 1206 | |
| 1207 | |
| 1208 | .. class:: withitem(context_expr, optional_vars) |
| 1209 | |
| 1210 | A single context manager in a ``with`` block. ``context_expr`` is the context |
| 1211 | manager, often a :class:`Call` node. ``optional_vars`` is a :class:`Name`, |
| 1212 | :class:`Tuple` or :class:`List` for the ``as foo`` part, or ``None`` if that |
| 1213 | isn't used. |
| 1214 | |
| 1215 | .. doctest:: |
| 1216 | |
| 1217 | >>> print(ast.dump(ast.parse("""\ |
| 1218 | ... with a as b, c as d: |
| 1219 | ... something(b, d) |
| 1220 | ... """), indent=4)) |
| 1221 | Module( |
| 1222 | body=[ |
| 1223 | With( |
| 1224 | items=[ |
| 1225 | withitem( |
| 1226 | context_expr=Name(id='a', ctx=Load()), |
| 1227 | optional_vars=Name(id='b', ctx=Store())), |
| 1228 | withitem( |
| 1229 | context_expr=Name(id='c', ctx=Load()), |
| 1230 | optional_vars=Name(id='d', ctx=Store()))], |
| 1231 | body=[ |
| 1232 | Expr( |
| 1233 | value=Call( |
| 1234 | func=Name(id='something', ctx=Load()), |
| 1235 | args=[ |
| 1236 | Name(id='b', ctx=Load()), |
| 1237 | Name(id='d', ctx=Load())], |
Serhiy Storchaka | b7e9525 | 2020-03-10 00:07:47 +0200 | [diff] [blame] | 1238 | keywords=[]))])], |
Pablo Galindo | 114081f | 2020-03-02 03:14:06 +0000 | [diff] [blame] | 1239 | type_ignores=[]) |
| 1240 | |
| 1241 | |
| 1242 | Function and class definitions |
| 1243 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 1244 | |
| 1245 | .. class:: FunctionDef(name, args, body, decorator_list, returns, type_comment) |
| 1246 | |
| 1247 | A function definition. |
| 1248 | |
| 1249 | * ``name`` is a raw string of the function name. |
| 1250 | * ``args`` is a :class:`arguments` node. |
| 1251 | * ``body`` is the list of nodes inside the function. |
| 1252 | * ``decorator_list`` is the list of decorators to be applied, stored outermost |
| 1253 | first (i.e. the first in the list will be applied last). |
| 1254 | * ``returns`` is the return annotation. |
| 1255 | |
| 1256 | .. attribute:: type_comment |
| 1257 | |
| 1258 | ``type_comment`` is an optional string with the type annotation as a comment. |
| 1259 | |
| 1260 | |
| 1261 | .. class:: Lambda(args, body) |
| 1262 | |
| 1263 | ``lambda`` is a minimal function definition that can be used inside an |
| 1264 | expression. Unlike :class:`FunctionDef`, ``body`` holds a single node. |
| 1265 | |
| 1266 | .. doctest:: |
| 1267 | |
Pablo Galindo | 02f64cb | 2020-03-07 18:22:58 +0000 | [diff] [blame] | 1268 | >>> print(ast.dump(ast.parse('lambda x,y: ...'), indent=4)) |
Pablo Galindo | 114081f | 2020-03-02 03:14:06 +0000 | [diff] [blame] | 1269 | Module( |
| 1270 | body=[ |
| 1271 | Expr( |
| 1272 | value=Lambda( |
| 1273 | args=arguments( |
| 1274 | posonlyargs=[], |
| 1275 | args=[ |
Serhiy Storchaka | b7e9525 | 2020-03-10 00:07:47 +0200 | [diff] [blame] | 1276 | arg(arg='x'), |
| 1277 | arg(arg='y')], |
Pablo Galindo | 114081f | 2020-03-02 03:14:06 +0000 | [diff] [blame] | 1278 | kwonlyargs=[], |
| 1279 | kw_defaults=[], |
Pablo Galindo | 114081f | 2020-03-02 03:14:06 +0000 | [diff] [blame] | 1280 | defaults=[]), |
Serhiy Storchaka | b7e9525 | 2020-03-10 00:07:47 +0200 | [diff] [blame] | 1281 | body=Constant(value=Ellipsis)))], |
Pablo Galindo | 114081f | 2020-03-02 03:14:06 +0000 | [diff] [blame] | 1282 | type_ignores=[]) |
| 1283 | |
| 1284 | |
| 1285 | .. class:: arguments(posonlyargs, args, vararg, kwonlyargs, kw_defaults, kwarg, defaults) |
| 1286 | |
| 1287 | The arguments for a function. |
| 1288 | |
| 1289 | * ``posonlyargs``, ``args`` and ``kwonlyargs`` are lists of :class:`arg` nodes. |
| 1290 | * ``vararg`` and ``kwarg`` are single :class:`arg` nodes, referring to the |
| 1291 | ``*args, **kwargs`` parameters. |
| 1292 | * ``kw_defaults`` is a list of default values for keyword-only arguments. If |
| 1293 | one is ``None``, the corresponding argument is required. |
| 1294 | * ``defaults`` is a list of default values for arguments that can be passed |
| 1295 | positionally. If there are fewer defaults, they correspond to the last n |
| 1296 | arguments. |
| 1297 | |
| 1298 | |
| 1299 | .. class:: arg(arg, annotation, type_comment) |
| 1300 | |
| 1301 | A single argument in a list. ``arg`` is a raw string of the argument |
| 1302 | name, ``annotation`` is its annotation, such as a :class:`Str` or |
| 1303 | :class:`Name` node. |
| 1304 | |
| 1305 | .. attribute:: type_comment |
| 1306 | |
| 1307 | ``type_comment`` is an optional string with the type annotation as a comment |
| 1308 | |
| 1309 | .. doctest:: |
| 1310 | |
| 1311 | >>> print(ast.dump(ast.parse("""\ |
| 1312 | ... @decorator1 |
| 1313 | ... @decorator2 |
| 1314 | ... def f(a: 'annotation', b=1, c=2, *d, e, f=3, **g) -> 'return annotation': |
| 1315 | ... pass |
| 1316 | ... """), indent=4)) |
| 1317 | Module( |
| 1318 | body=[ |
| 1319 | FunctionDef( |
| 1320 | name='f', |
| 1321 | args=arguments( |
| 1322 | posonlyargs=[], |
| 1323 | args=[ |
| 1324 | arg( |
| 1325 | arg='a', |
Serhiy Storchaka | b7e9525 | 2020-03-10 00:07:47 +0200 | [diff] [blame] | 1326 | annotation=Constant(value='annotation')), |
| 1327 | arg(arg='b'), |
| 1328 | arg(arg='c')], |
| 1329 | vararg=arg(arg='d'), |
Pablo Galindo | 114081f | 2020-03-02 03:14:06 +0000 | [diff] [blame] | 1330 | kwonlyargs=[ |
Serhiy Storchaka | b7e9525 | 2020-03-10 00:07:47 +0200 | [diff] [blame] | 1331 | arg(arg='e'), |
| 1332 | arg(arg='f')], |
Pablo Galindo | 114081f | 2020-03-02 03:14:06 +0000 | [diff] [blame] | 1333 | kw_defaults=[ |
| 1334 | None, |
Serhiy Storchaka | b7e9525 | 2020-03-10 00:07:47 +0200 | [diff] [blame] | 1335 | Constant(value=3)], |
| 1336 | kwarg=arg(arg='g'), |
Pablo Galindo | 114081f | 2020-03-02 03:14:06 +0000 | [diff] [blame] | 1337 | defaults=[ |
Serhiy Storchaka | b7e9525 | 2020-03-10 00:07:47 +0200 | [diff] [blame] | 1338 | Constant(value=1), |
| 1339 | Constant(value=2)]), |
Pablo Galindo | 114081f | 2020-03-02 03:14:06 +0000 | [diff] [blame] | 1340 | body=[ |
| 1341 | Pass()], |
| 1342 | decorator_list=[ |
| 1343 | Name(id='decorator1', ctx=Load()), |
| 1344 | Name(id='decorator2', ctx=Load())], |
Serhiy Storchaka | b7e9525 | 2020-03-10 00:07:47 +0200 | [diff] [blame] | 1345 | returns=Constant(value='return annotation'))], |
Pablo Galindo | 114081f | 2020-03-02 03:14:06 +0000 | [diff] [blame] | 1346 | type_ignores=[]) |
| 1347 | |
| 1348 | |
| 1349 | .. class:: Return(value) |
| 1350 | |
| 1351 | A ``return`` statement. |
| 1352 | |
| 1353 | .. doctest:: |
| 1354 | |
Pablo Galindo | 02f64cb | 2020-03-07 18:22:58 +0000 | [diff] [blame] | 1355 | >>> print(ast.dump(ast.parse('return 4'), indent=4)) |
Pablo Galindo | 114081f | 2020-03-02 03:14:06 +0000 | [diff] [blame] | 1356 | Module( |
| 1357 | body=[ |
| 1358 | Return( |
Serhiy Storchaka | b7e9525 | 2020-03-10 00:07:47 +0200 | [diff] [blame] | 1359 | value=Constant(value=4))], |
Pablo Galindo | 114081f | 2020-03-02 03:14:06 +0000 | [diff] [blame] | 1360 | type_ignores=[]) |
| 1361 | |
| 1362 | |
| 1363 | .. class:: Yield(value) |
| 1364 | YieldFrom(value) |
| 1365 | |
| 1366 | A ``yield`` or ``yield from`` expression. Because these are expressions, they |
| 1367 | must be wrapped in a :class:`Expr` node if the value sent back is not used. |
| 1368 | |
| 1369 | .. doctest:: |
| 1370 | |
Pablo Galindo | 02f64cb | 2020-03-07 18:22:58 +0000 | [diff] [blame] | 1371 | >>> print(ast.dump(ast.parse('yield x'), indent=4)) |
Pablo Galindo | 114081f | 2020-03-02 03:14:06 +0000 | [diff] [blame] | 1372 | Module( |
| 1373 | body=[ |
| 1374 | Expr( |
| 1375 | value=Yield( |
| 1376 | value=Name(id='x', ctx=Load())))], |
| 1377 | type_ignores=[]) |
| 1378 | |
Pablo Galindo | 02f64cb | 2020-03-07 18:22:58 +0000 | [diff] [blame] | 1379 | >>> print(ast.dump(ast.parse('yield from x'), indent=4)) |
Pablo Galindo | 114081f | 2020-03-02 03:14:06 +0000 | [diff] [blame] | 1380 | Module( |
| 1381 | body=[ |
| 1382 | Expr( |
| 1383 | value=YieldFrom( |
| 1384 | value=Name(id='x', ctx=Load())))], |
| 1385 | type_ignores=[]) |
| 1386 | |
| 1387 | |
| 1388 | .. class:: Global(names) |
| 1389 | Nonlocal(names) |
| 1390 | |
| 1391 | ``global`` and ``nonlocal`` statements. ``names`` is a list of raw strings. |
| 1392 | |
| 1393 | .. doctest:: |
| 1394 | |
Pablo Galindo | 02f64cb | 2020-03-07 18:22:58 +0000 | [diff] [blame] | 1395 | >>> print(ast.dump(ast.parse('global x,y,z'), indent=4)) |
Pablo Galindo | 114081f | 2020-03-02 03:14:06 +0000 | [diff] [blame] | 1396 | Module( |
| 1397 | body=[ |
| 1398 | Global( |
| 1399 | names=[ |
| 1400 | 'x', |
| 1401 | 'y', |
| 1402 | 'z'])], |
| 1403 | type_ignores=[]) |
| 1404 | |
Pablo Galindo | 02f64cb | 2020-03-07 18:22:58 +0000 | [diff] [blame] | 1405 | >>> print(ast.dump(ast.parse('nonlocal x,y,z'), indent=4)) |
Pablo Galindo | 114081f | 2020-03-02 03:14:06 +0000 | [diff] [blame] | 1406 | Module( |
| 1407 | body=[ |
| 1408 | Nonlocal( |
| 1409 | names=[ |
| 1410 | 'x', |
| 1411 | 'y', |
| 1412 | 'z'])], |
| 1413 | type_ignores=[]) |
| 1414 | |
| 1415 | |
| 1416 | .. class:: ClassDef(name, bases, keywords, starargs, kwargs, body, decorator_list) |
| 1417 | |
| 1418 | A class definition. |
| 1419 | |
| 1420 | * ``name`` is a raw string for the class name |
| 1421 | * ``bases`` is a list of nodes for explicitly specified base classes. |
| 1422 | * ``keywords`` is a list of :class:`keyword` nodes, principally for 'metaclass'. |
| 1423 | Other keywords will be passed to the metaclass, as per `PEP-3115 |
| 1424 | <http://www.python.org/dev/peps/pep-3115/>`_. |
| 1425 | * ``starargs`` and ``kwargs`` are each a single node, as in a function call. |
| 1426 | starargs will be expanded to join the list of base classes, and kwargs will |
| 1427 | be passed to the metaclass. |
| 1428 | * ``body`` is a list of nodes representing the code within the class |
| 1429 | definition. |
| 1430 | * ``decorator_list`` is a list of nodes, as in :class:`FunctionDef`. |
| 1431 | |
| 1432 | .. doctest:: |
| 1433 | |
| 1434 | >>> print(ast.dump(ast.parse("""\ |
| 1435 | ... @decorator1 |
| 1436 | ... @decorator2 |
| 1437 | ... class Foo(base1, base2, metaclass=meta): |
| 1438 | ... pass |
| 1439 | ... """), indent=4)) |
| 1440 | Module( |
| 1441 | body=[ |
| 1442 | ClassDef( |
| 1443 | name='Foo', |
| 1444 | bases=[ |
| 1445 | Name(id='base1', ctx=Load()), |
| 1446 | Name(id='base2', ctx=Load())], |
| 1447 | keywords=[ |
| 1448 | keyword( |
| 1449 | arg='metaclass', |
| 1450 | value=Name(id='meta', ctx=Load()))], |
| 1451 | body=[ |
| 1452 | Pass()], |
| 1453 | decorator_list=[ |
| 1454 | Name(id='decorator1', ctx=Load()), |
| 1455 | Name(id='decorator2', ctx=Load())])], |
| 1456 | type_ignores=[]) |
| 1457 | |
| 1458 | Async and await |
| 1459 | ^^^^^^^^^^^^^^^ |
| 1460 | |
| 1461 | .. class:: AsyncFunctionDef(name, args, body, decorator_list, returns, type_comment) |
| 1462 | |
| 1463 | An ``async def`` function definition. Has the same fields as |
| 1464 | :class:`FunctionDef`. |
| 1465 | |
| 1466 | |
| 1467 | .. class:: Await(value) |
| 1468 | |
| 1469 | An ``await`` expression. ``value`` is what it waits for. |
| 1470 | Only valid in the body of an :class:`AsyncFunctionDef`. |
| 1471 | |
| 1472 | .. doctest:: |
| 1473 | |
| 1474 | >>> print(ast.dump(ast.parse("""\ |
| 1475 | ... async def f(): |
| 1476 | ... await other_func() |
| 1477 | ... """), indent=4)) |
| 1478 | Module( |
| 1479 | body=[ |
| 1480 | AsyncFunctionDef( |
| 1481 | name='f', |
| 1482 | args=arguments( |
| 1483 | posonlyargs=[], |
| 1484 | args=[], |
Pablo Galindo | 114081f | 2020-03-02 03:14:06 +0000 | [diff] [blame] | 1485 | kwonlyargs=[], |
| 1486 | kw_defaults=[], |
Pablo Galindo | 114081f | 2020-03-02 03:14:06 +0000 | [diff] [blame] | 1487 | defaults=[]), |
| 1488 | body=[ |
| 1489 | Expr( |
| 1490 | value=Await( |
| 1491 | value=Call( |
| 1492 | func=Name(id='other_func', ctx=Load()), |
| 1493 | args=[], |
| 1494 | keywords=[])))], |
Serhiy Storchaka | b7e9525 | 2020-03-10 00:07:47 +0200 | [diff] [blame] | 1495 | decorator_list=[])], |
Pablo Galindo | 114081f | 2020-03-02 03:14:06 +0000 | [diff] [blame] | 1496 | type_ignores=[]) |
| 1497 | |
| 1498 | |
| 1499 | .. class:: AsyncFor(target, iter, body, orelse, type_comment) |
| 1500 | AsyncWith(items, body, type_comment) |
| 1501 | |
| 1502 | ``async for`` loops and ``async with`` context managers. They have the same |
| 1503 | fields as :class:`For` and :class:`With`, respectively. Only valid in the |
| 1504 | body of an :class:`AsyncFunctionDef`. |
Georg Brandl | 0c77a82 | 2008-06-10 16:37:50 +0000 | [diff] [blame] | 1505 | |
| 1506 | |
| 1507 | :mod:`ast` Helpers |
| 1508 | ------------------ |
| 1509 | |
Martin Panter | 2e4571a | 2015-11-14 01:07:43 +0000 | [diff] [blame] | 1510 | 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] | 1511 | and classes for traversing abstract syntax trees: |
| 1512 | |
Guido van Rossum | 10b55c1 | 2019-06-11 17:23:12 -0700 | [diff] [blame] | 1513 | .. 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] | 1514 | |
Terry Reedy | feac624 | 2011-01-24 21:36:03 +0000 | [diff] [blame] | 1515 | Parse the source into an AST node. Equivalent to ``compile(source, |
Benjamin Peterson | ec9199b | 2008-11-08 17:05:00 +0000 | [diff] [blame] | 1516 | filename, mode, ast.PyCF_ONLY_AST)``. |
Georg Brandl | 0c77a82 | 2008-06-10 16:37:50 +0000 | [diff] [blame] | 1517 | |
Guido van Rossum | dcfcd14 | 2019-01-31 03:40:27 -0800 | [diff] [blame] | 1518 | If ``type_comments=True`` is given, the parser is modified to check |
| 1519 | and return type comments as specified by :pep:`484` and :pep:`526`. |
| 1520 | This is equivalent to adding :data:`ast.PyCF_TYPE_COMMENTS` to the |
| 1521 | flags passed to :func:`compile()`. This will report syntax errors |
| 1522 | for misplaced type comments. Without this flag, type comments will |
| 1523 | be ignored, and the ``type_comment`` field on selected AST nodes |
| 1524 | will always be ``None``. In addition, the locations of ``# type: |
| 1525 | ignore`` comments will be returned as the ``type_ignores`` |
| 1526 | attribute of :class:`Module` (otherwise it is always an empty list). |
| 1527 | |
| 1528 | In addition, if ``mode`` is ``'func_type'``, the input syntax is |
| 1529 | modified to correspond to :pep:`484` "signature type comments", |
| 1530 | e.g. ``(str, int) -> List[str]``. |
| 1531 | |
Guido van Rossum | 10b55c1 | 2019-06-11 17:23:12 -0700 | [diff] [blame] | 1532 | Also, setting ``feature_version`` to a tuple ``(major, minor)`` |
| 1533 | will attempt to parse using that Python version's grammar. |
| 1534 | Currently ``major`` must equal to ``3``. For example, setting |
| 1535 | ``feature_version=(3, 4)`` will allow the use of ``async`` and |
| 1536 | ``await`` as variable names. The lowest supported version is |
| 1537 | ``(3, 4)``; the highest is ``sys.version_info[0:2]``. |
Guido van Rossum | 495da29 | 2019-03-07 12:38:08 -0800 | [diff] [blame] | 1538 | |
Brett Cannon | 7a7f100 | 2018-03-09 12:03:22 -0800 | [diff] [blame] | 1539 | .. warning:: |
| 1540 | It is possible to crash the Python interpreter with a |
| 1541 | sufficiently large/complex string due to stack depth limitations |
| 1542 | in Python's AST compiler. |
| 1543 | |
Guido van Rossum | dcfcd14 | 2019-01-31 03:40:27 -0800 | [diff] [blame] | 1544 | .. versionchanged:: 3.8 |
Guido van Rossum | 495da29 | 2019-03-07 12:38:08 -0800 | [diff] [blame] | 1545 | Added ``type_comments``, ``mode='func_type'`` and ``feature_version``. |
Guido van Rossum | dcfcd14 | 2019-01-31 03:40:27 -0800 | [diff] [blame] | 1546 | |
Georg Brandl | 48310cd | 2009-01-03 21:18:54 +0000 | [diff] [blame] | 1547 | |
Pablo Galindo | 27fc3b6 | 2019-11-24 23:02:40 +0000 | [diff] [blame] | 1548 | .. function:: unparse(ast_obj) |
| 1549 | |
| 1550 | Unparse an :class:`ast.AST` object and generate a string with code |
| 1551 | that would produce an equivalent :class:`ast.AST` object if parsed |
| 1552 | back with :func:`ast.parse`. |
| 1553 | |
| 1554 | .. warning:: |
Gurupad Hegde | 6c7bb38 | 2019-12-28 17:16:02 -0500 | [diff] [blame] | 1555 | The produced code string will not necessarily be equal to the original |
Pablo Galindo | 6e39999 | 2020-06-28 02:22:30 +0100 | [diff] [blame^] | 1556 | code that generated the :class:`ast.AST` object (without any compiler |
| 1557 | optimizations, such as constant tuples/frozensets). |
| 1558 | |
| 1559 | .. warning:: |
| 1560 | Trying to unparse a highly complex expression would result with |
| 1561 | :exc:`RecursionError`. |
Pablo Galindo | 27fc3b6 | 2019-11-24 23:02:40 +0000 | [diff] [blame] | 1562 | |
| 1563 | .. versionadded:: 3.9 |
| 1564 | |
| 1565 | |
Georg Brandl | 0c77a82 | 2008-06-10 16:37:50 +0000 | [diff] [blame] | 1566 | .. function:: literal_eval(node_or_string) |
| 1567 | |
Georg Brandl | b9b389e | 2014-11-05 20:20:28 +0100 | [diff] [blame] | 1568 | Safely evaluate an expression node or a string containing a Python literal or |
| 1569 | container display. The string or node provided may only consist of the |
| 1570 | following Python literal structures: strings, bytes, numbers, tuples, lists, |
| 1571 | dicts, sets, booleans, and ``None``. |
Georg Brandl | 0c77a82 | 2008-06-10 16:37:50 +0000 | [diff] [blame] | 1572 | |
Georg Brandl | b9b389e | 2014-11-05 20:20:28 +0100 | [diff] [blame] | 1573 | This can be used for safely evaluating strings containing Python values from |
| 1574 | untrusted sources without the need to parse the values oneself. It is not |
| 1575 | capable of evaluating arbitrarily complex expressions, for example involving |
| 1576 | operators or indexing. |
Georg Brandl | 0c77a82 | 2008-06-10 16:37:50 +0000 | [diff] [blame] | 1577 | |
Brett Cannon | 7a7f100 | 2018-03-09 12:03:22 -0800 | [diff] [blame] | 1578 | .. warning:: |
| 1579 | It is possible to crash the Python interpreter with a |
| 1580 | sufficiently large/complex string due to stack depth limitations |
| 1581 | in Python's AST compiler. |
| 1582 | |
Georg Brandl | 492f3fc | 2010-07-11 09:41:21 +0000 | [diff] [blame] | 1583 | .. versionchanged:: 3.2 |
Georg Brandl | 85f2177 | 2010-07-13 06:38:10 +0000 | [diff] [blame] | 1584 | Now allows bytes and set literals. |
Georg Brandl | 492f3fc | 2010-07-11 09:41:21 +0000 | [diff] [blame] | 1585 | |
Raymond Hettinger | 4fcf5c1 | 2020-01-02 22:21:18 -0700 | [diff] [blame] | 1586 | .. versionchanged:: 3.9 |
| 1587 | Now supports creating empty sets with ``'set()'``. |
| 1588 | |
Georg Brandl | 0c77a82 | 2008-06-10 16:37:50 +0000 | [diff] [blame] | 1589 | |
Amaury Forgeot d'Arc | fdfe62d | 2008-06-17 20:36:03 +0000 | [diff] [blame] | 1590 | .. function:: get_docstring(node, clean=True) |
Georg Brandl | 0c77a82 | 2008-06-10 16:37:50 +0000 | [diff] [blame] | 1591 | |
| 1592 | Return the docstring of the given *node* (which must be a |
INADA Naoki | cb41b27 | 2017-02-23 00:31:59 +0900 | [diff] [blame] | 1593 | :class:`FunctionDef`, :class:`AsyncFunctionDef`, :class:`ClassDef`, |
| 1594 | or :class:`Module` node), or ``None`` if it has no docstring. |
| 1595 | If *clean* is true, clean up the docstring's indentation with |
| 1596 | :func:`inspect.cleandoc`. |
| 1597 | |
| 1598 | .. versionchanged:: 3.5 |
| 1599 | :class:`AsyncFunctionDef` is now supported. |
| 1600 | |
Georg Brandl | 0c77a82 | 2008-06-10 16:37:50 +0000 | [diff] [blame] | 1601 | |
Ivan Levkivskyi | 9932a22 | 2019-01-22 11:18:22 +0000 | [diff] [blame] | 1602 | .. function:: get_source_segment(source, node, *, padded=False) |
| 1603 | |
| 1604 | Get source code segment of the *source* that generated *node*. |
| 1605 | If some location information (:attr:`lineno`, :attr:`end_lineno`, |
| 1606 | :attr:`col_offset`, or :attr:`end_col_offset`) is missing, return ``None``. |
| 1607 | |
| 1608 | If *padded* is ``True``, the first line of a multi-line statement will |
| 1609 | be padded with spaces to match its original position. |
| 1610 | |
| 1611 | .. versionadded:: 3.8 |
| 1612 | |
| 1613 | |
Georg Brandl | 0c77a82 | 2008-06-10 16:37:50 +0000 | [diff] [blame] | 1614 | .. function:: fix_missing_locations(node) |
| 1615 | |
| 1616 | When you compile a node tree with :func:`compile`, the compiler expects |
| 1617 | :attr:`lineno` and :attr:`col_offset` attributes for every node that supports |
| 1618 | them. This is rather tedious to fill in for generated nodes, so this helper |
| 1619 | adds these attributes recursively where not already set, by setting them to |
| 1620 | the values of the parent node. It works recursively starting at *node*. |
| 1621 | |
| 1622 | |
| 1623 | .. function:: increment_lineno(node, n=1) |
| 1624 | |
Ivan Levkivskyi | 9932a22 | 2019-01-22 11:18:22 +0000 | [diff] [blame] | 1625 | Increment the line number and end line number of each node in the tree |
| 1626 | starting at *node* by *n*. This is useful to "move code" to a different |
| 1627 | location in a file. |
Georg Brandl | 0c77a82 | 2008-06-10 16:37:50 +0000 | [diff] [blame] | 1628 | |
| 1629 | |
| 1630 | .. function:: copy_location(new_node, old_node) |
| 1631 | |
Ivan Levkivskyi | 9932a22 | 2019-01-22 11:18:22 +0000 | [diff] [blame] | 1632 | Copy source location (:attr:`lineno`, :attr:`col_offset`, :attr:`end_lineno`, |
| 1633 | and :attr:`end_col_offset`) from *old_node* to *new_node* if possible, |
| 1634 | and return *new_node*. |
Georg Brandl | 0c77a82 | 2008-06-10 16:37:50 +0000 | [diff] [blame] | 1635 | |
| 1636 | |
| 1637 | .. function:: iter_fields(node) |
| 1638 | |
| 1639 | Yield a tuple of ``(fieldname, value)`` for each field in ``node._fields`` |
| 1640 | that is present on *node*. |
| 1641 | |
| 1642 | |
| 1643 | .. function:: iter_child_nodes(node) |
| 1644 | |
| 1645 | Yield all direct child nodes of *node*, that is, all fields that are nodes |
| 1646 | and all items of fields that are lists of nodes. |
| 1647 | |
| 1648 | |
| 1649 | .. function:: walk(node) |
| 1650 | |
Georg Brandl | 619e7ba | 2011-01-09 07:38:51 +0000 | [diff] [blame] | 1651 | Recursively yield all descendant nodes in the tree starting at *node* |
| 1652 | (including *node* itself), in no specified order. This is useful if you only |
| 1653 | want to modify nodes in place and don't care about the context. |
Georg Brandl | 0c77a82 | 2008-06-10 16:37:50 +0000 | [diff] [blame] | 1654 | |
| 1655 | |
| 1656 | .. class:: NodeVisitor() |
| 1657 | |
| 1658 | A node visitor base class that walks the abstract syntax tree and calls a |
| 1659 | visitor function for every node found. This function may return a value |
Georg Brandl | 36ab1ef | 2009-01-03 21:17:04 +0000 | [diff] [blame] | 1660 | which is forwarded by the :meth:`visit` method. |
Georg Brandl | 0c77a82 | 2008-06-10 16:37:50 +0000 | [diff] [blame] | 1661 | |
| 1662 | This class is meant to be subclassed, with the subclass adding visitor |
| 1663 | methods. |
| 1664 | |
| 1665 | .. method:: visit(node) |
| 1666 | |
| 1667 | Visit a node. The default implementation calls the method called |
| 1668 | :samp:`self.visit_{classname}` where *classname* is the name of the node |
| 1669 | class, or :meth:`generic_visit` if that method doesn't exist. |
| 1670 | |
| 1671 | .. method:: generic_visit(node) |
| 1672 | |
| 1673 | This visitor calls :meth:`visit` on all children of the node. |
Georg Brandl | 48310cd | 2009-01-03 21:18:54 +0000 | [diff] [blame] | 1674 | |
Georg Brandl | 0c77a82 | 2008-06-10 16:37:50 +0000 | [diff] [blame] | 1675 | Note that child nodes of nodes that have a custom visitor method won't be |
| 1676 | visited unless the visitor calls :meth:`generic_visit` or visits them |
| 1677 | itself. |
| 1678 | |
| 1679 | Don't use the :class:`NodeVisitor` if you want to apply changes to nodes |
| 1680 | during traversal. For this a special visitor exists |
| 1681 | (:class:`NodeTransformer`) that allows modifications. |
| 1682 | |
Serhiy Storchaka | c3ea41e | 2019-08-26 10:13:19 +0300 | [diff] [blame] | 1683 | .. deprecated:: 3.8 |
| 1684 | |
| 1685 | Methods :meth:`visit_Num`, :meth:`visit_Str`, :meth:`visit_Bytes`, |
| 1686 | :meth:`visit_NameConstant` and :meth:`visit_Ellipsis` are deprecated |
| 1687 | now and will not be called in future Python versions. Add the |
| 1688 | :meth:`visit_Constant` method to handle all constant nodes. |
| 1689 | |
Georg Brandl | 0c77a82 | 2008-06-10 16:37:50 +0000 | [diff] [blame] | 1690 | |
| 1691 | .. class:: NodeTransformer() |
| 1692 | |
| 1693 | A :class:`NodeVisitor` subclass that walks the abstract syntax tree and |
| 1694 | allows modification of nodes. |
| 1695 | |
Georg Brandl | 36ab1ef | 2009-01-03 21:17:04 +0000 | [diff] [blame] | 1696 | The :class:`NodeTransformer` will walk the AST and use the return value of |
| 1697 | the visitor methods to replace or remove the old node. If the return value |
| 1698 | of the visitor method is ``None``, the node will be removed from its |
| 1699 | location, otherwise it is replaced with the return value. The return value |
| 1700 | may be the original node in which case no replacement takes place. |
Georg Brandl | 0c77a82 | 2008-06-10 16:37:50 +0000 | [diff] [blame] | 1701 | |
| 1702 | Here is an example transformer that rewrites all occurrences of name lookups |
| 1703 | (``foo``) to ``data['foo']``:: |
| 1704 | |
| 1705 | class RewriteName(NodeTransformer): |
| 1706 | |
| 1707 | def visit_Name(self, node): |
Batuhan Taşkaya | 6680f4a | 2020-01-12 23:38:53 +0300 | [diff] [blame] | 1708 | return Subscript( |
Georg Brandl | 0c77a82 | 2008-06-10 16:37:50 +0000 | [diff] [blame] | 1709 | value=Name(id='data', ctx=Load()), |
Serhiy Storchaka | 13d52c2 | 2020-03-10 18:52:34 +0200 | [diff] [blame] | 1710 | slice=Constant(value=node.id), |
Georg Brandl | 0c77a82 | 2008-06-10 16:37:50 +0000 | [diff] [blame] | 1711 | ctx=node.ctx |
Pablo Galindo | c00c86b | 2020-03-12 00:48:19 +0000 | [diff] [blame] | 1712 | ) |
Georg Brandl | 0c77a82 | 2008-06-10 16:37:50 +0000 | [diff] [blame] | 1713 | |
| 1714 | Keep in mind that if the node you're operating on has child nodes you must |
| 1715 | either transform the child nodes yourself or call the :meth:`generic_visit` |
| 1716 | method for the node first. |
| 1717 | |
| 1718 | For nodes that were part of a collection of statements (that applies to all |
| 1719 | statement nodes), the visitor may also return a list of nodes rather than |
| 1720 | just a single node. |
| 1721 | |
Batuhan Taşkaya | 6680f4a | 2020-01-12 23:38:53 +0300 | [diff] [blame] | 1722 | If :class:`NodeTransformer` introduces new nodes (that weren't part of |
| 1723 | original tree) without giving them location information (such as |
| 1724 | :attr:`lineno`), :func:`fix_missing_locations` should be called with |
| 1725 | the new sub-tree to recalculate the location information:: |
| 1726 | |
| 1727 | tree = ast.parse('foo', mode='eval') |
| 1728 | new_tree = fix_missing_locations(RewriteName().visit(tree)) |
| 1729 | |
Georg Brandl | 0c77a82 | 2008-06-10 16:37:50 +0000 | [diff] [blame] | 1730 | Usually you use the transformer like this:: |
| 1731 | |
| 1732 | node = YourTransformer().visit(node) |
| 1733 | |
| 1734 | |
Serhiy Storchaka | 850573b | 2019-09-09 19:33:13 +0300 | [diff] [blame] | 1735 | .. function:: dump(node, annotate_fields=True, include_attributes=False, *, indent=None) |
Georg Brandl | 0c77a82 | 2008-06-10 16:37:50 +0000 | [diff] [blame] | 1736 | |
| 1737 | 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] | 1738 | debugging purposes. If *annotate_fields* is true (by default), |
| 1739 | the returned string will show the names and the values for fields. |
| 1740 | If *annotate_fields* is false, the result string will be more compact by |
| 1741 | omitting unambiguous field names. Attributes such as line |
Benjamin Peterson | dcf97b9 | 2008-07-02 17:30:14 +0000 | [diff] [blame] | 1742 | 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] | 1743 | *include_attributes* can be set to true. |
Senthil Kumaran | f3695bf | 2016-01-06 21:26:53 -0800 | [diff] [blame] | 1744 | |
Serhiy Storchaka | 850573b | 2019-09-09 19:33:13 +0300 | [diff] [blame] | 1745 | If *indent* is a non-negative integer or string, then the tree will be |
| 1746 | pretty-printed with that indent level. An indent level |
| 1747 | of 0, negative, or ``""`` will only insert newlines. ``None`` (the default) |
| 1748 | selects the single line representation. Using a positive integer indent |
| 1749 | indents that many spaces per level. If *indent* is a string (such as ``"\t"``), |
| 1750 | that string is used to indent each level. |
| 1751 | |
| 1752 | .. versionchanged:: 3.9 |
| 1753 | Added the *indent* option. |
| 1754 | |
| 1755 | |
Serhiy Storchaka | 832e864 | 2019-09-09 23:36:13 +0300 | [diff] [blame] | 1756 | .. _ast-cli: |
| 1757 | |
| 1758 | Command-Line Usage |
| 1759 | ------------------ |
| 1760 | |
| 1761 | .. versionadded:: 3.9 |
| 1762 | |
| 1763 | The :mod:`ast` module can be executed as a script from the command line. |
| 1764 | It is as simple as: |
| 1765 | |
| 1766 | .. code-block:: sh |
| 1767 | |
| 1768 | python -m ast [-m <mode>] [-a] [infile] |
| 1769 | |
| 1770 | The following options are accepted: |
| 1771 | |
| 1772 | .. program:: ast |
| 1773 | |
| 1774 | .. cmdoption:: -h, --help |
| 1775 | |
| 1776 | Show the help message and exit. |
| 1777 | |
| 1778 | .. cmdoption:: -m <mode> |
| 1779 | --mode <mode> |
| 1780 | |
| 1781 | Specify what kind of code must be compiled, like the *mode* argument |
| 1782 | in :func:`parse`. |
| 1783 | |
Batuhan Taşkaya | 814d687 | 2019-12-16 21:23:27 +0300 | [diff] [blame] | 1784 | .. cmdoption:: --no-type-comments |
| 1785 | |
| 1786 | Don't parse type comments. |
| 1787 | |
Serhiy Storchaka | 832e864 | 2019-09-09 23:36:13 +0300 | [diff] [blame] | 1788 | .. cmdoption:: -a, --include-attributes |
| 1789 | |
| 1790 | Include attributes such as line numbers and column offsets. |
| 1791 | |
Batuhan Taşkaya | 814d687 | 2019-12-16 21:23:27 +0300 | [diff] [blame] | 1792 | .. cmdoption:: -i <indent> |
| 1793 | --indent <indent> |
| 1794 | |
| 1795 | Indentation of nodes in AST (number of spaces). |
| 1796 | |
Serhiy Storchaka | 832e864 | 2019-09-09 23:36:13 +0300 | [diff] [blame] | 1797 | If :file:`infile` is specified its contents are parsed to AST and dumped |
| 1798 | to stdout. Otherwise, the content is read from stdin. |
| 1799 | |
| 1800 | |
Senthil Kumaran | f3695bf | 2016-01-06 21:26:53 -0800 | [diff] [blame] | 1801 | .. seealso:: |
| 1802 | |
Sanyam Khurana | 338cd83 | 2018-01-20 05:55:37 +0530 | [diff] [blame] | 1803 | `Green Tree Snakes <https://greentreesnakes.readthedocs.io/>`_, an external documentation resource, has good |
Senthil Kumaran | f3695bf | 2016-01-06 21:26:53 -0800 | [diff] [blame] | 1804 | details on working with Python ASTs. |