Conversion from JavaScript to Python code?

Conversion from JavaScript to Python code?

You can translate JavaScript to Python using Js2Py. It supports whole JavaScript and you can use it to translate large JavaScript modules like esprima.js (a JavaScript 6 parser).

Short demo:

>>> import js2py
>>> f = js2py.eval_js( function $(a) {return a + arguments[1]} )
>>> f
function $(a) { [python code] }
>>> f(1, 2, 3)

This is how the translated function looks like internally (its rather ugly):

>>> print js2py.translate_js( function $(a) {return a + arguments[1]} )
from js2py.pyjs import *
var = Scope( JS_BUILTINS )
# Code follows:
def PyJsHoistedNonPyName(a, this, arguments, var=var):
    var = Scope({ua:a, uthis:this, uarguments:arguments}, var)
    return (var.get(ua)+var.get(uarguments).get(u1))
PyJsHoistedNonPyName.func_name = u$
var.put(u$, PyJsHoistedNonPyName)


Now several (4) years later this (almost certainly) can be done; though certainly not with RegEx.
I suggest future readers look to @Piotr Dabkowskis answer..
Or some of the other answers. (I dont know having not tried them)

Original Answer

Hm this is a hard one.
The definition of a compiler is translates from a higher level language to a lower level language.
eg python to machine-code.
or java to javascript (google has a rather famous compiler for this somewhere – its what makes google doc easier to make)
Python to javascript compilers abound.
technically javascript to python would be a decompiler. (afaik)

I found some speculation about a javascript-python converter here: follow the tread through. it mostly speaks of how it wouldnt be too hard to do.
I cant find anything , but that doesnt mean its no out there.

Regex is not suitable, regex is suitable only for regular languages.
programming languages are not normally regular languages. see this

Conversion from JavaScript to Python code?

This answer might be about 2 years late but how about js -> CoffeeScript -> python? If you use something like to convert to cs, then things like indentation and lists are already done for you.

Related posts:

Leave a Reply

Your email address will not be published. Required fields are marked *