blob: 97ce2f5281b5a5aea0fbb60c80a7a2aed6e61ac7 [file] [log] [blame]
Alexander Belopolskyf0a0d142010-10-27 03:06:43 +00001:mod:`ast` --- Abstract Syntax Trees
2====================================
Georg Brandl0c77a822008-06-10 16:37:50 +00003
4.. module:: ast
5 :synopsis: Abstract Syntax Tree classes and manipulation.
6
7.. sectionauthor:: Martin v. Lรถwis <martin@v.loewis.de>
8.. sectionauthor:: Georg Brandl <georg@python.org>
9
Raymond Hettinger10480942011-01-10 03:26:08 +000010**Source code:** :source:`Lib/ast.py`
Georg Brandl0c77a822008-06-10 16:37:50 +000011
Raymond Hettinger4f707fd2011-01-10 19:54:11 +000012--------------
13
Georg Brandl0c77a822008-06-10 16:37:50 +000014The :mod:`ast` module helps Python applications to process trees of the Python
15abstract syntax grammar. The abstract syntax itself might change with each
16Python release; this module helps to find out programmatically what the current
17grammar looks like.
18
Benjamin Petersonec9199b2008-11-08 17:05:00 +000019An abstract syntax tree can be generated by passing :data:`ast.PyCF_ONLY_AST` as
Georg Brandl22b34312009-07-26 14:54:51 +000020a flag to the :func:`compile` built-in function, or using the :func:`parse`
Georg Brandl0c77a822008-06-10 16:37:50 +000021helper provided in this module. The result will be a tree of objects whose
Benjamin Petersonec9199b2008-11-08 17:05:00 +000022classes all inherit from :class:`ast.AST`. An abstract syntax tree can be
23compiled into a Python code object using the built-in :func:`compile` function.
Georg Brandl0c77a822008-06-10 16:37:50 +000024
Georg Brandl0c77a822008-06-10 16:37:50 +000025
26Node 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
44 .. attribute:: _fields
45
46 Each concrete class has an attribute :attr:`_fields` which gives the names
47 of all child nodes.
48
49 Each instance of a concrete class has one attribute for each child node,
50 of the type as defined in the grammar. For example, :class:`ast.BinOp`
51 instances have an attribute :attr:`left` of type :class:`ast.expr`.
52
53 If these attributes are marked as optional in the grammar (using a
54 question mark), the value might be ``None``. If the attributes can have
55 zero-or-more values (marked with an asterisk), the values are represented
56 as Python lists. All possible attributes must be present and have valid
57 values when compiling an AST with :func:`compile`.
58
59 .. attribute:: lineno
60 col_offset
61
62 Instances of :class:`ast.expr` and :class:`ast.stmt` subclasses have
63 :attr:`lineno` and :attr:`col_offset` attributes. The :attr:`lineno` is
64 the line number of source text (1-indexed so the first line is line 1) and
65 the :attr:`col_offset` is the UTF-8 byte offset of the first token that
66 generated the node. The UTF-8 offset is recorded because the parser uses
67 UTF-8 internally.
68
69 The constructor of a class :class:`ast.T` parses its arguments as follows:
70
71 * If there are positional arguments, there must be as many as there are items
72 in :attr:`T._fields`; they will be assigned as attributes of these names.
73 * If there are keyword arguments, they will set the attributes of the same
74 names to the given values.
75
76 For example, to create and populate an :class:`ast.UnaryOp` node, you could
77 use ::
78
79 node = ast.UnaryOp()
80 node.op = ast.USub()
Serhiy Storchaka3f228112018-09-27 17:42:37 +030081 node.operand = ast.Constant()
82 node.operand.value = 5
Georg Brandl0c77a822008-06-10 16:37:50 +000083 node.operand.lineno = 0
84 node.operand.col_offset = 0
85 node.lineno = 0
86 node.col_offset = 0
87
88 or the more compact ::
89
Serhiy Storchaka3f228112018-09-27 17:42:37 +030090 node = ast.UnaryOp(ast.USub(), ast.Constant(5, lineno=0, col_offset=0),
Georg Brandl0c77a822008-06-10 16:37:50 +000091 lineno=0, col_offset=0)
92
Serhiy Storchaka3f228112018-09-27 17:42:37 +030093.. deprecated:: 3.8
94
95 Class :class:`ast.Constant` is now used for all constants. Old classes
96 :class:`ast.Num`, :class:`ast.Str`, :class:`ast.Bytes`,
97 :class:`ast.NameConstant` and :class:`ast.Ellipsis` are still available,
98 but they will be removed in future Python releases.
99
Georg Brandl0c77a822008-06-10 16:37:50 +0000100
101.. _abstract-grammar:
102
103Abstract Grammar
104----------------
105
Georg Brandl0c77a822008-06-10 16:37:50 +0000106The abstract grammar is currently defined as follows:
107
108.. literalinclude:: ../../Parser/Python.asdl
Martin Panter1050d2d2016-07-26 11:18:21 +0200109 :language: none
Georg Brandl0c77a822008-06-10 16:37:50 +0000110
111
112:mod:`ast` Helpers
113------------------
114
Martin Panter2e4571a2015-11-14 01:07:43 +0000115Apart from the node classes, the :mod:`ast` module defines these utility functions
Georg Brandl0c77a822008-06-10 16:37:50 +0000116and classes for traversing abstract syntax trees:
117
Terry Reedyfeac6242011-01-24 21:36:03 +0000118.. function:: parse(source, filename='<unknown>', mode='exec')
Georg Brandl0c77a822008-06-10 16:37:50 +0000119
Terry Reedyfeac6242011-01-24 21:36:03 +0000120 Parse the source into an AST node. Equivalent to ``compile(source,
Benjamin Petersonec9199b2008-11-08 17:05:00 +0000121 filename, mode, ast.PyCF_ONLY_AST)``.
Georg Brandl0c77a822008-06-10 16:37:50 +0000122
Brett Cannon7a7f1002018-03-09 12:03:22 -0800123 .. warning::
124 It is possible to crash the Python interpreter with a
125 sufficiently large/complex string due to stack depth limitations
126 in Python's AST compiler.
127
Georg Brandl48310cd2009-01-03 21:18:54 +0000128
Georg Brandl0c77a822008-06-10 16:37:50 +0000129.. function:: literal_eval(node_or_string)
130
Georg Brandlb9b389e2014-11-05 20:20:28 +0100131 Safely evaluate an expression node or a string containing a Python literal or
132 container display. The string or node provided may only consist of the
133 following Python literal structures: strings, bytes, numbers, tuples, lists,
134 dicts, sets, booleans, and ``None``.
Georg Brandl0c77a822008-06-10 16:37:50 +0000135
Georg Brandlb9b389e2014-11-05 20:20:28 +0100136 This can be used for safely evaluating strings containing Python values from
137 untrusted sources without the need to parse the values oneself. It is not
138 capable of evaluating arbitrarily complex expressions, for example involving
139 operators or indexing.
Georg Brandl0c77a822008-06-10 16:37:50 +0000140
Brett Cannon7a7f1002018-03-09 12:03:22 -0800141 .. warning::
142 It is possible to crash the Python interpreter with a
143 sufficiently large/complex string due to stack depth limitations
144 in Python's AST compiler.
145
Georg Brandl492f3fc2010-07-11 09:41:21 +0000146 .. versionchanged:: 3.2
Georg Brandl85f21772010-07-13 06:38:10 +0000147 Now allows bytes and set literals.
Georg Brandl492f3fc2010-07-11 09:41:21 +0000148
Georg Brandl0c77a822008-06-10 16:37:50 +0000149
Amaury Forgeot d'Arcfdfe62d2008-06-17 20:36:03 +0000150.. function:: get_docstring(node, clean=True)
Georg Brandl0c77a822008-06-10 16:37:50 +0000151
152 Return the docstring of the given *node* (which must be a
INADA Naokicb41b272017-02-23 00:31:59 +0900153 :class:`FunctionDef`, :class:`AsyncFunctionDef`, :class:`ClassDef`,
154 or :class:`Module` node), or ``None`` if it has no docstring.
155 If *clean* is true, clean up the docstring's indentation with
156 :func:`inspect.cleandoc`.
157
158 .. versionchanged:: 3.5
159 :class:`AsyncFunctionDef` is now supported.
160
Georg Brandl0c77a822008-06-10 16:37:50 +0000161
162.. function:: fix_missing_locations(node)
163
164 When you compile a node tree with :func:`compile`, the compiler expects
165 :attr:`lineno` and :attr:`col_offset` attributes for every node that supports
166 them. This is rather tedious to fill in for generated nodes, so this helper
167 adds these attributes recursively where not already set, by setting them to
168 the values of the parent node. It works recursively starting at *node*.
169
170
171.. function:: increment_lineno(node, n=1)
172
173 Increment the line number of each node in the tree starting at *node* by *n*.
174 This is useful to "move code" to a different location in a file.
175
176
177.. function:: copy_location(new_node, old_node)
178
179 Copy source location (:attr:`lineno` and :attr:`col_offset`) from *old_node*
180 to *new_node* if possible, and return *new_node*.
181
182
183.. function:: iter_fields(node)
184
185 Yield a tuple of ``(fieldname, value)`` for each field in ``node._fields``
186 that is present on *node*.
187
188
189.. function:: iter_child_nodes(node)
190
191 Yield all direct child nodes of *node*, that is, all fields that are nodes
192 and all items of fields that are lists of nodes.
193
194
195.. function:: walk(node)
196
Georg Brandl619e7ba2011-01-09 07:38:51 +0000197 Recursively yield all descendant nodes in the tree starting at *node*
198 (including *node* itself), in no specified order. This is useful if you only
199 want to modify nodes in place and don't care about the context.
Georg Brandl0c77a822008-06-10 16:37:50 +0000200
201
202.. class:: NodeVisitor()
203
204 A node visitor base class that walks the abstract syntax tree and calls a
205 visitor function for every node found. This function may return a value
Georg Brandl36ab1ef2009-01-03 21:17:04 +0000206 which is forwarded by the :meth:`visit` method.
Georg Brandl0c77a822008-06-10 16:37:50 +0000207
208 This class is meant to be subclassed, with the subclass adding visitor
209 methods.
210
211 .. method:: visit(node)
212
213 Visit a node. The default implementation calls the method called
214 :samp:`self.visit_{classname}` where *classname* is the name of the node
215 class, or :meth:`generic_visit` if that method doesn't exist.
216
217 .. method:: generic_visit(node)
218
219 This visitor calls :meth:`visit` on all children of the node.
Georg Brandl48310cd2009-01-03 21:18:54 +0000220
Georg Brandl0c77a822008-06-10 16:37:50 +0000221 Note that child nodes of nodes that have a custom visitor method won't be
222 visited unless the visitor calls :meth:`generic_visit` or visits them
223 itself.
224
225 Don't use the :class:`NodeVisitor` if you want to apply changes to nodes
226 during traversal. For this a special visitor exists
227 (:class:`NodeTransformer`) that allows modifications.
228
229
230.. class:: NodeTransformer()
231
232 A :class:`NodeVisitor` subclass that walks the abstract syntax tree and
233 allows modification of nodes.
234
Georg Brandl36ab1ef2009-01-03 21:17:04 +0000235 The :class:`NodeTransformer` will walk the AST and use the return value of
236 the visitor methods to replace or remove the old node. If the return value
237 of the visitor method is ``None``, the node will be removed from its
238 location, otherwise it is replaced with the return value. The return value
239 may be the original node in which case no replacement takes place.
Georg Brandl0c77a822008-06-10 16:37:50 +0000240
241 Here is an example transformer that rewrites all occurrences of name lookups
242 (``foo``) to ``data['foo']``::
243
244 class RewriteName(NodeTransformer):
245
246 def visit_Name(self, node):
247 return copy_location(Subscript(
248 value=Name(id='data', ctx=Load()),
Serhiy Storchaka3f228112018-09-27 17:42:37 +0300249 slice=Index(value=Constant(value=node.id)),
Georg Brandl0c77a822008-06-10 16:37:50 +0000250 ctx=node.ctx
251 ), node)
252
253 Keep in mind that if the node you're operating on has child nodes you must
254 either transform the child nodes yourself or call the :meth:`generic_visit`
255 method for the node first.
256
257 For nodes that were part of a collection of statements (that applies to all
258 statement nodes), the visitor may also return a list of nodes rather than
259 just a single node.
260
261 Usually you use the transformer like this::
262
263 node = YourTransformer().visit(node)
264
265
266.. function:: dump(node, annotate_fields=True, include_attributes=False)
267
268 Return a formatted dump of the tree in *node*. This is mainly useful for
269 debugging purposes. The returned string will show the names and the values
270 for fields. This makes the code impossible to evaluate, so if evaluation is
Serhiy Storchakafbc1c262013-11-29 12:17:13 +0200271 wanted *annotate_fields* must be set to ``False``. Attributes such as line
Benjamin Petersondcf97b92008-07-02 17:30:14 +0000272 numbers and column offsets are not dumped by default. If this is wanted,
Georg Brandl0c77a822008-06-10 16:37:50 +0000273 *include_attributes* can be set to ``True``.
Senthil Kumaranf3695bf2016-01-06 21:26:53 -0800274
275.. seealso::
276
Sanyam Khurana338cd832018-01-20 05:55:37 +0530277 `Green Tree Snakes <https://greentreesnakes.readthedocs.io/>`_, an external documentation resource, has good
Senthil Kumaranf3695bf2016-01-06 21:26:53 -0800278 details on working with Python ASTs.