Tutorial for PScript - Python to JavaScript transpilation


In [1]:
from pscript import py2js, evalpy

We can transpile strings of Python code:


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


var _pyfunc_range = function (start, end, step) {
var i, res = [];
    var val = start;
    var n = (end - start) / step;
    for (i=0; i<n; i++) {
        res.push(val);
        val += step;
    }
    return res;
};
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 _pyfunc_range = function (start, end, step) {
var i, res = [];
    var val = start;
    var n = (end - start) / step;
    for (i=0; i<n; i++) {
        res.push(val);
        val += step;
    }
    return res;
};
var _pymeth_append = function (x) { // nargs: 1
    if (!Array.isArray(this)) return this.append.apply(this, arguments);
    this.push(x);
};
var foo;
foo = function flx_foo (x) {
    var i, res;
    res = [];
    for (i = 0; i < x; i += 1) {
        _pymeth_append.call(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 _pyfunc_range = function (start, end, step) {
var i, res = [];
    var val = start;
    var n = (end - start) / step;
    for (i=0; i<n; i++) {
        res.push(val);
        val += step;
    }
    return res;
};
var foo;
foo = function flx_foo (x) {
    return (function list_comprehension (iter0) {var res = [];var i, i0;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;}).call(this, _pyfunc_range(0, x, 1));
};

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(3 + 4)')


Out[6]:
'7'

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


Out[7]:
'null'

In [ ]: