1 # -*- coding: utf-8 -*-
6 The `ast` module helps Python applications to process trees of the Python
7 abstract syntax grammar. The abstract syntax itself might change with
8 each Python release; this module helps to find out programmatically what
9 the current grammar looks like and allows modifications of it.
11 An abstract syntax tree can be generated by passing `ast.PyCF_ONLY_AST` as
12 a flag to the `compile()` builtin function or by using the `parse()`
13 function from this module. The result will be a tree of objects whose
14 classes all inherit from `ast.AST`.
16 A modified abstract syntax tree can be compiled into a Python code object
17 using the built-in `compile()` function.
19 Additionally various helper functions are provided that make working with
20 the trees simpler. The main intention of the helper functions and this
21 module in general is to provide an easy to use interface for libraries
22 that work tightly with the python syntax (template engines for example).
25 :copyright: Copyright 2008 by Armin Ronacher.
26 :license: Python License.
31 def parse(expr
, filename
='<unknown>', mode
='exec'):
33 Parse an expression into an AST node.
34 Equivalent to compile(expr, filename, mode, PyCF_ONLY_AST).
36 return compile(expr
, filename
, mode
, PyCF_ONLY_AST
)
39 def literal_eval(node_or_string
):
41 Safely evaluate an expression node or a string containing a Python
42 expression. The string or node provided may only consist of the following
43 Python literal structures: strings, numbers, tuples, lists, dicts, booleans,
46 _safe_names
= {'None': None, 'True': True, 'False': False}
47 if isinstance(node_or_string
, basestring
):
48 node_or_string
= parse(node_or_string
, mode
='eval')
49 if isinstance(node_or_string
, Expression
):
50 node_or_string
= node_or_string
.body
52 if isinstance(node
, Str
):
54 elif isinstance(node
, Num
):
56 elif isinstance(node
, Tuple
):
57 return tuple(map(_convert
, node
.elts
))
58 elif isinstance(node
, List
):
59 return list(map(_convert
, node
.elts
))
60 elif isinstance(node
, Dict
):
61 return dict((_convert(k
), _convert(v
)) for k
, v
62 in zip(node
.keys
, node
.values
))
63 elif isinstance(node
, Name
):
64 if node
.id in _safe_names
:
65 return _safe_names
[node
.id]
66 raise ValueError('malformed string')
67 return _convert(node_or_string
)
70 def dump(node
, annotate_fields
=True, include_attributes
=False):
72 Return a formatted dump of the tree in *node*. This is mainly useful for
73 debugging purposes. The returned string will show the names and the values
74 for fields. This makes the code impossible to evaluate, so if evaluation is
75 wanted *annotate_fields* must be set to False. Attributes such as line
76 numbers and column offsets are not dumped by default. If this is wanted,
77 *include_attributes* can be set to True.
80 if isinstance(node
, AST
):
81 fields
= [(a
, _format(b
)) for a
, b
in iter_fields(node
)]
82 rv
= '%s(%s' % (node
.__class
__.__name
__, ', '.join(
83 ('%s=%s' % field
for field
in fields
)
84 if annotate_fields
else
85 (b
for a
, b
in fields
)
87 if include_attributes
and node
._attributes
:
88 rv
+= fields
and ', ' or ' '
89 rv
+= ', '.join('%s=%s' % (a
, _format(getattr(node
, a
)))
90 for a
in node
._attributes
)
92 elif isinstance(node
, list):
93 return '[%s]' % ', '.join(_format(x
) for x
in node
)
95 if not isinstance(node
, AST
):
96 raise TypeError('expected AST, got %r' % node
.__class
__.__name
__)
100 def copy_location(new_node
, old_node
):
102 Copy source location (`lineno` and `col_offset` attributes) from
103 *old_node* to *new_node* if possible, and return *new_node*.
105 for attr
in 'lineno', 'col_offset':
106 if attr
in old_node
._attributes
and attr
in new_node
._attributes \
107 and hasattr(old_node
, attr
):
108 setattr(new_node
, attr
, getattr(old_node
, attr
))
112 def fix_missing_locations(node
):
114 When you compile a node tree with compile(), the compiler expects lineno and
115 col_offset attributes for every node that supports them. This is rather
116 tedious to fill in for generated nodes, so this helper adds these attributes
117 recursively where not already set, by setting them to the values of the
118 parent node. It works recursively starting at *node*.
120 def _fix(node
, lineno
, col_offset
):
121 if 'lineno' in node
._attributes
:
122 if not hasattr(node
, 'lineno'):
126 if 'col_offset' in node
._attributes
:
127 if not hasattr(node
, 'col_offset'):
128 node
.col_offset
= col_offset
130 col_offset
= node
.col_offset
131 for child
in iter_child_nodes(node
):
132 _fix(child
, lineno
, col_offset
)
137 def increment_lineno(node
, n
=1):
139 Increment the line number of each node in the tree starting at *node* by *n*.
140 This is useful to "move code" to a different location in a file.
142 if 'lineno' in node
._attributes
:
143 node
.lineno
= getattr(node
, 'lineno', 0) + n
144 for child
in walk(node
):
145 if 'lineno' in child
._attributes
:
146 child
.lineno
= getattr(child
, 'lineno', 0) + n
150 def iter_fields(node
):
152 Yield a tuple of ``(fieldname, value)`` for each field in ``node._fields``
153 that is present on *node*.
155 for field
in node
._fields
:
157 yield field
, getattr(node
, field
)
158 except AttributeError:
162 def iter_child_nodes(node
):
164 Yield all direct child nodes of *node*, that is, all fields that are nodes
165 and all items of fields that are lists of nodes.
167 for name
, field
in iter_fields(node
):
168 if isinstance(field
, AST
):
170 elif isinstance(field
, list):
172 if isinstance(item
, AST
):
176 def get_docstring(node
, clean
=True):
178 Return the docstring for the given node or None if no docstring can
179 be found. If the node provided does not have docstrings a TypeError
182 if not isinstance(node
, (FunctionDef
, ClassDef
, Module
)):
183 raise TypeError("%r can't have docstrings" % node
.__class
__.__name
__)
184 if node
.body
and isinstance(node
.body
[0], Expr
) and \
185 isinstance(node
.body
[0].value
, Str
):
188 return inspect
.cleandoc(node
.body
[0].value
.s
)
189 return node
.body
[0].value
.s
194 Recursively yield all child nodes of *node*, in no specified order. This is
195 useful if you only want to modify nodes in place and don't care about the
198 from collections
import deque
201 node
= todo
.popleft()
202 todo
.extend(iter_child_nodes(node
))
206 class NodeVisitor(object):
208 A node visitor base class that walks the abstract syntax tree and calls a
209 visitor function for every node found. This function may return a value
210 which is forwarded by the `visit` method.
212 This class is meant to be subclassed, with the subclass adding visitor
215 Per default the visitor functions for the nodes are ``'visit_'`` +
216 class name of the node. So a `TryFinally` node visit function would
217 be `visit_TryFinally`. This behavior can be changed by overriding
218 the `visit` method. If no visitor function exists for a node
219 (return value `None`) the `generic_visit` visitor is used instead.
221 Don't use the `NodeVisitor` if you want to apply changes to nodes during
222 traversing. For this a special visitor exists (`NodeTransformer`) that
223 allows modifications.
226 def visit(self
, node
):
228 method
= 'visit_' + node
.__class
__.__name
__
229 visitor
= getattr(self
, method
, self
.generic_visit
)
232 def generic_visit(self
, node
):
233 """Called if no explicit visitor function exists for a node."""
234 for field
, value
in iter_fields(node
):
235 if isinstance(value
, list):
237 if isinstance(item
, AST
):
239 elif isinstance(value
, AST
):
243 class NodeTransformer(NodeVisitor
):
245 A :class:`NodeVisitor` subclass that walks the abstract syntax tree and
246 allows modification of nodes.
248 The `NodeTransformer` will walk the AST and use the return value of the
249 visitor methods to replace or remove the old node. If the return value of
250 the visitor method is ``None``, the node will be removed from its location,
251 otherwise it is replaced with the return value. The return value may be the
252 original node in which case no replacement takes place.
254 Here is an example transformer that rewrites all occurrences of name lookups
255 (``foo``) to ``data['foo']``::
257 class RewriteName(NodeTransformer):
259 def visit_Name(self, node):
260 return copy_location(Subscript(
261 value=Name(id='data', ctx=Load()),
262 slice=Index(value=Str(s=node.id)),
266 Keep in mind that if the node you're operating on has child nodes you must
267 either transform the child nodes yourself or call the :meth:`generic_visit`
268 method for the node first.
270 For nodes that were part of a collection of statements (that applies to all
271 statement nodes), the visitor may also return a list of nodes rather than
274 Usually you use the transformer like this::
276 node = YourTransformer().visit(node)
279 def generic_visit(self
, node
):
280 for field
, old_value
in iter_fields(node
):
281 old_value
= getattr(node
, field
, None)
282 if isinstance(old_value
, list):
284 for value
in old_value
:
285 if isinstance(value
, AST
):
286 value
= self
.visit(value
)
289 elif not isinstance(value
, AST
):
290 new_values
.extend(value
)
292 new_values
.append(value
)
293 old_value
[:] = new_values
294 elif isinstance(old_value
, AST
):
295 new_node
= self
.visit(old_value
)
299 setattr(node
, field
, new_node
)