Skip to content

Using PyObjects directly

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

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 callable PyObject

  • .toString() calls the Python builtin str() and returns a JavaScript string

  • .id contains an unique identifier that is generally the same as the Python id()

  • A PyObject referencing a Python iterable can be iterated from JavaScript

    let 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)