Skip to content

Instantly share code, notes, and snippets.

@rberenguel
Last active January 8, 2017 17:57
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 rberenguel/1ca186cb98ad87eb84c9b4d0353be802 to your computer and use it in GitHub Desktop.
Save rberenguel/1ca186cb98ad87eb84c9b4d0353be802 to your computer and use it in GitHub Desktop.
Having some quick fun with the ast (and being really impressed by how grumpy (https://github.com/google/grumpy/tree/master/compiler) manages to do it so neatly for python-go, this is a quick hack to play with ast). Enters a simple (almost hardcoded for this example) class, outputs a scala-valid class that you can try on an interpreter.
from __future__ import print_function
import ast
"""
Save the following in test.py, then execute fun_with_ast.py.
You can paste the output in a Scala interpreter
class something(object):
def __init__(self, value1, value2):
self.value1 = value2
self.value2 = value1
def do_it(self):
print self.value1
"""
if __name__ == "__main__":
pyfile = open("test.py").read()
parsed = ast.parse(pyfile)
for child in parsed.body:
if type(child) == ast.ClassDef:
a_class = child
class_name = a_class.name
inherits_from = a_class.bases # ignoring it
init_args = []
for func in a_class.body:
args = [arg.id for arg in func.args.args]
if func.name == "__init__":
init_args = args.remove("self")
init_body = func.body
targets = []
stmts = []
for stmt in init_body:
if type(stmt) == ast.Assign:
if stmt.targets[0].value.id == "self":
targets.append(stmt.targets[0].attr)
stmts.append("var _{} = {}".format(stmt.targets[0].attr, stmt.value.id))
vals = ", ".join(["val {}: Any".format(t) for t in targets])
print("class {}({}){{".format(class_name.capitalize(), vals))
for stmt in stmts:
print(stmt)
else:
args = args.remove("self")
body = func.body
name = func.name
print("def {}() = {{".format(name)) # I know there are no more args here...
for stmt in body:
if type(stmt) == ast.Print:
arg = stmt.values[0].attr
print("println({})".format(arg))
print("}")
print("}")
@rberenguel
Copy link
Author

The AST package for Python seems interesting indeed

@rberenguel
Copy link
Author

Reminder for next time I play with ast: Use NodeVisitor!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment