Skip to content

Using PyObjects directly

Momtchil Momtchev edited this page Nov 21, 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
  • .toString() calls the Python builtin str() and returns a JavaScript string
  • 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
  • Refer to Python specific features for how to express Python-specific features absent from JavaScript such as operator overloading, slices and using objects as subscript indices.