-
-
Notifications
You must be signed in to change notification settings - Fork 8
Using PyObjects directly
A PyObject
can be used from JavaScript as follows:
for a slightly more readable interface that omits the .get()
/.call()
part at a small performance cost refer to Using proxified PyObjects
import { pymport } from 'pymport';
// Python: import numpy as np
// np is a PyObject
const np = pymport('numpy');
// Python: a = np.arange(15).reshape(3, 5)
// a is a PyObject
const a = np.get('arange').call(15).get('reshape').call(3, 5);
// Python: a = np.ones((2, 3), dtype=int16)
// np.get('int16') is a PyObject
// (if the last argument is a plain JS object, it is considered a kwargs argument)
const b = np.get('ones').call([2, 3], { dtype: np.get('int16') });
// Python: print(a.tolist())
// PyObject.toJS() converts to JS
console.log(a.get('tolist').call().toJS());
A PyObject
can be used directly by calling
-
.toJS()
returns a native JavaScript copy - see the section on conversions for more details -
.get()
to use the Python member operator.
-
.call()
to invoke a Python callable -
.item()
to use the Python subscript operator[]
-
.length
is defined for Python iterables -
.type
contains the Python type -
.callable
indicates if the object is callable (ie it is a function) -
.constr
returns the Python constructor, a callablePyObject
-
.toString()
calls the Python builtinstr()
and returns a JavaScript string -
.id
contains an unique identifier that is generally the same as the Pythonid()
-
A
PyObject
referencing a Python iterable can be iterated from JavaScriptlet sum = 0; const list = PyObject.list([8, 9, 3]); for (const i of list) { sum += +i; } // i is a PyObject, +i is a number
-
Refer to Python specific features for how to express Python-specific features absent from JavaScript such as operator overloading, lvalues, slices and using objects as subscript indices.
The can be only one PyObject
for one Python object. This means that these tests works as expected:
const a = np.get('ones').call([2, 3]);
assert.isTrue(a.constr == np.get('ndarray'))
or with proxified objects:
const a = np.ones([2, 3]);
assert.isTrue(a.constr == np.ndarray)
Momtchil Momtchev [email protected], 2022
This project is created and maintained as a free service to the open source community and to remain as a constant life-time remainder to the OpenJS foundation about backing up an extortion linked to corruption in French Judicial system over a sexually-motivated affair.