ast_utils¶
AST manipulation helpers.
This module provides helpers to manipulate Python ASTs: ifize() moves statements following an IF into the IF branch not ending with a return - making control flow linear for code generators - plus an AST dump utility honoring an environment-driven indentation and a static AST evaluator executing statements/expressions.
Example
import ast
from py_misc_utils import ast_utils as au
tree = ast.parse('a + b', mode='eval')
assert 'BinOp' in au.dump(tree, indent=2)
# Statements execute into the given namespaces...
node = ast.parse('res = a + b').body[0]
locs = dict()
au.static_eval(node, dict(a=1, b=2), locs)
assert locs['res'] == 3
# ...and expressions evaluate to their value.
v = au.static_eval(ast.parse('a * b', mode='eval').body, dict(a=3, b=4), {})
assert v == 12
ifize(node)
¶
Normalizes an AST so that each IF terminates its statement list.
Recursively rearranges all the statement lists held by an AST, applying the _ifize_stmt_list() transformation. The transformation mutates the AST in place and returns None.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
node
|
The AST node to transform - e.g. a module or a function definition. |
required |
Source code in py_misc_utils/ast_utils.py
118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 | |
dump(node, indent=None)
¶
Returns the string representation of an AST node.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
node
|
The AST node to dump. |
required | |
indent
|
An optional indentation of the dumped fields. If None, the AST_INDENT environment variable is used - if set - and the one-line ast.dump() representation otherwise. |
None
|
Returns:
| Type | Description |
|---|---|
|
The dumped AST node. |
Source code in py_misc_utils/ast_utils.py
142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 | |
static_eval(node, eval_globals, eval_locals, filename=None)
¶
Evaluates an AST statement or expression.
Note that this is not a sandbox: the node is compiled and executed, so arbitrary code can run.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
node
|
The AST node to evaluate: a statement or an expression. |
required | |
eval_globals
|
The globals used to evaluate the node. |
required | |
eval_locals
|
The locals used to evaluate the node. |
required | |
filename
|
An optional filename used to compile the node. |
None
|
Returns:
| Type | Description |
|---|---|
|
The evaluation result of expression nodes. Statement nodes return |
|
|
no value - their effects are applied to the given globals/locals. |
Source code in py_misc_utils/ast_utils.py
162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 | |