Tutorial for flexx.pyscript - Python to JavaScript transpilation


In [1]:
from flexx.pyscript import py2js, evalpy

We can transpile strings of Python code:


In [2]:
js = py2js('for i in range(10): print(i)')
print(js)


var i;
for (i = 0; i < 10; i += 1) {
    console.log(i);
}

Or actual Python functions:


In [3]:
def foo(x):
    res = []
    for i in range(x):
        res.append(i**2)
    return res
js = py2js(foo)
print(js)


var foo;
foo = function (x) {
    var i, res;
    res = [];
    for (i = 0; i < x; i += 1) {
        (res.append || res.push).apply(res, [Math.pow(i, 2)]);
    }
    return res;
};

Let's try that again, but now with a list comprehension. (The JS is valid and will run fine, though its less readable.)


In [4]:
def foo(x):
    return [i**2 for i in range(x)]
js = py2js(foo)
print(js)


var foo;
foo = function (x) {
    return (function list_comprehenson () {var res = [];var i, iter0, i0;iter0 = (function (start, end, step) {var i, res = []; for (i=start; i<end; i+=step) {res.push(i);} return res;})(0, x, 1);if ((typeof iter0 === "object") && (!Array.isArray(iter0))) {iter0 = Object.keys(iter0);}for (i0=0; i0<iter0.length; i0++) {i = iter0[i0];{res.push(Math.pow(i, 2));}}return res;})();
};

Classes are also supported, but not in the notebook (apparently Python cannot retrieve the source code in this case).


In [5]:
class Bar:
    def spam(self):
        return 3 + 4
#js = py2js(Bar)
# This only works if Bar is defined in an actual module.

Using evalpy you can evaluate Python code in NodeJS:


In [6]:
evalpy('print(None)')


Out[6]:
'null'