-
-
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 -
.toString()
calls the Python builtinstr()
and returns a JavaScript string -
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.
Momtchil Momtchev momtchil@momtchev.com, 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.