Skip to content

Instantly share code, notes, and snippets.

@s-hiiragi
Created April 16, 2018 17:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save s-hiiragi/5a169bd2c41d1b6156a920910f683e11 to your computer and use it in GitHub Desktop.
Save s-hiiragi/5a169bd2c41d1b6156a920910f683e11 to your computer and use it in GitHub Desktop.
ast practice 1
import ast
source = """
name = "Inu"
age = 10
print("Hello, {}({})!".format(name, age))
"""
tree = ast.parse(source)
def print_ast(node, level=0, prefixes="", is_last=True):
if level >= 1:
prefix = " `-- " if is_last else " |-- "
else:
prefix = ""
class_name = node.__class__.__name__
fields = []
for n, v in ast.iter_fields(node):
if isinstance(v, str):
fields.append('{}="{}"'.format(n, v))
elif isinstance(v, int):
fields.append("{}={}".format(n, v))
else:
fields.append("{}".format(n))
field_string = ", ".join(fields)
print("{}{}{} ({})".format(prefixes, prefix, class_name, field_string))
children = tuple(ast.iter_child_nodes(node))
l = len(children)
if level >= 1:
prefixes += " " if is_last else " | "
for i, n in enumerate(children):
print_ast(n, level + 1, prefixes, i + 1 == l)
print_ast(tree)
"""==>
Module (body, docstring)
|-- Assign (targets, value)
| |-- Name (id="name", ctx)
| | `-- Store ()
| `-- Str (s="Inu")
|-- Assign (targets, value)
| |-- Name (id="age", ctx)
| | `-- Store ()
| `-- Num (n=10)
`-- Expr (value)
`-- Call (func, args, keywords)
|-- Name (id="print", ctx)
| `-- Load ()
`-- Call (func, args, keywords)
|-- Attribute (value, attr="format", ctx)
| |-- Str (s="Hello, {}({})!")
| `-- Load ()
|-- Name (id="name", ctx)
| `-- Load ()
`-- Name (id="age", ctx)
`-- Load ()
"""
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment