Skip to content

Instantly share code, notes, and snippets.

@cessor
Created January 16, 2020 18:45
Show Gist options
  • Save cessor/6761a3e6e4a256cd554dc80e556cb443 to your computer and use it in GitHub Desktop.
Save cessor/6761a3e6e4a256cd554dc80e556cb443 to your computer and use it in GitHub Desktop.
obast.py
import ast
ast = ast.parse('a = (1 + 2)\n', filename='<string>', mode='single')
statement, *_ = ast.body
def walk(node, field='', depth=0):
indent = depth * ' '
name = node.__class__.__name__
if isinstance(node, list):
for n in node:
walk(n, field, depth)
return
if hasattr(node, '_fields'):
print(f'{indent}{field}:{name}')
for field in node._fields:
child = getattr(node, field)
walk(child, field, depth + 1)
return
print(f'{indent}{field}:{node}')
walk(statement, 'Statement')
Statement:Assign
targets:Name
id:a
ctx:Store
value:BinOp
left:Num
n:1
op:Add
right:Num
n:2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment