Skip to content

Inline Python

Momtchil Momtchev edited this page Nov 23, 2022 · 2 revisions

Inline Python is supported through pyval which uses Python eval.

pyval can be used to create any value that is not easily expressed in JavaScript:

const memviewSlice = pyval('memoryview(b'123')[::2]');

Every Python expression can be used in pyval - note that eval expects a Python expression and not a Python statement:

// fn is a PyObject
const fn = pyval('lambda x: (x + 42)');

assert.isTrue(fn.callable);
assert.strictEqual(fn.call(-42).toJS(), 0);

// with eval arguments
// (this is not a real closure as Python still does not
// have access to the JS objects - this will produce a
// Python copy of the variable x)
const array = pyval('list([1, x, 3])', { x: 4 });
assert.instanceOf(array, PyObject);
assert.deepEqual(array.toJS(), [1, 4, 3]);

// The same with a PyObject
// In this case the expression is a real closure
// x will be passed by reference in the globals of the lambda
const x = PyObject.fromJS(4);
const lambda = pyval('lambda y: (y + x)', { x });
assert.strictEqual(lambda.call(-4).toJS(), 0);

// Modules can be passed too
const np = pymport('numpy');
const py_array = pyval('np.array([2, 1, 0]).tolist()', { np });
assert.deepEqual(py_array.toJS(), [2, 1, 0]);

pyval runs the whole Python compiler chain and it is an expensive function.

[New in 1.2] When imported from pymport/proxified pyval will automatically return profixied objects.