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.
29 from _ast
import __version__
32 def parse(expr
, filename
='<unknown>', mode
='exec'):
34 Parse an expression into an AST node.
35 Equivalent to compile(expr, filename, mode, PyCF_ONLY_AST).
37 return compile(expr
, filename
, mode
, PyCF_ONLY_AST
)
40 def literal_eval(node_or_string
):
42 Safely evaluate an expression node or a string containing a Python
43 expression. The string or node provided may only consist of the following
44 Python literal structures: strings, numbers, tuples, lists, dicts, booleans,
47 _safe_names
= {'None': None, 'True': True, 'False': False}
48 if isinstance(node_or_string
, basestring
):
49 node_or_string
= parse(node_or_string
, mode
='eval')
50 if isinstance(node_or_string
, Expression
):
51 node_or_string
= node_or_string
.body
53 if isinstance(node
, Str
):
55 elif isinstance(node
, Num
):
57 elif isinstance(node
, Tuple
):
58 return tuple(map(_convert
, node
.elts
))
59 elif isinstance(node
, List
):
60 return list(map(_convert
, node
.elts
))
61 elif isinstance(node
, Dict
):
62 return dict((_convert(k
), _convert(v
)) for k
, v
63 in zip(node
.keys
, node
.values
))
64 elif isinstance(node
, Name
):
65 if node
.id in _safe_names
:
66 return _safe_names
[node
.id]
67 raise ValueError('malformed string')
68 return _convert(node_or_string
)
71 def dump(node
, annotate_fields
=True, include_attributes
=False):
73 Return a formatted dump of the tree in *node*. This is mainly useful for
74 debugging purposes. The returned string will show the names and the values
75 for fields. This makes the code impossible to evaluate, so if evaluation is
76 wanted *annotate_fields* must be set to False. Attributes such as line
77 numbers and column offsets are not dumped by default. If this is wanted,
78 *include_attributes* can be set to True.
81 if isinstance(node
, AST
):
82 fields
= [(a
, _format(b
)) for a
, b
in iter_fields(node
)]
83 rv
= '%s(%s' % (node
.__class
__.__name
__, ', '.join(
84 ('%s=%s' % field
for field
in fields
)
85 if annotate_fields
else
86 (b
for a
, b
in fields
)
88 if include_attributes
and node
._attributes
:
89 rv
+= fields
and ', ' or ' '
90 rv
+= ', '.join('%s=%s' % (a
, _format(getattr(node
, a
)))
91 for a
in node
._attributes
)
93 elif isinstance(node
, list):
94 return '[%s]' % ', '.join(_format(x
) for x
in node
)
96 if not isinstance(node
, AST
):
97 raise TypeError('expected AST, got %r' % node
.__class
__.__name
__)
101 def copy_location(new_node
, old_node
):
103 Copy source location (`lineno` and `col_offset` attributes) from
104 *old_node* to *new_node* if possible, and return *new_node*.
106 for attr
in 'lineno', 'col_offset':
107 if attr
in old_node
._attributes
and attr
in new_node
._attributes \
108 and hasattr(old_node
, attr
):
109 setattr(new_node
, attr
, getattr(old_node
, attr
))
113 def fix_missing_locations(node
):
115 When you compile a node tree with compile(), the compiler expects lineno and
116 col_offset attributes for every node that supports them. This is rather
117 tedious to fill in for generated nodes, so this helper adds these attributes
118 recursively where not already set, by setting them to the values of the
119 parent node. It works recursively starting at *node*.
121 def _fix(node
, lineno
, col_offset
):
122 if 'lineno' in node
._attributes
:
123 if not hasattr(node
, 'lineno'):
127 if 'col_offset' in node
._attributes
:
128 if not hasattr(node
, 'col_offset'):
129 node
.col_offset
= col_offset
131 col_offset
= node
.col_offset
132 for child
in iter_child_nodes(node
):
133 _fix(child
, lineno
, col_offset
)
138 def increment_lineno(node
, n
=1):
140 Increment the line number of each node in the tree starting at *node* by *n*.
141 This is useful to "move code" to a different location in a file.
143 if 'lineno' in node
._attributes
:
144 node
.lineno
= getattr(node
, 'lineno', 0) + n
145 for child
in walk(node
):
146 if 'lineno' in child
._attributes
:
147 child
.lineno
= getattr(child
, 'lineno', 0) + n
151 def iter_fields(node
):
153 Yield a tuple of ``(fieldname, value)`` for each field in ``node._fields``
154 that is present on *node*.
156 for field
in node
._fields
:
158 yield field
, getattr(node
, field
)
159 except AttributeError:
163 def iter_child_nodes(node
):
165 Yield all direct child nodes of *node*, that is, all fields that are nodes
166 and all items of fields that are lists of nodes.
168 for name
, field
in iter_fields(node
):
169 if isinstance(field
, AST
):
171 elif isinstance(field
, list):
173 if isinstance(item
, AST
):
177 def get_docstring(node
, clean
=True):
179 Return the docstring for the given node or None if no docstring can
180 be found. If the node provided does not have docstrings a TypeError
183 if not isinstance(node
, (FunctionDef
, ClassDef
, Module
)):
184 raise TypeError("%r can't have docstrings" % node
.__class
__.__name
__)
185 if node
.body
and isinstance(node
.body
[0], Expr
) and \
186 isinstance(node
.body
[0].value
, Str
):
189 return inspect
.cleandoc(node
.body
[0].value
.s
)
190 return node
.body
[0].value
.s
195 Recursively yield all child nodes of *node*, in no specified order. This is
196 useful if you only want to modify nodes in place and don't care about the
199 from collections
import deque
202 node
= todo
.popleft()
203 todo
.extend(iter_child_nodes(node
))
207 class NodeVisitor(object):
209 A node visitor base class that walks the abstract syntax tree and calls a
210 visitor function for every node found. This function may return a value
211 which is forwarded by the `visit` method.
213 This class is meant to be subclassed, with the subclass adding visitor
216 Per default the visitor functions for the nodes are ``'visit_'`` +
217 class name of the node. So a `TryFinally` node visit function would
218 be `visit_TryFinally`. This behavior can be changed by overriding
219 the `visit` method. If no visitor function exists for a node
220 (return value `None`) the `generic_visit` visitor is used instead.
222 Don't use the `NodeVisitor` if you want to apply changes to nodes during
223 traversing. For this a special visitor exists (`NodeTransformer`) that
224 allows modifications.
227 def visit(self
, node
):
229 method
= 'visit_' + node
.__class
__.__name
__
230 visitor
= getattr(self
, method
, self
.generic_visit
)
233 def generic_visit(self
, node
):
234 """Called if no explicit visitor function exists for a node."""
235 for field
, value
in iter_fields(node
):
236 if isinstance(value
, list):
238 if isinstance(item
, AST
):
240 elif isinstance(value
, AST
):
244 class NodeTransformer(NodeVisitor
):
246 A :class:`NodeVisitor` subclass that walks the abstract syntax tree and
247 allows modification of nodes.
249 The `NodeTransformer` will walk the AST and use the return value of the
250 visitor methods to replace or remove the old node. If the return value of
251 the visitor method is ``None``, the node will be removed from its location,
252 otherwise it is replaced with the return value. The return value may be the
253 original node in which case no replacement takes place.
255 Here is an example transformer that rewrites all occurrences of name lookups
256 (``foo``) to ``data['foo']``::
258 class RewriteName(NodeTransformer):
260 def visit_Name(self, node):
261 return copy_location(Subscript(
262 value=Name(id='data', ctx=Load()),
263 slice=Index(value=Str(s=node.id)),
267 Keep in mind that if the node you're operating on has child nodes you must
268 either transform the child nodes yourself or call the :meth:`generic_visit`
269 method for the node first.
271 For nodes that were part of a collection of statements (that applies to all
272 statement nodes), the visitor may also return a list of nodes rather than
275 Usually you use the transformer like this::
277 node = YourTransformer().visit(node)
280 def generic_visit(self
, node
):
281 for field
, old_value
in iter_fields(node
):
282 old_value
= getattr(node
, field
, None)
283 if isinstance(old_value
, list):
285 for value
in old_value
:
286 if isinstance(value
, AST
):
287 value
= self
.visit(value
)
290 elif not isinstance(value
, AST
):
291 new_values
.extend(value
)
293 new_values
.append(value
)
294 old_value
[:] = new_values
295 elif isinstance(old_value
, AST
):
296 new_node
= self
.visit(old_value
)
300 setattr(node
, field
, new_node
)