JavaScript API#

Backward compatibility of the API is not guaranteed at this point.

Globals#

Functions:

async loadPyodide(options)

Load the main Pyodide wasm module and initialize it.

async globalThis.loadPyodide(options)#

Load the main Pyodide wasm module and initialize it.

Arguments:
  • options.args (string[]) – Command line arguments to pass to Python on startup. See Python command line interface options for more details. Default: []

  • options.fullStdLib (boolean) – Load the full Python standard library. Setting this to false excludes unvendored modules from the standard library. Default: false

  • options.homedir (string) – The home directory which Pyodide will use inside virtual file system. Default: "/home/pyodide"

  • options.indexURL (string) – The URL from which Pyodide will load the main Pyodide runtime and packages. It is recommended that you leave this unchanged, providing an incorrect value can cause broken behavior. Default: The url that Pyodide is loaded from with the file name (pyodide.js or pyodide.mjs) removed.

  • options.jsglobals (object) – The object that Pyodide will use for the js module. Default: globalThis

  • options.lockFileURL (string) – The URL from which Pyodide will load the Pyodide repodata.json lock file. You can produce custom lock files with micropip.freeze(). Default: `${indexURL}/repodata.json`

  • options.stdLibURL (string) – The URL from which to load the standard library python_stdlib.zip file. This URL includes the most of the Python stadard library. Some stdlib modules were unvendored, and can be loaded separately with fullStdLib=true option or by their package name. Default: `${indexURL}/python_stdlib.zip`

  • options.stderr ((msg: string) => void) – Override the standard error output callback.

  • options.stdin (() => string) – Override the standard input callback. Should ask the user for one line of input.

  • options.stdout ((msg: string) => void) – Override the standard output callback.

Returns:

Promise<PyodideInterface> – The pyodide module.

pyodide#

Attributes:

ERRNO_CODES

A map from posix error names to error codes.

FS

An alias to the Emscripten File System API.

PATH

An alias to the Emscripten Path API.

canvas

This provides APIs to set a canvas for rendering graphics.

ffi

See pyodide.ffi

globals

An alias to the global Python namespace.

loadedPackages

The list of packages that Pyodide has loaded.

pyodide_py

An alias to the Python pyodide package.

version

The Pyodide version.

Functions:

checkInterrupt()

Throws a KeyboardInterrupt error if a KeyboardInterrupt has been requested via the interrupt buffer.

isPyProxy(jsobj)

Is jsobj a PyProxy?

async loadPackage(names, options)

Load packages from the Pyodide distribution or Python wheels by URL.

async loadPackagesFromImports(code, options)

Inspect a Python code chunk and use pyodide.loadPackage() to install any known packages that the code chunk imports.

async mountNativeFS(path, fileSystemHandle)

Mounts a FileSystemDirectoryHandle into the target directory.

pyimport(mod_name)

Imports a module and returns it.

registerComlink(Comlink)

Tell Pyodide about Comlink.

registerJsModule(name, module)

Registers the JavaScript object module as a JavaScript module named name.

runPython(code, options)

Runs a string of Python code from JavaScript, using eval_code() to evaluate the code.

async runPythonAsync(code, options)

Run a Python code string with top level await using eval_code_async() to evaluate the code.

setInterruptBuffer(interrupt_buffer)

Sets the interrupt buffer to be interrupt_buffer.

setStderr(options)

Sets the standard error handler.

setStdin(options)

Set a stdin handler.

setStdout(options)

Sets the standard out handler.

toPy(obj, options)

Convert a JavaScript object to a Python object as best as possible.

unpackArchive(buffer, format, options)

Unpack an archive into a target directory.

unregisterJsModule(name)

Unregisters a JavaScript module with given name that has been previously registered with pyodide.registerJsModule() or register_js_module().

Classes:

PyBuffer

An alias for pyodide.ffi.PyBufferView.

PyProxyBuffer

An alias for pyodide.ffi.PyBuffer.

PythonError

An alias for pyodide.ffi.PyBuffer.

pyodide.ERRNO_CODES#

type: {[code: string]: number}

A map from posix error names to error codes.

pyodide.FS#

type: any

An alias to the Emscripten File System API.

This provides a wide range of POSIX-like file/device operations, including mount which can be used to extend the in-memory filesystem with features like persistence.

While all the file systems implementations are enabled, only the default MEMFS is guaranteed to work in all runtime settings. The implementations are available as members of FS.filesystems: IDBFS, NODEFS, PROXYFS, WORKERFS.

pyodide.PATH#

type: any

An alias to the Emscripten Path API.

This provides a variety of operations for working with file system paths, such as dirname, normalize, and splitPath.

pyodide.canvas#

type: CanvasInterface

This provides APIs to set a canvas for rendering graphics.

For example, you need to set a canvas if you want to use the SDL library. See Using SDL-based packages in Pyodide for more information.

pyodide.ffi#

See pyodide.ffi

pyodide.globals#

type: PyProxy

An alias to the global Python namespace.

For example, to access a variable called foo in the Python global scope, use pyodide.globals.get("foo")

pyodide.loadedPackages#

type: {[key: string]: string}

The list of packages that Pyodide has loaded. Use Object.keys(pyodide.loadedPackages) to get the list of names of loaded packages, and pyodide.loadedPackages[package_name] to access install location for a particular package_name.

pyodide.pyodide_py#

type: PyProxy

An alias to the Python pyodide package.

You can use this to call functions defined in the Pyodide Python package from JavaScript.

pyodide.version#

type: string

The Pyodide version.

The version here is a Python version, following PEP 440. This is different from the version in package.json which follows the node package manager version convention.

static pyodide.checkInterrupt()#

Throws a KeyboardInterrupt error if a KeyboardInterrupt has been requested via the interrupt buffer.

This can be used to enable keyboard interrupts during execution of JavaScript code, just as PyErr_CheckSignals() is used to enable keyboard interrupts during execution of C code.

static pyodide.isPyProxy(jsobj)#

Note

Deprecated: Use obj instanceof pyodide.ffi.PyProxy instead.

Is jsobj a PyProxy?

Arguments:
  • jsobj (any) – Object to test.

Returns:

boolean (typeguard for PyProxy) –

async pyodide.loadPackage(names, options)#

Load packages from the Pyodide distribution or Python wheels by URL.

This installs packages in the virtual filesystem. Packages needs to be imported from Python before it can be used.

This function can only install packages included in the Pyodide distribution, or Python wheels by URL, without dependency resolution. It is significantly more limited in terms of functionality as compared to micropip, however it has less overhead and can be faster.

When installing binary wheels by URLs it is user’s responsibility to check that the installed binary wheel is compatible in terms of Python and Emscripten versions. Compatibility is not checked during installation time (unlike with micropip). If a wheel for the wrong Python/Emscripten version is installed it would fail at import time.

Arguments:
  • names (string | string[] | PyProxy) – Either a single package name or URL or a list of them. URLs can be absolute or relative. The URLs must correspond to Python wheels: either pure Python wheels, with a file name ending with none-any.whl or Emscripten/WASM 32 wheels, with a file name ending with cp<pyversion>_emscripten_<em_version>_wasm32.whl. The argument can be a PyProxy of a list, in which case the list will be converted to JavaScript and the PyProxy will be destroyed.

  • options.checkIntegrity (boolean) – If true, check the integrity of the downloaded packages (default: true)

  • options.errorCallback ((message: string) => void) – A callback, called with error/warning messages (optional)

  • options.messageCallback ((message: string) => void) – A callback, called with progress messages (optional)

Returns:

Promise<void>

static pyodide.pyimport(mod_name)#

Imports a module and returns it.

Warning

This function has a completely different behavior than the old removed pyimport function!

pyimport is roughly equivalent to:

pyodide.runPython(`import ${pkgname}; ${pkgname}`);

except that the global namespace will not change.

Example:

let sysmodule = pyodide.pyimport("sys");
let recursionLimit = sysmodule.getrecursionlimit();
Arguments:
  • mod_name (string) – The name of the module to import

Returns:

PyProxy – A PyProxy for the imported module

Tell Pyodide about Comlink. Necessary to enable importing Comlink proxies into Python.

Arguments:
  • Comlink (any) –

static pyodide.registerJsModule(name, module)#

Registers the JavaScript object module as a JavaScript module named name. This module can then be imported from Python using the standard Python import system. If another module by the same name has already been imported, this won’t have much effect unless you also delete the imported module from sys.modules. This calls register_js_module().

Arguments:
  • name (string) – Name of the JavaScript module to add

  • module (object) – JavaScript object backing the module

static pyodide.runPython(code, options)#

Runs a string of Python code from JavaScript, using eval_code() to evaluate the code. If the last statement in the Python code is an expression (and the code doesn’t end with a semicolon), the value of the expression is returned.

Arguments:
  • code (string) – Python code to evaluate

  • options.globals (PyProxy) – An optional Python dictionary to use as the globals. Defaults to pyodide.globals.

  • options.locals (PyProxy) – An optional Python dictionary to use as the locals. Defaults to the same as globals.

Returns:

any – The result of the Python code translated to JavaScript. See the documentation for eval_code() for more info.

static pyodide.setInterruptBuffer(interrupt_buffer)#

Sets the interrupt buffer to be interrupt_buffer. This is only useful when Pyodide is used in a webworker. The buffer should be a SharedArrayBuffer shared with the main browser thread (or another worker). In that case, signal signum may be sent by writing signum into the interrupt buffer. If signum does not satisfy 0 < signum < 65 it will be silently ignored.

You can disable interrupts by calling setInterruptBuffer(undefined).

If you wish to trigger a KeyboardInterrupt, write SIGINT (a 2) into the interrupt buffer.

By default SIGINT raises a KeyboardInterrupt and all other signals are ignored. You can install custom signal handlers with the signal module. Even signals that normally have special meaning and can’t be overridden like SIGKILL and SIGSEGV are ignored by default and can be used for any purpose you like.

Arguments:
  • interrupt_buffer (TypedArray) –

pyodide.setStderr(options)#

Sets the standard error handler. A batched handler or a raw handler can be provided (both not both). If neither is provided, we restore the default handler.

Arguments:
  • options.isatty (boolean) – Should isatty(stderr) return true or false. Can only be set to true if a raw handler is provided (default false).

  • options.batched ((a: string) => void) – A batched handler is called with a string whenever a newline character is written is written or stderr is flushed. In the former case, the received line will end with a newline, in the latter case it will not. isatty(stderr) is set to false (when using a batched handler, stderr is buffered so it is impossible to make a tty with it).

  • options.raw ((a: number) => void) – A raw handler is called with the handler is called with a number for each byte of the output to stderr.

pyodide.setStdin(options)#

Set a stdin handler.

The stdin handler is called with zero arguments whenever stdin is read and the current input buffer is exhausted. It should return one of:

If a number is returned, it is interpreted as a single character code. The number should be between 0 and 255.

If a string is returned, a new line is appended if one is not present and the resulting string is turned into a Uint8Array using TextEncoder.

Returning a buffer is more efficient and allows returning partial lines of text.

Arguments:
  • options.autoEOF (boolean) – Insert an EOF automatically after each string or buffer? (default true).

  • options.error (boolean) – If this is set to true, attempts to read from stdin will always set an IO error.

  • options.isatty (boolean) – Should isatty(stdin) be true or false (default false).

  • options.stdin (() => null | undefined | string | ArrayBuffer | Uint8Array | number) – The stdin handler.

pyodide.setStdout(options)#

Sets the standard out handler. A batched handler or a raw handler can be provided (both not both). If neither is provided, we restore the default handler.

Arguments:
  • options.isatty (boolean) – Should isatty(stdout) return true or false. Can only be set to true if a raw handler is provided (default false).

  • options.batched ((a: string) => void) – A batched handler is called with a string whenever a newline character is written is written or stdout is flushed. In the former case, the received line will end with a newline, in the latter case it will not.

  • options.raw ((a: number) => void) – A raw handler is called with the handler is called with a number for each byte of the output to stdout.

static pyodide.toPy(obj, options)#

Convert a JavaScript object to a Python object as best as possible.

This is similar to to_py() but for use from JavaScript. If the object is immutable or a PyProxy, it will be returned unchanged. If the object cannot be converted into Python, it will be returned unchanged.

See JavaScript to Python for more information.

Arguments:
  • obj (any) – The object to convert.

  • options.depth (number) – Optional argument to limit the depth of the conversion.

  • options.defaultConverter ((value: any, converter: (value: any) => any, cacheConversion: (input: any, output: any) => void) => any) – Optional argument to convert objects with no default conversion. See the documentation of to_py().

Returns:

any – The object converted to Python.

static pyodide.unpackArchive(buffer, format, options)#

Unpack an archive into a target directory.

Arguments:
  • buffer (ArrayBuffer | TypedArray) – The archive as an ArrayBuffer or TypedArray.

  • format (string) – The format of the archive. Should be one of the formats recognized by shutil.unpack_archive(). By default the options are 'bztar', 'gztar', 'tar', 'zip', and 'wheel'. Several synonyms are accepted for each format, e.g., for 'gztar' any of '.gztar', '.tar.gz', '.tgz', 'tar.gz' or 'tgz' are considered to be synonyms.

  • options.extractDir (string) – The directory to unpack the archive into. Defaults to the working directory.

static pyodide.unregisterJsModule(name)#

Unregisters a JavaScript module with given name that has been previously registered with pyodide.registerJsModule() or register_js_module(). If a JavaScript module with that name does not already exist, will throw an error. Note that if the module has already been imported, this won’t have much effect unless you also delete the imported module from sys.modules. This calls unregister_js_module().

Arguments:
  • name (string) – Name of the JavaScript module to remove

pyodide.PyBuffer#

Note

Deprecated.

An alias for pyodide.ffi.PyBufferView.

pyodide.PyProxyBuffer#

Note

Deprecated.

An alias for pyodide.ffi.PyBuffer.

pyodide.PythonError#

Note

Deprecated.

An alias for pyodide.ffi.PyBuffer.

pyodide.ffi#

To import types from pyodide.ffi you can use for example

import type { PyProxy } from "pyodide/ffi";

Classes:

PyAsyncGenerator

A PyProxy whose proxied Python object is an asynchronous generator (i.e., it is an instance of AsyncGenerator)

PyAsyncIterable

A PyProxy whose proxied Python object is asynchronous iterable (i.e., has an __aiter__() method).

PyAsyncIterator

A PyProxy whose proxied Python object is an asynchronous iterator

PyAwaitable

A PyProxy whose proxied Python object is awaitable (i.e., has an __await__() method).

PyBuffer

A PyProxy whose proxied Python object supports the Python Buffer Protocol.

PyBufferView

A class to allow access to Python data buffers from JavaScript.

PyCallable

A PyProxy whose proxied Python object is callable (i.e., has an __call__() method).

PyDict

A PyProxy whose proxied Python object is a dict.

PyGenerator

A PyProxy whose proxied Python object is a generator (i.e., it is an instance of Generator).

PyIterable

A PyProxy whose proxied Python object is iterable (i.e., it has an __iter__() method).

PyIterator

A PyProxy whose proxied Python object is an iterator (i.e., has a send() or __next__() method).

PyProxy

A PyProxy is an object that allows idiomatic use of a Python object from JavaScript.

PyProxyWithGet

A PyProxy whose proxied Python object has a __getitem__() method.

PyProxyWithHas

A PyProxy whose proxied Python object has a __contains__() method.

PyProxyWithLength

A PyProxy whose proxied Python object has a __len__() method.

PyProxyWithSet

A PyProxy whose proxied Python object has a __setitem__() or __delitem__() method.

PythonError

A JavaScript error caused by a Python exception.

class pyodide.ffi.PyAsyncGenerator()#

A PyProxy whose proxied Python object is an asynchronous generator (i.e., it is an instance of AsyncGenerator)

Extends:
PyAsyncGenerator.return(v)#

Throws a GeneratorExit into the generator and if the GeneratorExit is not caught returns the argument value {done: true, value: v}. If the generator catches the GeneratorExit and returns or yields another value the next value of the generator this is returned in the normal way. If it throws some error other than GeneratorExit or StopAsyncIteration, that error is propagated. See the documentation for AsyncGenerator.throw()

Arguments:
Returns:

Promise<IteratorResult<any, any> > – An Object with two properties: done and value. When the generator yields some_value, return returns {done : false, value : some_value}. When the generator raises a StopAsyncIteration exception, return returns {done : true, value : result_value}.

PyAsyncGenerator.throw(exc)#

Throws an exception into the Generator.

See the documentation for AsyncGenerator.throw().

Arguments:
  • exc (any) –

Returns:

Promise<IteratorResult<any, any> > – An Object with two properties: done and value. When the generator yields some_value, return returns {done : false, value : some_value}. When the generator raises a StopIteration(result_value) exception, return returns {done : true, value : result_value}.

class pyodide.ffi.PyAsyncIterable()#

A PyProxy whose proxied Python object is asynchronous iterable (i.e., has an __aiter__() method).

Extends:
PyAsyncIterable.[Symbol․asyncIterator]()#

This translates to the Python code aiter(obj). Return an async iterator associated to the proxy. See the documentation for Symbol.asyncIterator.

This will be used implicitly by for(await let x of proxy){}.

Returns:

AsyncIterator<any, any, any>

class pyodide.ffi.PyAsyncIterator()#

A PyProxy whose proxied Python object is an asynchronous iterator

Extends:
PyAsyncIterator.next(arg=undefined)#

This translates to the Python code anext(obj). Returns the next value of the asynchronous iterator. The argument will be sent to the Python iterator (if it’s a generator for instance).

This will be used implicitly by for(let x of proxy){}.

Arguments:
  • arg (any) –

Returns:

Promise<IteratorResult<any, any> > – An Object with two properties: done and value. When the iterator yields some_value, next returns {done : false, value : some_value}. When the giterator is done, next returns {done : true }.

class pyodide.ffi.PyAwaitable()#

A PyProxy whose proxied Python object is awaitable (i.e., has an __await__() method).

Extends:
class pyodide.ffi.PyBuffer()#

A PyProxy whose proxied Python object supports the Python Buffer Protocol.

Examples of buffers include {py:class}`bytes` objects and numpy {external+numpy:ref}`arrays`.

Extends:
PyBuffer.getBuffer(type)#

Get a view of the buffer data which is usable from JavaScript. No copy is ever performed.

We do not support suboffsets, if the buffer requires suboffsets we will throw an error. JavaScript nd array libraries can’t handle suboffsets anyways. In this case, you should use the toJs() api or copy the buffer to one that doesn’t use suboffsets (using e.g., numpy.ascontiguousarray()).

If the buffer stores big endian data or half floats, this function will fail without an explicit type argument. For big endian data you can use toJs(). DataView has support for big endian data, so you might want to pass 'dataview' as the type argument in that case.

Arguments:
  • type (string) – The type of the data field in the output. Should be one of: "i8", "u8", "u8clamped", "i16", "u16", "i32", "u32", "i32", "u32", "i64", "u64", "f32", "f64, or "dataview". This argument is optional, if absent getBuffer() will try to determine the appropriate output type based on the buffer format string (see Format Strings).

Returns:

PyBufferView

class pyodide.ffi.PyBufferView()#

A class to allow access to Python data buffers from JavaScript. These are produced by getBuffer() and cannot be constructed directly. When you are done, release it with the release() method. See the Python Buffer Protocol documentation for more information.

To find the element x[a_1, ..., a_n], you could use the following code:

function multiIndexToIndex(pybuff, multiIndex){
   if(multindex.length !==pybuff.ndim){
      throw new Error("Wrong length index");
   }
   let idx = pybuff.offset;
   for(let i = 0; i < pybuff.ndim; i++){
      if(multiIndex[i] < 0){
         multiIndex[i] = pybuff.shape[i] - multiIndex[i];
      }
      if(multiIndex[i] < 0 || multiIndex[i] >= pybuff.shape[i]){
         throw new Error("Index out of range");
      }
      idx += multiIndex[i] * pybuff.stride[i];
   }
   return idx;
}
console.log("entry is", pybuff.data[multiIndexToIndex(pybuff, [2, 0, -1])]);

Converting between TypedArray types

The following naive code to change the type of a typed array does not work:

// Incorrectly convert a TypedArray.
// Produces a Uint16Array that points to the entire WASM memory!
let myarray = new Uint16Array(buffer.data.buffer);

Instead, if you want to convert the output TypedArray, you need to say:

// Correctly convert a TypedArray.
let myarray = new Uint16Array(
    buffer.data.buffer,
    buffer.data.byteOffset,
    buffer.data.byteLength
);
PyBufferView.c_contiguous#

type: boolean

Is it C contiguous? See memoryview.c_contiguous.

PyBufferView.data#

type: TypedArray

The actual data. A typed array of an appropriate size backed by a segment of the WASM memory.

The type argument of getBuffer() determines which sort of TypedArray or DataView to return. By default getBuffer() will look at the format string to determine the most appropriate option. Most often the result is a Uint8Array.

Contiguity

If the buffer is not contiguous, the readonly TypedArray will contain data that is not part of the buffer. Modifying this data leads to undefined behavior.

Read only buffers

If buffer.readonly is true, you should not modify the buffer. Modifying a read only buffer leads to undefined behavior.

PyBufferView.f_contiguous#

type: boolean

Is it Fortran contiguous? See memoryview.f_contiguous.

PyBufferView.format#

type: string

The format string for the buffer. See Format Strings and memoryview.format.

PyBufferView.itemsize#

type: number

How large is each entry in bytes? See memoryview.itemsize.

PyBufferView.nbytes#

type: number

The total number of bytes the buffer takes up. This is equal to buff.data.byteLength. See memoryview.nbytes.

PyBufferView.ndim#

type: number

The number of dimensions of the buffer. If ndim is 0, the buffer represents a single scalar or struct. Otherwise, it represents an array. See memoryview.ndim.

PyBufferView.offset#

type: number

The offset of the first entry of the array. For instance if our array is 3d, then you will find array[0,0,0] at pybuf.data[pybuf.offset]

PyBufferView.readonly#

type: boolean

If the data is read only, you should not modify it. There is no way for us to enforce this, but it may cause very weird behavior. See memoryview.readonly.

PyBufferView.shape#

type: number[]

The shape of the buffer, that is how long it is in each dimension. The length will be equal to ndim. For instance, a 2x3x4 array would have shape [2, 3, 4]. See memoryview.shape.

PyBufferView.strides#

type: number[]

An array of of length ndim giving the number of elements to skip to get to a new element in each dimension. See the example definition of a multiIndexToIndex function above. See memoryview.strides.

PyBufferView.release()#

Release the buffer. This allows the memory to be reclaimed.

class pyodide.ffi.PyCallable()#

A PyProxy whose proxied Python object is callable (i.e., has an __call__() method).

Extends:
PyCallable.apply(thisArg, jsargs)#

The apply() method calls the specified function with a given this value, and arguments provided as an array (or an array-like object). Like Function.apply().

Arguments:
  • thisArg (any) – The this argument. Has no effect unless the PyCallable has captureThis() set. If captureThis() is set, it will be passed as the first argument to the Python function.

  • jsargs (any) – The array of arguments

Returns:

any – The result from the function call.

PyCallable.bind(thisArg, ...jsargs)#

The bind() method creates a new function that, when called, has its this keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called. See Function.bind().

If the PyCallable does not have captureThis() set, the this parameter will be discarded. If it does have captureThis() set, thisArg will be set to the first argument of the Python function. The returned proxy and the original proxy have the same lifetime so destroying either destroys both.

Arguments:
  • thisArg (any) – The value to be passed as the this parameter to the target function func when the bound function is called.

  • jsargs (any) – Extra arguments to prepend to arguments provided to the bound function when invoking func.

Returns:

PyProxy

PyCallable.call(thisArg, ...jsargs)#

Calls the function with a given this value and arguments provided individually. See Function.call().

Arguments:
  • thisArg (any) – The this argument. Has no effect unless the PyCallable has captureThis() set. If captureThis() is set, it will be passed as the first argument to the Python function.

  • jsargs (any) – The arguments

Returns:

any – The result from the function call.

PyCallable.callKwargs(...jsargs)#

Call the function with key word arguments. The last argument must be an object with the keyword arguments.

Arguments:
  • jsargs (any) –

Returns:

any

PyCallable.captureThis()#

Returns a PyProxy that passes this as the first argument to the Python function. The returned PyProxy has the internal captureThis property set.

It can then be used as a method on a JavaScript object. The returned proxy and the original proxy have the same lifetime so destroying either destroys both.

For example:

let obj = { a : 7 };
pyodide.runPython(`
  def f(self):
    return self.a
`);
// Without captureThis, it doesn't work to use f as a method for obj:
obj.f = pyodide.globals.get("f");
obj.f(); // raises "TypeError: f() missing 1 required positional argument: 'self'"
// With captureThis, it works fine:
obj.f = pyodide.globals.get("f").captureThis();
obj.f(); // returns 7
Returns:

PyProxy – The resulting PyProxy. It has the same lifetime as the original PyProxy but passes this to the wrapped function.

class pyodide.ffi.PyDict()#

A PyProxy whose proxied Python object is a dict.

Extends:
class pyodide.ffi.PyGenerator()#

A PyProxy whose proxied Python object is a generator (i.e., it is an instance of Generator).

Extends:
PyGenerator.return(v)#

Throws a GeneratorExit into the generator and if the GeneratorExit is not caught returns the argument value {done: true, value: v}. If the generator catches the GeneratorExit and returns or yields another value the next value of the generator this is returned in the normal way. If it throws some error other than GeneratorExit or StopIteration, that error is propagated. See the documentation for Generator.return().

Arguments:
Returns:

IteratorResult<any, any> – An Object with two properties: done and value. When the generator yields some_value, return returns {done : false, value : some_value}. When the generator raises a StopIteration(result_value) exception, return returns {done : true, value : result_value}.

PyGenerator.throw(exc)#

Throws an exception into the Generator.

See the documentation for Generator.throw().

Arguments:
  • exc (any) –

Returns:

IteratorResult<any, any> – An Object with two properties: done and value. When the generator yields some_value, return returns {done : false, value : some_value}. When the generator raises a StopIteration(result_value) exception, return returns {done : true, value : result_value}.

class pyodide.ffi.PyIterable()#

A PyProxy whose proxied Python object is iterable (i.e., it has an __iter__() method).

Extends:
PyIterable.[Symbol․iterator]()#

This translates to the Python code iter(obj). Return an iterator associated to the proxy. See the documentation for Symbol.iterator.

This will be used implicitly by for(let x of proxy){}.

Returns:

Iterator<any, any, any>

class pyodide.ffi.PyIterator()#

A PyProxy whose proxied Python object is an iterator (i.e., has a send() or __next__() method).

Extends:
PyIterator.next(arg=undefined)#

This translates to the Python code next(obj). Returns the next value of the generator. See the documentation for Generator.next() The argument will be sent to the Python generator.

This will be used implicitly by for(let x of proxy){}.

Arguments:
  • arg (any) –

Returns:

IteratorResult<any, any> – An Object with two properties: done and value. When the generator yields some_value, next returns {done : false, value : some_value}. When the generator raises a StopIteration exception, next returns {done : true, value : result_value}.

class pyodide.ffi.PyProxy()#

A PyProxy is an object that allows idiomatic use of a Python object from JavaScript. See Proxying from Python into JavaScript.

PyProxy.type#

type: string

The name of the type of the object.

Usually the value is "module.name" but for builtins or interpreter-defined types it is just "name". As pseudocode this is:

ty = type(x)
if ty.__module__ == 'builtins' or ty.__module__ == "__main__":
    return ty.__name__
else:
    ty.__module__ + "." + ty.__name__
PyProxy.copy()#

Make a new PyProxy pointing to the same Python object. Useful if the PyProxy is destroyed somewhere else.

Returns:

PyProxy

PyProxy.destroy(options)#

Destroy the PyProxy. This will release the memory. Any further attempt to use the object will raise an error.

In a browser supporting FinalizationRegistry, Pyodide will automatically destroy the PyProxy when it is garbage collected, however there is no guarantee that the finalizer will be run in a timely manner so it is better to destroy the proxy explicitly.

Arguments:
  • options.destroyRoundtrip (boolean) –

  • options.message (string) – The error message to print if use is attempted after destroying. Defaults to “Object has already been destroyed”.

PyProxy.isAwaitable()#

Note

Deprecated: Use obj instanceof pyodide.ffi.PyAwaitable instead.

Check whether the PyProxy is a PyAwaitable

Returns:

boolean (typeguard for PyAwaitable) –

PyProxy.isBuffer()#

Note

Deprecated: Use obj instanceof pyodide.ffi.PyBuffer instead.

Check whether the PyProxy is a PyBuffer.

Returns:

boolean (typeguard for PyBuffer) –

PyProxy.isCallable()#

Note

Deprecated: obj instanceof pyodide.ffi.PyCallable instead.

Check whether the PyProxy is a PyCallable.

Returns:

boolean (typeguard for PyCallable) –

PyProxy.isIterable()#

Note

Deprecated: Use obj instanceof pyodide.ffi.PyIterable instead.

Check whether the PyProxy is a PyIterable.

Returns:

boolean (typeguard for PyIterable) –

PyProxy.isIterator()#

Note

Deprecated: Use obj instanceof pyodide.ffi.PyIterator instead.

Check whether the PyProxy is a PyIterator

Returns:

boolean (typeguard for PyIterator) –

PyProxy.supportsGet()#

Note

Deprecated: Use obj instanceof pyodide.ffi.PyProxyWithGet instead.

Check whether the PyProxy is a PyProxyWithGet.

Returns:

boolean (typeguard for PyProxyWithGet) –

PyProxy.supportsHas()#

Note

Deprecated: Use obj instanceof pyodide.ffi.PyProxyWithHas instead.

Check whether the PyProxy is a PyProxyWithHas.

Returns:

boolean (typeguard for PyProxyWithHas) –

PyProxy.supportsLength()#

Note

Deprecated: Use obj instanceof pyodide.ffi.PyProxyWithLength instead.

Check whether the PyProxy is a PyProxyWithLength.

Returns:

boolean (typeguard for PyProxyWithLength) –

PyProxy.supportsSet()#

Note

Deprecated: Use obj instanceof pyodide.ffi.PyProxyWithSet instead.

Check whether the PyProxy is a PyProxyWithSet.

Returns:

boolean (typeguard for PyProxyWithSet) –

PyProxy.toJs(options)#

Converts the PyProxy into a JavaScript object as best as possible. By default does a deep conversion, if a shallow conversion is desired, you can use proxy.toJs({depth : 1}). See Explicit Conversion of PyProxy for more info.

Arguments:
  • options.create_pyproxies (boolean) – If false, toJs() will throw a ConversionError rather than producing a PyProxy.

  • options.depth (number) – How many layers deep to perform the conversion. Defaults to infinite

  • options.pyproxies (PyProxy[]) – If provided, toJs() will store all PyProxies created in this list. This allows you to easily destroy all the PyProxies by iterating the list without having to recurse over the generated structure. The most common use case is to create a new empty list, pass the list as pyproxies, and then later iterate over pyproxies to destroy all of created proxies.

  • options.default_converter ((obj: PyProxy, convert: (obj: PyProxy) => any, cacheConversion: (obj: PyProxy, result: any) => void) => any) – Optional argument to convert objects with no default conversion. See the documentation of to_js().

  • options.dict_converter ((array: Iterable<[key: string, value: any] > ) => any) – A function to be called on an iterable of pairs [key, value]. Convert this iterable of pairs to the desired output. For instance, Object.fromEntries() would convert the dict to an object, Array.from() converts it to an Array of pairs, and (it) => new Map(it) converts it to a Map (which is the default behavior).

Returns:

any – The JavaScript object resulting from the conversion.

PyProxy.toString()#
Returns:

string

class pyodide.ffi.PyProxyWithGet()#

A PyProxy whose proxied Python object has a __getitem__() method.

Extends:
PyProxyWithGet.get(key)#

This translates to the Python code obj[key].

Arguments:
  • key (any) – The key to look up.

Returns:

any – The corresponding value.

class pyodide.ffi.PyProxyWithHas()#

A PyProxy whose proxied Python object has a __contains__() method.

Extends:
PyProxyWithHas.has(key)#

This translates to the Python code key in obj.

Arguments:
  • key (any) – The key to check for.

Returns:

boolean – Is key present?

class pyodide.ffi.PyProxyWithLength()#

A PyProxy whose proxied Python object has a __len__() method.

Extends:
PyProxyWithLength.length#

type: number

The length of the object.

class pyodide.ffi.PyProxyWithSet()#

A PyProxy whose proxied Python object has a __setitem__() or __delitem__() method.

Extends:
PyProxyWithSet.delete(key)#

This translates to the Python code del obj[key].

Arguments:
  • key (any) – The key to delete.

PyProxyWithSet.set(key, value)#

This translates to the Python code obj[key] = value.

Arguments:
  • key (any) – The key to set.

  • value (any) – The value to set it to.

class pyodide.ffi.PythonError()#

A JavaScript error caused by a Python exception.

In order to reduce the risk of large memory leaks, the PythonError contains no reference to the Python exception that caused it. You can find the actual Python exception that caused this error as sys.last_value.

See type translations of errors for more information.

Avoid leaking stack Frames

If you make a PyProxy of sys.last_value, you should be especially careful to destroy() it when you are done. You may leak a large amount of memory including the local variables of all the stack frames in the traceback if you don’t. The easiest way is to only handle the exception in Python.

PythonError.type#

type: string

The name of the Python error class, e.g, RuntimeError or KeyError.

pyodide.canvas#

This provides APIs to set a canvas for rendering graphics.

Functions:

getCanvas2D()

getCanvas3D()

setCanvas2D(canvas)

setCanvas3D(canvas)

pyodide.canvas.getCanvas2D()#
Returns:

undefined | HTMLCanvasElement – The HTML5 canvas element used for 2D rendering. For now, Emscripten only supports one canvas element, so getCanvas2D and getCanvas3D are the same.

pyodide.canvas.getCanvas3D()#
Returns:

undefined | HTMLCanvasElement – The HTML5 canvas element used for 3D rendering. For now, Emscripten only supports one canvas element, so getCanvas2D and getCanvas3D are the same.

pyodide.canvas.setCanvas2D(canvas)#
Arguments:
  • canvas (HTMLCanvasElement) – The HTML5 canvas element to use for 2D rendering. For now, Emscripten only supports one canvas element, so setCanvas2D and setCanvas3D are the same.

pyodide.canvas.setCanvas3D(canvas)#
Arguments:
  • canvas (HTMLCanvasElement) – The HTML5 canvas element to use for 3D rendering. For now, Emscripten only supports one canvas element, so setCanvas2D and setCanvas3D are the same.