Create a gist now

Instantly share code, notes, and snippets.

@madhadron /py2js.py Secret
Created Aug 6, 2012

Example of Python to JavaScript
import inspect
import ast
def ast_of(f):
lines, count = inspect.getsourcelines(f)
source = ''.join(lines)
a = ast.parse(source)
return a
def genjs(node):
f = globals()['_' + node.__class__.__name__]
return f(node)
def _FunctionDef(node):
print node._fields
arglist = ', '.join(genjs(arg) for arg in node.args.args)
s = 'var ' + node.name + '=function(' + arglist + ') {\n' + '\n'.join(genjs(stmt) for stmt in node.body) + '\n};'
return s
def _Module(node):
return '\n\n'.join(genjs(stmt) for stmt in node.body)
def _Assign(node):
return 'var ' + genjs(node.targets[0]) + '=' + genjs(node.value) + ';'
def _Num(node):
return str(node.n)
def _BinOp(node):
return genjs(node.left) + genjs(node.op) + genjs(node.right)
def _Add(node):
return '+'
def _Return(node):
return 'return ' + genjs(node.value) + ';'
def _Name(node):
return node.id
def f(a,b):
a = 3
b = a+5
return a+b
print genjs(ast_of(f))
# Prints:
# var f=function(a, b) {
# var a=3;
# var b=a+5;
# return a+b;
# };
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment