Skip to content

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
def 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.

  Args:
    node: The AST node to transform - e.g. a module or a function
      definition.
  """
  for field, value in ast.iter_fields(node):
    if isinstance(value, list):
      for lvalue in value:
        if isinstance(lvalue, ast.AST):
          ifize(lvalue)

      xlist = _ifize_stmt_list(value)
      if xlist is not value:
        setattr(node, field, xlist)
    elif isinstance(value, ast.AST):
      ifize(value)

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
def dump(node, indent=None):
  """Returns the string representation of an AST node.

  Args:
    node: The AST node to dump.
    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.

  Returns:
    The dumped AST node.
  """
  if indent is None:
    indent = os.getenv('AST_INDENT')
    if indent is not None:
      indent = int(indent)

  return ast.dump(node, indent=indent)

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
def 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.

  Args:
    node: The AST node to evaluate: a statement or an expression.
    eval_globals: The globals used to evaluate the node.
    eval_locals: The locals used to evaluate the node.
    filename: An optional filename used to compile the node.

  Returns:
    The evaluation result of expression nodes. Statement nodes return
    no value - their effects are applied to the given globals/locals.
  """
  if isinstance(node, ast.stmt):
    mod = ast.Module(body=[node], type_ignores=[])
    cmod = compile(mod, filename=filename or '<ast_eval>', mode='exec')
    # ast_eval exists to execute caller-supplied AST nodes: exec is its
    # documented contract (the expression branch below uses eval likewise).
    exec(cmod, eval_globals, eval_locals)  # noqa: S102
  elif isinstance(node, ast.expr):
    expr = ast.Expression(body=node)
    cexpr = compile(expr, filename=filename or '<ast_eval>', mode='eval')
    value = eval(cexpr, eval_globals, eval_locals)

    return value
  else:
    alog.xraise(ValueError, f'Invalid AST node: {dump(node)}')