Last active
January 8, 2017 17:57
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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("}") |
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
The AST package for Python seems interesting indeed