Node.js library that enables seamless integration of Python libraries into JavaScript applications
—
Quality
Pending
Does it follow best practices?
Impact
Pending
No eval scenarios have been run
Complete PyObject class providing JavaScript interface to Python objects, with methods for property access, method calls, type conversion, and iteration.
Read-only properties that provide metadata about the wrapped Python object.
/**
* Numeric identifier of the Python object, equivalent to Python id()
*/
readonly id: number;
/**
* Whether the Python object is callable (function, method, class, etc.)
*/
readonly callable: boolean;
/**
* String representation of the Python object's type
*/
readonly type: string;
/**
* Length of the object if it supports len(), undefined otherwise
*/
readonly length: number | undefined;
/**
* The Python type/constructor of the object, equivalent to type(obj)
*/
readonly constr: PyObject;Access Python object attributes and check for their existence.
/**
* Get a property from the Python object
* @param name - Property name to retrieve
* @returns PyObject representing the property value
*/
get(name: string): PyObject;
/**
* Check if a property exists on the Python object
* @param name - Property name to check (for sets, can be any value)
* @returns True if the property exists
*/
has(name: string | any): boolean;Usage Examples:
const sys = pymport('sys');
// Get properties
const version = sys.get('version');
const path = sys.get('path');
// Check if properties exist
console.log(sys.has('version')); // true
console.log(sys.has('nonexistent')); // false
// For sets, check membership
const pySet = PyObject.set([1, 2, 3]);
console.log(pySet.has(2)); // true
console.log(pySet.has(5)); // falseAccess Python object elements by index or key, equivalent to Python's subscript operator [].
/**
* Retrieve an element by index or key
* @param index - Index, key, or slice for element access
* @returns PyObject representing the accessed element
*/
item(index: any): PyObject;Usage Examples:
const np = proxify(pymport('numpy'));
// Array indexing
const arr = np.array([1, 2, 3, 4, 5]);
console.log(arr.item(0).toJS()); // 1
console.log(arr.item(-1).toJS()); // 5
// Dictionary key access
const pyDict = PyObject.dict({ a: 1, b: 2 });
console.log(pyDict.item('a').toJS()); // 1
// Slice access
const slice = PyObject.slice([1, 4, 1]); // start=1, stop=4, step=1
const subarray = arr.item(slice);
console.log(subarray.toJS()); // [2, 3, 4]Call Python functions and methods with automatic argument conversion.
/**
* Call a callable PyObject synchronously
* @param args - Arguments to pass to the Python function
* @returns PyObject result of the function call
* @throws Error if the object is not callable
*/
call(...args: any[]): PyObject;
/**
* Call a callable PyObject asynchronously
* @param args - Arguments to pass to the Python function
* @returns Promise resolving to PyObject result
* @throws Promise rejection if the object is not callable
*/
callAsync(...args: any[]): Promise<PyObject>;Usage Examples:
const np = proxify(pymport('numpy'));
// Synchronous function calls
const array = np.array.call([1, 2, 3, 4]);
const sum = np.sum.call(array);
// Asynchronous function calls (useful for long-running operations)
const largeArray = np.random.random.call([1000, 1000]);
const asyncSum = await np.sum.callAsync(largeArray);
// Method calls on objects
const reshaped = array.get('reshape').call(2, 2);Execute code within Python context managers (with statements).
/**
* Execute a function within the context of this PyObject
* Equivalent to Python's 'with' statement
* @param fn - Function to execute with the context object
* @returns Result of the function execution
*/
with<T>(fn: (v: PyObject) => T): T;Usage Examples:
// File handling with context management
const builtins = pymport('builtins');
const open = builtins.get('open');
const file = open.call('example.txt', 'w');
file.with((f) => {
f.get('write').call('Hello, Python from Node.js!');
// File automatically closed when context exits
});
// Custom context managers
const contextManager = pyval('some_context_manager()');
const result = contextManager.with((ctx) => {
// Use the context object
return ctx.get('some_method').call();
});Convert PyObjects to JavaScript values and vice versa.
/**
* Convert PyObject to JavaScript value with configurable options
* @param opts - Conversion options
* @param opts.depth - Maximum recursion depth (undefined for unlimited)
* @param opts.buffer - Whether to convert buffer protocol objects
* @returns JavaScript representation of the Python object
*/
toJS(opts?: { depth?: number; buffer?: boolean; }): any;
/**
* Convert PyObject to JavaScript value (equivalent to toJS())
* @returns JavaScript representation of the Python object
*/
valueOf(): any;
/**
* Get string representation using Python's str() function
* @returns String representation of the object
*/
toString(): string;Usage Examples:
const np = proxify(pymport('numpy'));
// Basic conversion
const pyArray = np.array([1, 2, 3]);
const jsArray = pyArray.toJS();
console.log(jsArray); // [1, 2, 3]
// Controlled depth conversion
const nested = np.array([[1, 2], [3, 4]]);
const shallow = nested.toJS({ depth: 1 }); // Keep inner arrays as PyObjects
const deep = nested.toJS(); // Convert everything to JS
// String representation
console.log(pyArray.toString()); // "[1 2 3]"Iterate over Python objects that support iteration.
/**
* Return an iterator over the object's elements
* Works with any Python iterable (lists, tuples, strings, etc.)
*/
[Symbol.iterator](): Iterator<PyObject>;
/**
* Map function over iterable PyObject elements
* @param callback - Function to call for each element
* @param thisArg - Optional 'this' context for the callback
* @returns Array of mapped results
*/
map<T, U>(
callback: (this: U, element: PyObject, index: number, iterable: PyObject) => T,
thisArg?: U
): T[];Usage Examples:
const pyList = PyObject.list([1, 2, 3, 4, 5]);
// For-of iteration
for (const item of pyList) {
console.log(item.toJS());
}
// Map over elements
const doubled = pyList.map((item, index) => item.toJS() * 2);
console.log(doubled); // [2, 4, 6, 8, 10]
// String iteration
const pyString = PyObject.string('hello');
const chars = [...pyString].map(char => char.toString());
console.log(chars); // ['h', 'e', 'l', 'l', 'o']Utility methods for working with Python dictionaries.
/**
* Get dictionary keys as a Python list
* @param obj - Dictionary PyObject
* @returns PyObject list of keys
*/
static keys(obj: PyObject): PyObject;
/**
* Get dictionary values as a Python list
* @param obj - Dictionary PyObject
* @returns PyObject list of values
*/
static values(obj: PyObject): PyObject;Usage Examples:
const pyDict = PyObject.dict({ a: 1, b: 2, c: 3 });
// Get keys and values
const keys = PyObject.keys(pyDict);
const values = PyObject.values(pyDict);
console.log(keys.toJS()); // ['a', 'b', 'c']
console.log(values.toJS()); // [1, 2, 3]
// Iterate over dictionary items
for (const key of keys) {
const value = pyDict.item(key.toString());
console.log(`${key.toString()}: ${value.toJS()}`);
}Install with Tessl CLI
npx tessl i tessl/npm-pymport