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 | |
Raymond Hettinger | 1048094 | 2011-01-10 03:26:08 +0000 | [diff] [blame] | 10 | **Source code:** :source:`Lib/ast.py` |
Georg Brandl | 0c77a82 | 2008-06-10 16:37:50 +0000 | [diff] [blame] | 11 | |
Raymond Hettinger | 4f707fd | 2011-01-10 19:54:11 +0000 | [diff] [blame] | 12 | -------------- |
| 13 | |
Georg Brandl | 0c77a82 | 2008-06-10 16:37:50 +0000 | [diff] [blame] | 14 | The :mod:`ast` module helps Python applications to process trees of the Python |
| 15 | abstract syntax grammar. The abstract syntax itself might change with each |
| 16 | Python release; this module helps to find out programmatically what the current |
| 17 | grammar looks like. |
| 18 | |
Benjamin Peterson | ec9199b | 2008-11-08 17:05:00 +0000 | [diff] [blame] | 19 | 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] | 20 | 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] | 21 | 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] | 22 | classes all inherit from :class:`ast.AST`. An abstract syntax tree can be |
| 23 | 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] | 24 | |
Georg Brandl | 0c77a82 | 2008-06-10 16:37:50 +0000 | [diff] [blame] | 25 | |
| 26 | Node classes |
| 27 | ------------ |
| 28 | |
| 29 | .. class:: AST |
| 30 | |
| 31 | This is the base of all AST node classes. The actual node classes are |
| 32 | derived from the :file:`Parser/Python.asdl` file, which is reproduced |
| 33 | :ref:`below <abstract-grammar>`. They are defined in the :mod:`_ast` C |
| 34 | module and re-exported in :mod:`ast`. |
| 35 | |
| 36 | There is one class defined for each left-hand side symbol in the abstract |
| 37 | grammar (for example, :class:`ast.stmt` or :class:`ast.expr`). In addition, |
| 38 | there is one class defined for each constructor on the right-hand side; these |
| 39 | classes inherit from the classes for the left-hand side trees. For example, |
| 40 | :class:`ast.BinOp` inherits from :class:`ast.expr`. For production rules |
| 41 | with alternatives (aka "sums"), the left-hand side class is abstract: only |
| 42 | instances of specific constructor nodes are ever created. |
| 43 | |
Serhiy Storchaka | 913876d | 2018-10-28 13:41:26 +0200 | [diff] [blame] | 44 | .. index:: single: ? (question mark); in AST grammar |
| 45 | .. index:: single: * (asterisk); in AST grammar |
| 46 | |
Georg Brandl | 0c77a82 | 2008-06-10 16:37:50 +0000 | [diff] [blame] | 47 | .. attribute:: _fields |
| 48 | |
| 49 | Each concrete class has an attribute :attr:`_fields` which gives the names |
| 50 | of all child nodes. |
| 51 | |
| 52 | Each instance of a concrete class has one attribute for each child node, |
| 53 | of the type as defined in the grammar. For example, :class:`ast.BinOp` |
| 54 | instances have an attribute :attr:`left` of type :class:`ast.expr`. |
| 55 | |
| 56 | If these attributes are marked as optional in the grammar (using a |
| 57 | question mark), the value might be ``None``. If the attributes can have |
| 58 | zero-or-more values (marked with an asterisk), the values are represented |
| 59 | as Python lists. All possible attributes must be present and have valid |
| 60 | values when compiling an AST with :func:`compile`. |
| 61 | |
| 62 | .. attribute:: lineno |
| 63 | col_offset |
Ivan Levkivskyi | 9932a22 | 2019-01-22 11:18:22 +0000 | [diff] [blame] | 64 | end_lineno |
| 65 | end_col_offset |
Georg Brandl | 0c77a82 | 2008-06-10 16:37:50 +0000 | [diff] [blame] | 66 | |
| 67 | Instances of :class:`ast.expr` and :class:`ast.stmt` subclasses have |
Ivan Levkivskyi | 9932a22 | 2019-01-22 11:18:22 +0000 | [diff] [blame] | 68 | :attr:`lineno`, :attr:`col_offset`, :attr:`lineno`, and :attr:`col_offset` |
| 69 | attributes. The :attr:`lineno` and :attr:`end_lineno` are the first and |
| 70 | last line numbers of source text span (1-indexed so the first line is line 1) |
| 71 | and the :attr:`col_offset` and :attr:`end_col_offset` are the corresponding |
| 72 | UTF-8 byte offsets of the first and last tokens that generated the node. |
| 73 | The UTF-8 offset is recorded because the parser uses UTF-8 internally. |
| 74 | |
| 75 | Note that the end positions are not required by the compiler and are |
| 76 | therefore optional. The end offset is *after* the last symbol, for example |
| 77 | one can get the source segment of a one-line expression node using |
| 78 | ``source_line[node.col_offset : node.end_col_offset]``. |
Georg Brandl | 0c77a82 | 2008-06-10 16:37:50 +0000 | [diff] [blame] | 79 | |
| 80 | The constructor of a class :class:`ast.T` parses its arguments as follows: |
| 81 | |
| 82 | * If there are positional arguments, there must be as many as there are items |
| 83 | in :attr:`T._fields`; they will be assigned as attributes of these names. |
| 84 | * If there are keyword arguments, they will set the attributes of the same |
| 85 | names to the given values. |
| 86 | |
| 87 | For example, to create and populate an :class:`ast.UnaryOp` node, you could |
| 88 | use :: |
| 89 | |
| 90 | node = ast.UnaryOp() |
| 91 | node.op = ast.USub() |
Serhiy Storchaka | 3f22811 | 2018-09-27 17:42:37 +0300 | [diff] [blame] | 92 | node.operand = ast.Constant() |
| 93 | node.operand.value = 5 |
Georg Brandl | 0c77a82 | 2008-06-10 16:37:50 +0000 | [diff] [blame] | 94 | node.operand.lineno = 0 |
| 95 | node.operand.col_offset = 0 |
| 96 | node.lineno = 0 |
| 97 | node.col_offset = 0 |
| 98 | |
| 99 | or the more compact :: |
| 100 | |
Serhiy Storchaka | 3f22811 | 2018-09-27 17:42:37 +0300 | [diff] [blame] | 101 | 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] | 102 | lineno=0, col_offset=0) |
| 103 | |
Serhiy Storchaka | 3f22811 | 2018-09-27 17:42:37 +0300 | [diff] [blame] | 104 | .. deprecated:: 3.8 |
| 105 | |
| 106 | Class :class:`ast.Constant` is now used for all constants. Old classes |
| 107 | :class:`ast.Num`, :class:`ast.Str`, :class:`ast.Bytes`, |
| 108 | :class:`ast.NameConstant` and :class:`ast.Ellipsis` are still available, |
| 109 | but they will be removed in future Python releases. |
| 110 | |
Georg Brandl | 0c77a82 | 2008-06-10 16:37:50 +0000 | [diff] [blame] | 111 | |
| 112 | .. _abstract-grammar: |
| 113 | |
| 114 | Abstract Grammar |
| 115 | ---------------- |
| 116 | |
Georg Brandl | 0c77a82 | 2008-06-10 16:37:50 +0000 | [diff] [blame] | 117 | The abstract grammar is currently defined as follows: |
| 118 | |
| 119 | .. literalinclude:: ../../Parser/Python.asdl |
Martin Panter | 1050d2d | 2016-07-26 11:18:21 +0200 | [diff] [blame] | 120 | :language: none |
Georg Brandl | 0c77a82 | 2008-06-10 16:37:50 +0000 | [diff] [blame] | 121 | |
| 122 | |
| 123 | :mod:`ast` Helpers |
| 124 | ------------------ |
| 125 | |
Martin Panter | 2e4571a | 2015-11-14 01:07:43 +0000 | [diff] [blame] | 126 | 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] | 127 | and classes for traversing abstract syntax trees: |
| 128 | |
Guido van Rossum | 10b55c1 | 2019-06-11 17:23:12 -0700 | [diff] [blame] | 129 | .. 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] | 130 | |
Terry Reedy | feac624 | 2011-01-24 21:36:03 +0000 | [diff] [blame] | 131 | Parse the source into an AST node. Equivalent to ``compile(source, |
Benjamin Peterson | ec9199b | 2008-11-08 17:05:00 +0000 | [diff] [blame] | 132 | filename, mode, ast.PyCF_ONLY_AST)``. |
Georg Brandl | 0c77a82 | 2008-06-10 16:37:50 +0000 | [diff] [blame] | 133 | |
Guido van Rossum | dcfcd14 | 2019-01-31 03:40:27 -0800 | [diff] [blame] | 134 | If ``type_comments=True`` is given, the parser is modified to check |
| 135 | and return type comments as specified by :pep:`484` and :pep:`526`. |
| 136 | This is equivalent to adding :data:`ast.PyCF_TYPE_COMMENTS` to the |
| 137 | flags passed to :func:`compile()`. This will report syntax errors |
| 138 | for misplaced type comments. Without this flag, type comments will |
| 139 | be ignored, and the ``type_comment`` field on selected AST nodes |
| 140 | will always be ``None``. In addition, the locations of ``# type: |
| 141 | ignore`` comments will be returned as the ``type_ignores`` |
| 142 | attribute of :class:`Module` (otherwise it is always an empty list). |
| 143 | |
| 144 | In addition, if ``mode`` is ``'func_type'``, the input syntax is |
| 145 | modified to correspond to :pep:`484` "signature type comments", |
| 146 | e.g. ``(str, int) -> List[str]``. |
| 147 | |
Guido van Rossum | 10b55c1 | 2019-06-11 17:23:12 -0700 | [diff] [blame] | 148 | Also, setting ``feature_version`` to a tuple ``(major, minor)`` |
| 149 | will attempt to parse using that Python version's grammar. |
| 150 | Currently ``major`` must equal to ``3``. For example, setting |
| 151 | ``feature_version=(3, 4)`` will allow the use of ``async`` and |
| 152 | ``await`` as variable names. The lowest supported version is |
| 153 | ``(3, 4)``; the highest is ``sys.version_info[0:2]``. |
Guido van Rossum | 495da29 | 2019-03-07 12:38:08 -0800 | [diff] [blame] | 154 | |
Brett Cannon | 7a7f100 | 2018-03-09 12:03:22 -0800 | [diff] [blame] | 155 | .. warning:: |
| 156 | It is possible to crash the Python interpreter with a |
| 157 | sufficiently large/complex string due to stack depth limitations |
| 158 | in Python's AST compiler. |
| 159 | |
Guido van Rossum | dcfcd14 | 2019-01-31 03:40:27 -0800 | [diff] [blame] | 160 | .. versionchanged:: 3.8 |
Guido van Rossum | 495da29 | 2019-03-07 12:38:08 -0800 | [diff] [blame] | 161 | Added ``type_comments``, ``mode='func_type'`` and ``feature_version``. |
Guido van Rossum | dcfcd14 | 2019-01-31 03:40:27 -0800 | [diff] [blame] | 162 | |
Georg Brandl | 48310cd | 2009-01-03 21:18:54 +0000 | [diff] [blame] | 163 | |
Pablo Galindo | 27fc3b6 | 2019-11-24 23:02:40 +0000 | [diff] [blame] | 164 | .. function:: unparse(ast_obj) |
| 165 | |
| 166 | Unparse an :class:`ast.AST` object and generate a string with code |
| 167 | that would produce an equivalent :class:`ast.AST` object if parsed |
| 168 | back with :func:`ast.parse`. |
| 169 | |
| 170 | .. warning:: |
Gurupad Hegde | 6c7bb38 | 2019-12-28 17:16:02 -0500 | [diff] [blame] | 171 | The produced code string will not necessarily be equal to the original |
Pablo Galindo | 27fc3b6 | 2019-11-24 23:02:40 +0000 | [diff] [blame] | 172 | code that generated the :class:`ast.AST` object. |
| 173 | |
| 174 | .. versionadded:: 3.9 |
| 175 | |
| 176 | |
Georg Brandl | 0c77a82 | 2008-06-10 16:37:50 +0000 | [diff] [blame] | 177 | .. function:: literal_eval(node_or_string) |
| 178 | |
Georg Brandl | b9b389e | 2014-11-05 20:20:28 +0100 | [diff] [blame] | 179 | Safely evaluate an expression node or a string containing a Python literal or |
| 180 | container display. The string or node provided may only consist of the |
| 181 | following Python literal structures: strings, bytes, numbers, tuples, lists, |
| 182 | dicts, sets, booleans, and ``None``. |
Georg Brandl | 0c77a82 | 2008-06-10 16:37:50 +0000 | [diff] [blame] | 183 | |
Georg Brandl | b9b389e | 2014-11-05 20:20:28 +0100 | [diff] [blame] | 184 | This can be used for safely evaluating strings containing Python values from |
| 185 | untrusted sources without the need to parse the values oneself. It is not |
| 186 | capable of evaluating arbitrarily complex expressions, for example involving |
| 187 | operators or indexing. |
Georg Brandl | 0c77a82 | 2008-06-10 16:37:50 +0000 | [diff] [blame] | 188 | |
Brett Cannon | 7a7f100 | 2018-03-09 12:03:22 -0800 | [diff] [blame] | 189 | .. warning:: |
| 190 | It is possible to crash the Python interpreter with a |
| 191 | sufficiently large/complex string due to stack depth limitations |
| 192 | in Python's AST compiler. |
| 193 | |
Georg Brandl | 492f3fc | 2010-07-11 09:41:21 +0000 | [diff] [blame] | 194 | .. versionchanged:: 3.2 |
Georg Brandl | 85f2177 | 2010-07-13 06:38:10 +0000 | [diff] [blame] | 195 | Now allows bytes and set literals. |
Georg Brandl | 492f3fc | 2010-07-11 09:41:21 +0000 | [diff] [blame] | 196 | |
Raymond Hettinger | 4fcf5c1 | 2020-01-02 22:21:18 -0700 | [diff] [blame] | 197 | .. versionchanged:: 3.9 |
| 198 | Now supports creating empty sets with ``'set()'``. |
| 199 | |
Georg Brandl | 0c77a82 | 2008-06-10 16:37:50 +0000 | [diff] [blame] | 200 | |
Amaury Forgeot d'Arc | fdfe62d | 2008-06-17 20:36:03 +0000 | [diff] [blame] | 201 | .. function:: get_docstring(node, clean=True) |
Georg Brandl | 0c77a82 | 2008-06-10 16:37:50 +0000 | [diff] [blame] | 202 | |
| 203 | Return the docstring of the given *node* (which must be a |
INADA Naoki | cb41b27 | 2017-02-23 00:31:59 +0900 | [diff] [blame] | 204 | :class:`FunctionDef`, :class:`AsyncFunctionDef`, :class:`ClassDef`, |
| 205 | or :class:`Module` node), or ``None`` if it has no docstring. |
| 206 | If *clean* is true, clean up the docstring's indentation with |
| 207 | :func:`inspect.cleandoc`. |
| 208 | |
| 209 | .. versionchanged:: 3.5 |
| 210 | :class:`AsyncFunctionDef` is now supported. |
| 211 | |
Georg Brandl | 0c77a82 | 2008-06-10 16:37:50 +0000 | [diff] [blame] | 212 | |
Ivan Levkivskyi | 9932a22 | 2019-01-22 11:18:22 +0000 | [diff] [blame] | 213 | .. function:: get_source_segment(source, node, *, padded=False) |
| 214 | |
| 215 | Get source code segment of the *source* that generated *node*. |
| 216 | If some location information (:attr:`lineno`, :attr:`end_lineno`, |
| 217 | :attr:`col_offset`, or :attr:`end_col_offset`) is missing, return ``None``. |
| 218 | |
| 219 | If *padded* is ``True``, the first line of a multi-line statement will |
| 220 | be padded with spaces to match its original position. |
| 221 | |
| 222 | .. versionadded:: 3.8 |
| 223 | |
| 224 | |
Georg Brandl | 0c77a82 | 2008-06-10 16:37:50 +0000 | [diff] [blame] | 225 | .. function:: fix_missing_locations(node) |
| 226 | |
| 227 | When you compile a node tree with :func:`compile`, the compiler expects |
| 228 | :attr:`lineno` and :attr:`col_offset` attributes for every node that supports |
| 229 | them. This is rather tedious to fill in for generated nodes, so this helper |
| 230 | adds these attributes recursively where not already set, by setting them to |
| 231 | the values of the parent node. It works recursively starting at *node*. |
| 232 | |
| 233 | |
| 234 | .. function:: increment_lineno(node, n=1) |
| 235 | |
Ivan Levkivskyi | 9932a22 | 2019-01-22 11:18:22 +0000 | [diff] [blame] | 236 | Increment the line number and end line number of each node in the tree |
| 237 | starting at *node* by *n*. This is useful to "move code" to a different |
| 238 | location in a file. |
Georg Brandl | 0c77a82 | 2008-06-10 16:37:50 +0000 | [diff] [blame] | 239 | |
| 240 | |
| 241 | .. function:: copy_location(new_node, old_node) |
| 242 | |
Ivan Levkivskyi | 9932a22 | 2019-01-22 11:18:22 +0000 | [diff] [blame] | 243 | Copy source location (:attr:`lineno`, :attr:`col_offset`, :attr:`end_lineno`, |
| 244 | and :attr:`end_col_offset`) from *old_node* to *new_node* if possible, |
| 245 | and return *new_node*. |
Georg Brandl | 0c77a82 | 2008-06-10 16:37:50 +0000 | [diff] [blame] | 246 | |
| 247 | |
| 248 | .. function:: iter_fields(node) |
| 249 | |
| 250 | Yield a tuple of ``(fieldname, value)`` for each field in ``node._fields`` |
| 251 | that is present on *node*. |
| 252 | |
| 253 | |
| 254 | .. function:: iter_child_nodes(node) |
| 255 | |
| 256 | Yield all direct child nodes of *node*, that is, all fields that are nodes |
| 257 | and all items of fields that are lists of nodes. |
| 258 | |
| 259 | |
| 260 | .. function:: walk(node) |
| 261 | |
Georg Brandl | 619e7ba | 2011-01-09 07:38:51 +0000 | [diff] [blame] | 262 | Recursively yield all descendant nodes in the tree starting at *node* |
| 263 | (including *node* itself), in no specified order. This is useful if you only |
| 264 | 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] | 265 | |
| 266 | |
| 267 | .. class:: NodeVisitor() |
| 268 | |
| 269 | A node visitor base class that walks the abstract syntax tree and calls a |
| 270 | visitor function for every node found. This function may return a value |
Georg Brandl | 36ab1ef | 2009-01-03 21:17:04 +0000 | [diff] [blame] | 271 | which is forwarded by the :meth:`visit` method. |
Georg Brandl | 0c77a82 | 2008-06-10 16:37:50 +0000 | [diff] [blame] | 272 | |
| 273 | This class is meant to be subclassed, with the subclass adding visitor |
| 274 | methods. |
| 275 | |
| 276 | .. method:: visit(node) |
| 277 | |
| 278 | Visit a node. The default implementation calls the method called |
| 279 | :samp:`self.visit_{classname}` where *classname* is the name of the node |
| 280 | class, or :meth:`generic_visit` if that method doesn't exist. |
| 281 | |
| 282 | .. method:: generic_visit(node) |
| 283 | |
| 284 | This visitor calls :meth:`visit` on all children of the node. |
Georg Brandl | 48310cd | 2009-01-03 21:18:54 +0000 | [diff] [blame] | 285 | |
Georg Brandl | 0c77a82 | 2008-06-10 16:37:50 +0000 | [diff] [blame] | 286 | Note that child nodes of nodes that have a custom visitor method won't be |
| 287 | visited unless the visitor calls :meth:`generic_visit` or visits them |
| 288 | itself. |
| 289 | |
| 290 | Don't use the :class:`NodeVisitor` if you want to apply changes to nodes |
| 291 | during traversal. For this a special visitor exists |
| 292 | (:class:`NodeTransformer`) that allows modifications. |
| 293 | |
Serhiy Storchaka | c3ea41e | 2019-08-26 10:13:19 +0300 | [diff] [blame] | 294 | .. deprecated:: 3.8 |
| 295 | |
| 296 | Methods :meth:`visit_Num`, :meth:`visit_Str`, :meth:`visit_Bytes`, |
| 297 | :meth:`visit_NameConstant` and :meth:`visit_Ellipsis` are deprecated |
| 298 | now and will not be called in future Python versions. Add the |
| 299 | :meth:`visit_Constant` method to handle all constant nodes. |
| 300 | |
Georg Brandl | 0c77a82 | 2008-06-10 16:37:50 +0000 | [diff] [blame] | 301 | |
| 302 | .. class:: NodeTransformer() |
| 303 | |
| 304 | A :class:`NodeVisitor` subclass that walks the abstract syntax tree and |
| 305 | allows modification of nodes. |
| 306 | |
Georg Brandl | 36ab1ef | 2009-01-03 21:17:04 +0000 | [diff] [blame] | 307 | The :class:`NodeTransformer` will walk the AST and use the return value of |
| 308 | the visitor methods to replace or remove the old node. If the return value |
| 309 | of the visitor method is ``None``, the node will be removed from its |
| 310 | location, otherwise it is replaced with the return value. The return value |
| 311 | may be the original node in which case no replacement takes place. |
Georg Brandl | 0c77a82 | 2008-06-10 16:37:50 +0000 | [diff] [blame] | 312 | |
| 313 | Here is an example transformer that rewrites all occurrences of name lookups |
| 314 | (``foo``) to ``data['foo']``:: |
| 315 | |
| 316 | class RewriteName(NodeTransformer): |
| 317 | |
| 318 | def visit_Name(self, node): |
Batuhan Taşkaya | 6680f4a | 2020-01-12 23:38:53 +0300 | [diff] [blame] | 319 | return Subscript( |
Georg Brandl | 0c77a82 | 2008-06-10 16:37:50 +0000 | [diff] [blame] | 320 | value=Name(id='data', ctx=Load()), |
Serhiy Storchaka | 3f22811 | 2018-09-27 17:42:37 +0300 | [diff] [blame] | 321 | slice=Index(value=Constant(value=node.id)), |
Georg Brandl | 0c77a82 | 2008-06-10 16:37:50 +0000 | [diff] [blame] | 322 | ctx=node.ctx |
| 323 | ), node) |
| 324 | |
| 325 | Keep in mind that if the node you're operating on has child nodes you must |
| 326 | either transform the child nodes yourself or call the :meth:`generic_visit` |
| 327 | method for the node first. |
| 328 | |
| 329 | For nodes that were part of a collection of statements (that applies to all |
| 330 | statement nodes), the visitor may also return a list of nodes rather than |
| 331 | just a single node. |
| 332 | |
Batuhan Taşkaya | 6680f4a | 2020-01-12 23:38:53 +0300 | [diff] [blame] | 333 | If :class:`NodeTransformer` introduces new nodes (that weren't part of |
| 334 | original tree) without giving them location information (such as |
| 335 | :attr:`lineno`), :func:`fix_missing_locations` should be called with |
| 336 | the new sub-tree to recalculate the location information:: |
| 337 | |
| 338 | tree = ast.parse('foo', mode='eval') |
| 339 | new_tree = fix_missing_locations(RewriteName().visit(tree)) |
| 340 | |
Georg Brandl | 0c77a82 | 2008-06-10 16:37:50 +0000 | [diff] [blame] | 341 | Usually you use the transformer like this:: |
| 342 | |
| 343 | node = YourTransformer().visit(node) |
| 344 | |
| 345 | |
Serhiy Storchaka | 850573b | 2019-09-09 19:33:13 +0300 | [diff] [blame] | 346 | .. function:: dump(node, annotate_fields=True, include_attributes=False, *, indent=None) |
Georg Brandl | 0c77a82 | 2008-06-10 16:37:50 +0000 | [diff] [blame] | 347 | |
| 348 | 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] | 349 | debugging purposes. If *annotate_fields* is true (by default), |
| 350 | the returned string will show the names and the values for fields. |
| 351 | If *annotate_fields* is false, the result string will be more compact by |
| 352 | omitting unambiguous field names. Attributes such as line |
Benjamin Peterson | dcf97b9 | 2008-07-02 17:30:14 +0000 | [diff] [blame] | 353 | 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] | 354 | *include_attributes* can be set to true. |
Senthil Kumaran | f3695bf | 2016-01-06 21:26:53 -0800 | [diff] [blame] | 355 | |
Serhiy Storchaka | 850573b | 2019-09-09 19:33:13 +0300 | [diff] [blame] | 356 | If *indent* is a non-negative integer or string, then the tree will be |
| 357 | pretty-printed with that indent level. An indent level |
| 358 | of 0, negative, or ``""`` will only insert newlines. ``None`` (the default) |
| 359 | selects the single line representation. Using a positive integer indent |
| 360 | indents that many spaces per level. If *indent* is a string (such as ``"\t"``), |
| 361 | that string is used to indent each level. |
| 362 | |
| 363 | .. versionchanged:: 3.9 |
| 364 | Added the *indent* option. |
| 365 | |
| 366 | |
Serhiy Storchaka | 832e864 | 2019-09-09 23:36:13 +0300 | [diff] [blame] | 367 | .. _ast-cli: |
| 368 | |
| 369 | Command-Line Usage |
| 370 | ------------------ |
| 371 | |
| 372 | .. versionadded:: 3.9 |
| 373 | |
| 374 | The :mod:`ast` module can be executed as a script from the command line. |
| 375 | It is as simple as: |
| 376 | |
| 377 | .. code-block:: sh |
| 378 | |
| 379 | python -m ast [-m <mode>] [-a] [infile] |
| 380 | |
| 381 | The following options are accepted: |
| 382 | |
| 383 | .. program:: ast |
| 384 | |
| 385 | .. cmdoption:: -h, --help |
| 386 | |
| 387 | Show the help message and exit. |
| 388 | |
| 389 | .. cmdoption:: -m <mode> |
| 390 | --mode <mode> |
| 391 | |
| 392 | Specify what kind of code must be compiled, like the *mode* argument |
| 393 | in :func:`parse`. |
| 394 | |
Batuhan Taşkaya | 814d687 | 2019-12-16 21:23:27 +0300 | [diff] [blame] | 395 | .. cmdoption:: --no-type-comments |
| 396 | |
| 397 | Don't parse type comments. |
| 398 | |
Serhiy Storchaka | 832e864 | 2019-09-09 23:36:13 +0300 | [diff] [blame] | 399 | .. cmdoption:: -a, --include-attributes |
| 400 | |
| 401 | Include attributes such as line numbers and column offsets. |
| 402 | |
Batuhan Taşkaya | 814d687 | 2019-12-16 21:23:27 +0300 | [diff] [blame] | 403 | .. cmdoption:: -i <indent> |
| 404 | --indent <indent> |
| 405 | |
| 406 | Indentation of nodes in AST (number of spaces). |
| 407 | |
Serhiy Storchaka | 832e864 | 2019-09-09 23:36:13 +0300 | [diff] [blame] | 408 | If :file:`infile` is specified its contents are parsed to AST and dumped |
| 409 | to stdout. Otherwise, the content is read from stdin. |
| 410 | |
| 411 | |
Senthil Kumaran | f3695bf | 2016-01-06 21:26:53 -0800 | [diff] [blame] | 412 | .. seealso:: |
| 413 | |
Sanyam Khurana | 338cd83 | 2018-01-20 05:55:37 +0530 | [diff] [blame] | 414 | `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] | 415 | details on working with Python ASTs. |