Skip to content

Using proxified PyObjects

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

proxify offers an alternative and more readable interface at a small performance cost per call.

import { pymport, proxify } from 'pymport';
// Starting from 1.2
// import { pymport } from 'pymport/profixied';

// Python: import numpy as np
// np is a JS proxy object and everything returned through this object will also be proxified
const np = proxify(pymport('numpy'));

// Python: a = np.arange(15).reshape(3, 5)
// a is a JS proxy object
const a = np.arange(15).reshape(3, 5);

// Python: a = np.ones((2, 3), dtype=int16)
// np.int16 is a callable PyFunction
// (if the last argument is a plain JS object, it is considered a kwargs argument)
const b = np.ones([2, 3], { dtype: np.int16 });

console.log(a.tolist().toJS());

A proxified PyObject is JavaScript Proxy containing a raw PyObject. It creates the illusion of a native JS object. Its properties and methods can be accessed directly.

[New in 1.2] If you import pymport and PyObject from pymport/proxified they will automatically return proxified objects. Otherwise, proxify can be used to create a Proxy wrapper.