JavaScript API#
Top Level Exports#
These can be imported via import { name } from "pyodide.mjs";. If you cant
use the es6 module, pyodide.js places loadPyodide() on
globalThis. The other top level exports cannot be accessed from
pyodide.js.
-
PyodideAPI#
The return type of loadPyodide(). See
the pyodide api docs for more information.
-
interface PyodideConfig#
The configuration options for loading Pyodide.
-
PyodideConfig.args?#
type: string[]
Command line arguments to pass to Python on startup. See Python command
line interface options for
more details. Default: []
-
PyodideConfig.checkAPIVersion?#
type: boolean
If true (default), throw an error if the version of Pyodide core does not
match the version of the Pyodide js package.
-
PyodideConfig.convertNullToNone?#
-
type: boolean
Opt into the old behavior where JavaScript null is converted to None
instead of jsnull. Deprecated.
-
PyodideConfig.createPyodideModule?#
type: (settings: EmscriptenSettings) => Promise<PyodideModule>
The constructor function to use to create the Pyodide module.
This function can be imported from pyodide.asm.mjs
and passed to loadPyodide as createPyodideModule option.
This is used to work around service workers forbid dynamic import(),
and not intended to be used in other cases.
Warning: This is an experimental feature and may change in the future.
-
PyodideConfig.enableRunUntilComplete?#
type: boolean
Make loop.run_until_complete() function correctly using stack switching.
Default: true.
-
PyodideConfig.env?#
type: { [key: string]: string; }
Environment variables to pass to Python. This can be accessed inside of
Python at runtime via os.environ. Certain environment variables change
the way that Python loads:
https://docs.python.org/3.10/using/cmdline.html#environment-variables
Default: {}.
If env.HOME is undefined, it will be set to a default value of
"/home/pyodide"
-
PyodideConfig.fullStdLib?#
type: boolean
Deprecated: This option has no effect.
-
PyodideConfig.indexURL?#
type: 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.
-
PyodideConfig.jsglobals?#
type: object
The object that Pyodide will use for the js module.
Default: globalThis
-
PyodideConfig.lockFileContents?#
type: string | Lockfile | Promise<string | Lockfile>
The contents of a lockfile. If a string, it should be valid json and
JSON.parse() should return a Lockfile instance. See
Lockfile for the schema.
-
PyodideConfig.lockFileURL?#
type: string
The URL from which Pyodide will load the Pyodide pyodide-lock.json lock
file. You can produce custom lock files with micropip.freeze().
Default: `${indexURL}/pyodide-lock.json`
-
PyodideConfig.packageBaseUrl?#
type: string
The base url relative to which a relative value of
file_name is interpreted. If
lockfileContents is provided, then lockFileContents must be
provided explicitly in order to install packages with relative paths.
Otherwise, the default is calculated as follows:
If lockFileURL contains a /, the default is everything before the last
/ in lockFileURL.
If in the browser, the default is location.toString().
Otherwise, the default is '.'.
-
PyodideConfig.packageCacheDir?#
type: string
The file path where packages will be cached in node. If a package
exists in packageCacheDir it is loaded from there, otherwise it is
downloaded from the JsDelivr CDN and then cached into packageCacheDir.
Only applies when running in node; ignored in browsers.
Default: same as indexURL
-
PyodideConfig.packages?#
type: string[]
A list of packages to load as Pyodide is initializing.
This is the same as loading the packages with
pyodide.loadPackage() after Pyodide is loaded except using the
packages option is more efficient because the packages are downloaded
while Pyodide bootstraps itself.
-
PyodideConfig.pyproxyToStringRepr?#
-
type: boolean
Opt into the old behavior where PyProxy.toString()
calls repr() and not str(). Deprecated.
-
PyodideConfig.stdLibURL?#
type: string
The URL from which to load the standard library python_stdlib.zip
file. This URL includes the most of the Python standard library.
Default: `${indexURL}/python_stdlib.zip`
-
PyodideConfig.toJsLiteralMap?#
-
type: boolean
Opt into the old behavior where Python dictionaries are converted to
LiteralMap instead of Object.
-
async PyodideConfig.fsInit?(FS, info)#
This is a hook that allows modification of the file system before the
main() function is called and the intereter is started. When this is
called, it is guaranteed that there is an empty site-packages directory.
- Arguments:
-
- Returns:
Promise<void>
-
PyodideConfig.stderr?(msg)#
Override the standard error output callback. The
pyodide.setStderr() function is more flexible and should be
preferred in most cases, but depending on the args passed to
loadPyodide, Pyodide may write to stdout on startup, which can only
be controlled by passing a custom stdout function.
- Arguments:
-
-
PyodideConfig.stdin?()#
Override the standard input callback. Should ask the user for one line of
input. The pyodide.setStdin() function is more flexible and
should be preferred.
- Returns:
null | string
-
PyodideConfig.stdout?(msg)#
Override the standard output callback. The pyodide.setStdout()
function is more flexible and should be preferred in most cases, but
depending on the args passed to loadPyodide, Pyodide may write to
stdout on startup, which can only be controlled by passing a custom
stdout function.
- Arguments:
-
-
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.
-
async loadPyodide(options={})#
Load the main Pyodide wasm module and initialize it.
- Arguments:
-
- Returns:
Promise<typeof PyodideAPI> The pyodide module.
Example
async function main() {
const pyodide = await loadPyodide({
stdout: (msg) => console.log(`Pyodide: ${msg}`),
});
console.log("Loaded Pyodide");
}
main();
pyodide#
This section documents the pyodide API object, which is returned by
loadPyodide().
-
interface BatchedWriteHandler#
A batched handler to provide to setStdout() or
setStderr().
The handler.batched() handler is called with a string whenever a newline
character 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. Streams
implemented with a batched handlers cannot be a tty.
-
BatchedWriteHandler.batched(output)#
- Arguments:
-
-
interface Lockfile#
The type of a package lockfile.
-
Lockfile.info#
type: LockfileInfo
-
Lockfile.packages#
type: Record<string, LockfilePackage>
-
interface LockfileInfo#
The lockfile platform info. The abi_version field is used to check if the
lockfile is compatible with the interpreter. The remaining fields are
informational.
-
LockfileInfo.abi_version#
type: string
The ABI version is structured as yyyy_patch. For the lockfile to be
compatible with the current interpreter this field must match exactly with
the ABI version of the interpreter.
-
LockfileInfo.arch#
type: wasm32
Machine architecture. At present, only can be wasm32. Pyodide has no wasm64
build.
-
LockfileInfo.platform#
type: string
The Emscripten versions for instance, emscripten_4_0_9. Different
Emscripten versions have different ABIs so if this changes abi_version
must also change.
-
LockfileInfo.python#
type: string
The Python version this lock file was made with. If the minor version
changes (e.g, 3.12 to 3.13) this changes the ABI and the abi_version
must change too. Patch versions do not imply a change to the
abi_version.
-
LockfileInfo.version#
type: string
The Pyodide version the lockfile was made with. Informational only, has no
compatibility implications. May be removed in the future.
-
interface LockfilePackage#
A package entry in the lock file.
-
LockfilePackage.depends#
type: string[]
The set of dependencies of this package.
-
LockfilePackage.file_name#
type: string
The file name or url of the package wheel. If its relative, it will be
resolved with respect to packageBaseUrl. If there is no
packageBaseUrl, attempting to install a package with a relative
file_name will fail.
-
LockfilePackage.imports#
type: string[]
The set of imports provided by this package as best we can tell. Used by
pyodide.loadPackagesFromImports() to work out what packages to
install.
-
LockfilePackage.install_dir#
type: site | dynlib
The installation directory. Will be site except for certain system
dynamic libraries that need to go on the global LD_LIBRARY_PATH.
-
LockfilePackage.name#
type: string
The unnormalized name of the package.
-
LockfilePackage.package_type#
type: package | cpython_module | shared_library | static_library
-
LockfilePackage.sha256#
type: string
Integrity. Must be present unless checkIntegrity: false is passed to
loadPyodide.
-
LockfilePackage.version#
type: string
-
interface PackageData#
-
PackageData.fileName#
type: string
-
PackageData.name#
type: string
-
PackageData.packageType#
type: package | cpython_module | shared_library | static_library
-
PackageData.version#
type: string
-
interface RawWriteHandler#
A raw handler to provide to setStdout() or
setStderr().
The handler.raw() function is called once with each byte written to the
stream as an argument.
isatty controls whether isatty() returns true or false for the
stream. It defaults to false.
If present, and isatty is true, getTerminalSize() controls the size of
the terminal reported by the tiocgwinsz ioctl, which propagates to
os.get_terminal_size(). If absent, the terminal size is reported as 24 rows
by 80 columns.
-
RawWriteHandler.isatty?#
type: boolean
-
RawWriteHandler.getTerminalSize?()#
- Returns:
undefined | { columns: number; rows: number; }
-
RawWriteHandler.raw(charCode)#
- Arguments:
-
-
interface Writer#
A Writer to provide to setStdout() or
setStderr().
Writer.write is called with a series of Uint8Array buffers containing
bytes to write to the stream.
isatty controls whether isatty() returns true or false for the
stream. It defaults to false.
If present, and isatty is true, getTerminalSize() controls the size of
the terminal reported by the tiocgwinsz ioctl, which propagates to
os.get_terminal_size(). If absent, the terminal size is reported as 24 rows
by 80 columns.
If provided, fsync is called when the stream is fsyncd.
-
Writer.isatty?#
type: boolean
-
Writer.fsync?()#
-
Writer.getTerminalSize?()#
- Returns:
undefined | { columns: number; rows: number; }
-
Writer.write(buffer)#
- Arguments:
-
- Returns:
number
-
pyodide.ERRNO_CODES#
type: { [code: string]: number; }
A map from posix error names to error codes.
-
pyodide.FS#
type: typeof FS
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.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: Record<string, string>
An object whose keys are the names of the loaded packages and whose values
are the install sources of the packages. Use
Object.keys(pyodide.loadedPackages) to get the list of names of loaded
packages, and pyodide.loadedPackages[package_name] to access the install
source for a particular package_name.
-
pyodide.lockfile#
type: readonly Lockfile
Returns the pyodide lockfile used to load the current Pyodide instance.
The format of the lockfile is defined in the pyodide/pyodide-lock repository.
-
pyodide.lockfileBaseUrl#
type: readonly undefined | string
Returns the URL or path with respect to which relative paths in the lock
file are resolved, or undefined.
-
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.
-
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.
-
async pyodide.initializeNodeSockFS(connectFunc)#
Initialize NodeSockFS.
connectFunc can be optionally given to change the behavior of the connect function.
The conndctFunc should satisfy the WinterCG socket-api interface (WinterTC55/proposal-sockets-api),
and it is designed to be used in Cloudflare Workers
- Arguments:
-
- Returns:
Promise<void>
-
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 users 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.messageCallback ((message: string) => void) A callback, called with progress messages (optional)
options.errorCallback ((message: string) => void) A callback, called with error/warning messages (optional)
options.checkIntegrity (boolean) If true, check the integrity of the downloaded packages (default: true)
- Returns:
Promise<PackageData[]> The loaded package data.
-
async pyodide.loadPackagesFromImports(code, options)#
Inspect a Python code chunk and use pyodide.loadPackage() to install
any known packages that the code chunk imports. Uses the Python API
pyodide.code.find_imports() to inspect the code.
For example, given the following code as input
import numpy as np
x = np.array([1, 2, 3])
loadPackagesFromImports() will call
pyodide.loadPackage(['numpy']).
- Arguments:
code (string) The code to inspect.
options.messageCallback ((message: string) => void) A callback, called with progress messages (optional)
options.errorCallback ((message: string) => void) A callback, called with error/warning messages (optional)
options.checkIntegrity (boolean) If true, check the integrity of the downloaded packages (default: true)
- Returns:
Promise<PackageData[]>
-
async pyodide.mountNativeFS(path, fileSystemHandle)#
Mounts a FileSystemDirectoryHandle into the target directory.
Currently its only possible to acquire a
FileSystemDirectoryHandle in Chrome.
- Arguments:
-
- Returns:
Promise<{ syncfs: () => Promise<void>; }>
-
pyodide.mountNodeFS(emscriptenPath, hostPath)#
Mounts a host directory into Pyodide file system. Only works in node.
- Arguments:
emscriptenPath (string) The absolute path in the Emscripten file system to mount the native directory. If the directory does not exist, it will be created. If it does exist, it must be empty.
hostPath (string) The host path to mount. It must be a directory that exists.
-
pyodide.pyimport(mod_name)#
Imports a module and returns it.
If name has no dot in it, then pyimport(name) is approximately
equivalent to:
pyodide.runPython(`import ${name}; ${name}`)
except that name is not introduced into the Python global namespace. If
the name has one or more dots in it, say it is of the form path.name
where name has no dots but path may have zero or more dots. Then it is
approximately the same as:
pyodide.runPython(`from ${path} import ${name}; ${name}`);
- Arguments:
-
- Returns:
any
Example
pyodide.pyimport("math.comb")(4, 2) // returns 4 choose 2 = 6
-
pyodide.registerComlink(Comlink)#
Tell Pyodide about Comlink.
Necessary to enable importing Comlink proxies into Python.
- Arguments:
-
-
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 wont have much effect unless you also delete the imported
module from sys.modules. This calls
register_js_module().
Any attributes of the JavaScript objects which are themselves objects will
be treated as submodules:
pyodide.registerJsModule("mymodule", { submodule: { value: 7 } });
pyodide.runPython(`
from mymodule.submodule import value
assert value == 7
`);
If you wish to prevent this, try the following instead:
const sys = pyodide.pyimport("sys");
sys.modules.set("mymodule", { obj: { value: 7 } });
pyodide.runPython(`
from mymodule import obj
assert obj.value == 7
# attempting to treat obj as a submodule raises ModuleNotFoundError:
# "No module named 'mymodule.obj'; 'mymodule' is not a package"
from mymodule.obj import value
`);
- Arguments:
-
-
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 doesnt end with a semicolon), the value of the
expression is returned.
- Arguments:
code (string) The Python code to run
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.
options.filename (string) An optional string to use as the file name. Defaults to "<exec>". If a custom file name is given, the traceback for any exception that is thrown will show source lines (unless the given file name starts with < and ends with >).
- Returns:
any The result of the Python code translated to JavaScript. See the documentation for eval_code() for more info.
Example
async function main(){
const pyodide = await loadPyodide();
console.log(pyodide.runPython("1 + 2"));
// 3
const globals = pyodide.toPy({ x: 3 });
console.log(pyodide.runPython("x + 1", { globals }));
// 4
const locals = pyodide.toPy({ arr: [1, 2, 3] });
console.log(pyodide.runPython("sum(arr)", { locals }));
// 6
}
main();
-
async pyodide.runPythonAsync(code, options)#
Run a Python code string with top level await using
eval_code_async() to evaluate the code. Returns a promise which
resolves when execution completes. If the last statement in the Python code
is an expression (and the code doesnt end with a semicolon), the returned
promise will resolve to the value of this expression.
For example:
let result = await pyodide.runPythonAsync(`
from js import fetch
response = await fetch("./pyodide-lock.json")
packages = await response.json()
# If final statement is an expression, its value is returned to JavaScript
len(packages.packages.object_keys())
`);
console.log(result); // 79
Python imports
Since pyodide 0.18.0, you must call loadPackagesFromImports() to
import any python packages referenced via import statements in your
code. This function will no longer do it for you.
- Arguments:
code (string) The Python code to run
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.
options.filename (string) An optional string to use as the file name. Defaults to "<exec>". If a custom file name is given, the traceback for any exception that is thrown will show source lines (unless the given file name starts with < and ends with >).
- Returns:
Promise<any> The result of the Python code translated to JavaScript.
-
pyodide.setDebug(debug)#
Turn on or off debug mode. In debug mode, some error messages are improved
at a performance cost.
- Arguments:
-
- Returns:
boolean The old value of the debug flag.
-
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 cant be overridden like
SIGKILL and SIGSEGV are ignored by default and can be used for any
purpose you like.
- Arguments:
-
-
pyodide.setStderr(options)#
Sets the standard error handler. A BatchedWriteHandler, a
RawWriteHandler, or a Writer can be provided.
See the documentation for these types for more information about how each
works. If no handler is provided, we restore the default handler. Passing a
Writer provides the most flexibility and the best performance.
- Arguments:
-
-
pyodide.setStdin(options)#
Set a stdin handler. See redirecting standard streams
for a more detailed explanation. There are two different possible interfaces
to implement a handler. Its also possible to select either the default
handler or an error handler that always returns an IO error.
passing a read function (see below),
passing a stdin function (see below),
passing error: true indicates that attempting to read from stdin
should always raise an IO error.
passing none of these sets the default behavior. In node, the default is
to read from stdin. In the browser, the default is to raise an error.
The functions on the options argument will be called with options
bound to this so passing an instance of a class as the options object
works as expected.
The interfaces that the handlers implement are as follows:
The read function is called with a Uint8Array argument. The
function should place the utf8-encoded input into this buffer and return
the number of bytes written. For instance, if the buffer was completely
filled with input, then return buffer.length. If a read function is
passed you may optionally also pass an fsync function which is called
when stdin is flushed.
The stdin function is called with zero arguments. 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, it is encoded into a buffer using
TextEncoder. By default, an EOF is appended after each string
or buffer returned. If this behavior is not desired, pass autoEOF: false.
- Arguments:
options.stdin (() => null | undefined | string | ArrayBuffer | Uint8Array | number) A stdin handler
options.read ((buffer: Uint8Array) => number) A read handler
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.autoEOF (boolean) Insert an EOF automatically after each string or buffer? (default true). This option can only be used with the stdin handler.
-
pyodide.setStdout(options)#
Sets the standard out handler. A BatchedWriteHandler, a
RawWriteHandler, or a Writer can be provided. See the
documentation for these types for more information about how each works. If
no handler is provided, we restore the default handler. Passing a Writer
provides the most flexibility and the best performance.
- Arguments:
-
Example
async function main(){
const pyodide = await loadPyodide();
pyodide.setStdout({ batched: (msg) => console.log(msg) });
pyodide.runPython("print('ABC')");
// 'ABC'
pyodide.setStdout({ raw: (byte) => console.log(byte) });
pyodide.runPython("print('ABC')");
// 65
// 66
// 67
// 10 (the ascii values for 'ABC' including a new line character)
}
main();
-
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.
-
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.
-
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 wont have much effect unless you also delete the
imported module from sys.modules. This calls
unregister_js_module().
- Arguments:
-
-
async pyodide.useNodeSockFS()#
Use Node.js native socket filesystem instead of Emscriptens SOCKFS.
- Returns:
Promise<void>
pyodide.ffi#
Foreign function interface classes. Can be used for typescript type annotations
or at runtime for instanceof checks.
To import types from pyodide.ffi you can use for example
import type { PyProxy } from "pyodide/ffi";
If you want to do an instance check, youll need to access the type via the
Pyodide API returned from loadPyodide():
const pyodide = loadPyodide();
const result = pyodide.runPython("... code here");
if (result instanceof pyodide.ffi.PyProxy) {
// Do something
}
-
TypedArray#
type: Int8Array | Uint8Array | Int16Array | Uint16Array | Int32Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array
-
class pyodide.ffi.PyAsyncGenerator()#
A PyProxy whose proxied Python object is an
asynchronous generator (i.e., it is an instance of
AsyncGenerator)
- Extends:
-
-
async 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}.
-
async PyAsyncGenerator.throw(exc)#
Throws an exception into the Generator.
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 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.[SymbolasyncIterator]()#
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:
-
-
async 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 its a generator for instance).
This will be used implicitly by for(let x of proxy){}.
- Arguments:
-
- 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:
-
-
async PyAwaitable.catch(onrejected)#
Attaches a callback for only the rejection of the Promise.
- Type parameters:
TResult
- Arguments:
-
- Returns:
Promise<any> A Promise for the completion of the callback.
-
async PyAwaitable.finally(onfinally)#
Attaches a callback that is invoked when the Promise is settled (fulfilled or rejected). The
resolved value cannot be modified from the callback.
- Arguments:
-
- Returns:
Promise<any> A Promise for the completion of the callback.
-
async PyAwaitable.then(onfulfilled, onrejected)#
Attaches callbacks for the resolution and/or rejection of the Promise.
- Type parameters:
-
- Arguments:
onfulfilled (null | (value: any) => TResult1 | PromiseLike<TResult1>) The callback to execute when the Promise is resolved.
onrejected (null | (reason: any) => TResult2 | PromiseLike<TResult2>) The callback to execute when the Promise is rejected.
- Returns:
Promise<TResult1 | TResult2> A Promise for the completion of which ever callback is executed.
-
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 cant handle suboffsets
anyways. In this case, you should use the toJs() api or
copy the buffer to one that doesnt 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.
When you are done with the buffer view, you have to call
release(). Alternatively, if you declare the buffer
with using pybuf = proxy.getBuffer(), JavaScript will automatically
release the buffer at the end of the current scope.
- 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. It has a [Symbol.dispose]() method
which is identical to the release method, so if you create the buffer with
using pybuf = proxy.getBuffer(); and JavaScript will automatically release
it at the end of the scope. 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:
-
- Returns:
any The result from the function call.
-
PyCallable.callKwargs(...jsargs)#
Call the function with keyword arguments. The last argument must be an
object with the keyword arguments.
- Arguments:
-
- Returns:
any
-
PyCallable.callKwargsRelaxed(...jsargs)#
Call the function with keyword arguments in a relaxed manner. The last
argument must be an object with the keyword arguments. Any extra arguments
will be ignored. This matches the behavior of JavaScript functions more
accurately.
Missing arguments are NOT filled with None. If too few arguments are
passed, this will still raise a TypeError. Also, if the same argument is
passed as both a keyword argument and a positional argument, it will raise
an error.
This uses pyodide.code.relaxed_call().
- Arguments:
-
- Returns:
any
-
async PyCallable.callPromising(...jsargs)#
Call the function with stack switching enabled. The last argument must be
an object with the keyword arguments. Functions called this way can use
run_sync() to block until an
Awaitable is resolved. Only works in runtimes
with JS Promise integration.
Experimental
This feature is not yet stable.
- Arguments:
-
- Returns:
Promise<any>
-
async PyCallable.callPromisingKwargs(...jsargs)#
Call the function with stack switching enabled. The last argument must be
an object with the keyword arguments. Functions called this way can use
run_sync() to block until an
Awaitable is resolved. Only works in runtimes
with JS Promise integration.
Experimental
This feature is not yet stable.
- Arguments:
-
- Returns:
Promise<any>
-
PyCallable.callRelaxed(...jsargs)#
Call the function in a relaxed manner. Any extra arguments will be
ignored. This matches the behavior of JavaScript functions more accurately.
Any extra arguments will be ignored. This matches the behavior of
JavaScript functions more accurately. Missing arguments are NOT filled
with None. If too few arguments are passed, this will still raise a
TypeError.
This uses pyodide.code.relaxed_call().
- Arguments:
-
- Returns:
any
-
PyCallable.callWithOptions(options, ...jsargs)#
Call the Python function. The first parameter controls various parameters
that change the way the call is performed.
- Arguments:
options.relaxed (boolean) If true, extra arguments are ignored instead of raising a TypeError.
options.kwargs (boolean) If true, the last argument is treated as a collection of keyword arguments.
options.promising (boolean) If true, the call is made with stack switching enabled. Not needed if the callee is an async Python function.
jsargs (any) Arguments to the Python function.
- 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:
-
- 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.[Symboliterator]()#
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:
-
- 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.PyMutableSequence()#
A PyProxy whose proxied Python object is an
MutableSequence (i.e., a list)
- Extends:
-
-
PyMutableSequence.copyWithin(target, start, end)#
The Array.copyWithin() method shallow copies part of a
PyMutableSequence to another location in the same PyMutableSequence
without modifying its length.
- Arguments:
target (number) Zero-based index at which to copy the sequence to.
start (number) Zero-based index at which to start copying elements from.
end (number) Zero-based index at which to end copying elements from.
- Returns:
any The modified PyMutableSequence.
-
PyMutableSequence.fill(value, start, end)#
The Array.fill() method changes all elements in an array to a
static value, from a start index to an end index.
- Arguments:
value (any) Value to fill the array with.
start (number) Zero-based index at which to start filling. Default 0.
end (number) Zero-based index at which to end filling. Default list.length.
- Returns:
any
-
PyMutableSequence.pop()#
The Array.pop() method removes the last element from a
PyMutableSequence.
- Returns:
any The removed element from the PyMutableSequence; undefined if the PyMutableSequence is empty.
-
PyMutableSequence.push(...elts)#
The Array.push() method adds the specified elements to the end of
a PyMutableSequence.
- Arguments:
-
- Returns:
any The new length property of the object upon which the method was called.
-
PyMutableSequence.reverse()#
The Array.reverse() method reverses a PyMutableSequence in
place.
- Returns:
PyMutableSequence A reference to the same PyMutableSequence
-
PyMutableSequence.shift()#
The Array.shift() method removes the first element from a
PyMutableSequence.
- Returns:
any The removed element from the PyMutableSequence; undefined if the PyMutableSequence is empty.
-
PyMutableSequence.sort(compareFn)#
The Array.sort() method sorts the elements of a
PyMutableSequence in place.
- Arguments:
-
- Returns:
PyMutableSequence A reference to the same PyMutableSequence
-
PyMutableSequence.splice(start, deleteCount, ...items)#
The Array.splice() method changes the contents of a
PyMutableSequence by removing or replacing existing elements and/or
adding new elements in place.
- Arguments:
-
- Returns:
any[] An array containing the deleted elements.
-
PyMutableSequence.unshift(...elts)#
The Array.unshift() method adds the specified elements to the
beginning of a PyMutableSequence.
- Arguments:
-
- Returns:
any The new length of the PyMutableSequence.
-
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: readonly 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:
-
-
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.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.create_pyproxies (boolean) If false, toJs() will throw a ConversionError rather than producing a PyProxy.
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).
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.eager_converter ((obj: PyProxy, convert: (obj: PyProxy) => any, cacheConversion: (obj: PyProxy, result: any) => void) => any) Optional callback to convert objects which gets called after str, int, float, bool, None, and JsProxy are converted but before any default conversions are applied to standard data structures. Its arguments are the same as dict_converter. See the documentation of to_js().
- Returns:
any The JavaScript object resulting from the conversion.
-
PyProxy.toString()#
Returns str(o) (unless pyproxyToStringRepr: true was passed to
loadPyodide() in which case it will return repr(o))
- Returns:
string
-
class pyodide.ffi.PyProxyWithGet()#
A PyProxy whose proxied Python object has a
__getitem__() method.
- Extends:
-
-
PyProxyWithGet.asJsJson()#
Returns the object treated as a json adaptor.
- With a JsonAdaptor:
property access / modification / deletion is implemented with
__getitem__(), __setitem__(), and
__delitem__() respectively.
If an attribute is accessed and the result implements
__getitem__() then the result will also be a json
adaptor.
For instance, JSON.stringify(proxy.asJsJson()) acts like an
inverse to Pythons json.loads().
- Returns:
PyProxy
-
PyProxyWithGet.get(key)#
This translates to the Python code obj[key].
- Arguments:
-
- 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:
-
- Returns:
boolean Is key present?
-
class pyodide.ffi.PyProxyWithLength()#
A PyProxy whose proxied Python object has a __len__()
method.
- Extends:
-
-
PyProxyWithLength.length#
type: readonly 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:
-
-
PyProxyWithSet.set(key, value)#
This translates to the Python code obj[key] = value.
- Arguments:
-
-
class pyodide.ffi.PySequence()#
A PyProxy whose proxied Python object is an
Sequence (i.e., a list)
- Extends:
-
-
PySequence.asJsJson()#
Returns the object treated as a json adaptor.
- With a JsonAdaptor:
property access / modification / deletion is implemented with
__getitem__(), __setitem__(), and
__delitem__() respectively.
If an attribute is accessed and the result implements
__getitem__() then the result will also be a json
adaptor.
For instance, JSON.stringify(proxy.asJsJson()) acts like an
inverse to Pythons json.loads().
- Returns:
PyProxy
-
PySequence.at(index)#
See Array.at(). Takes an integer value and returns the item at
that index.
- Arguments:
-
- Returns:
any The element in the Sequence matching the given index.
-
PySequence.concat(...rest)#
The Array.concat() method is used to merge two or more arrays.
This method does not change the existing arrays, but instead returns a new
array.
- Arguments:
-
- Returns:
any[] A new Array instance.
-
PySequence.entries()#
The Array.entries() method returns a new iterator object that
contains the key/value pairs for each index in the Sequence.
- Returns:
IterableIterator<[number, any]> A new iterator object.
-
PySequence.every(predicate, thisArg)#
See Array.every(). Tests whether every element in the Sequence
passes the test implemented by the provided function.
- Arguments:
predicate ((value: any, index: number, array: any[]) => unknown) A function to execute for each element in the Sequence. It should return a truthy value to indicate the element passes the test, and a falsy value otherwise.
thisArg (any) A value to use as this when executing predicate.
- Returns:
boolean
-
PySequence.filter(predicate, thisArg)#
See Array.filter(). Creates a shallow copy of a portion of a given
Sequence, filtered down to just the elements from the given array that pass
the test implemented by the provided function.
- Arguments:
predicate ((elt: any, index: number, array: any) => boolean) A function to execute for each element in the array. It should return a truthy value to keep the element in the resulting array, and a falsy value otherwise.
thisArg (any) A value to use as this when executing predicate.
- Returns:
any[]
-
PySequence.find(predicate, thisArg)#
The Array.find() method returns the first element in the provided
array that satisfies the provided testing function.
- Arguments:
predicate ((value: any, index: number, obj: any[]) => any) A function to execute for each element in the Sequence. It should return a truthy value to indicate a matching element has been found, and a falsy value otherwise.
thisArg (any) A value to use as this when executing predicate.
- Returns:
any The first element in the Sequence that satisfies the provided testing function.
-
PySequence.findIndex(predicate, thisArg)#
The Array.findIndex() method returns the index of the first
element in the provided array that satisfies the provided testing function.
- Arguments:
predicate ((value: any, index: number, obj: any[]) => any) A function to execute for each element in the Sequence. It should return a truthy value to indicate a matching element has been found, and a falsy value otherwise.
thisArg (any) A value to use as this when executing predicate.
- Returns:
number The index of the first element in the Sequence that satisfies the provided testing function.
-
PySequence.forEach(callbackfn, thisArg)#
See Array.forEach(). Executes a provided function once for each
Sequence element.
- Arguments:
-
-
PySequence.includes(elt)#
The Array.includes() method determines whether a Sequence
includes a certain value among its entries, returning true or false as
appropriate.
- Arguments:
-
- Returns:
any
-
PySequence.indexOf(elt, fromIndex)#
See Array.indexOf(). Returns the first index at which a given
element can be found in the Sequence, or -1 if it is not present.
- Arguments:
elt (any) Element to locate in the Sequence.
fromIndex (number) Zero-based index at which to start searching, converted to an integer. Negative index counts back from the end of the Sequence.
- Returns:
number The first index of the element in the Sequence; -1 if not found.
-
PySequence.join(separator)#
See Array.join(). The Array.join() method creates and
returns a new string by concatenating all of the elements in the
Sequence.
- Arguments:
-
- Returns:
string A string with all Sequence elements joined.
-
PySequence.keys()#
The Array.keys() method returns a new iterator object that
contains the keys for each index in the Sequence.
- Returns:
IterableIterator<number> A new iterator object.
-
PySequence.lastIndexOf(elt, fromIndex)#
See Array.lastIndexOf(). Returns the last index at which a given
element can be found in the Sequence, or -1 if it is not present.
- Arguments:
elt (any) Element to locate in the Sequence.
fromIndex (number) Zero-based index at which to start searching backwards, converted to an integer. Negative index counts back from the end of the Sequence.
- Returns:
number The last index of the element in the Sequence; -1 if not found.
-
PySequence.map(callbackfn, thisArg)#
See Array.map(). Creates a new array populated with the results of
calling a provided function on every element in the calling Sequence.
- Type parameters:
U
- Arguments:
callbackfn ((elt: any, index: number, array: any) => U) A function to execute for each element in the Sequence. Its return value is added as a single element in the new array.
thisArg (any) A value to use as this when executing callbackFn.
- Returns:
U[]
-
PySequence.reduce(callbackfn, initialValue)#
See Array.reduce(). Executes a user-supplied reducer callback
function on each element of the Sequence, in order, passing in the return
value from the calculation on the preceding element. The final result of
running the reducer across all elements of the Sequence is a single value.
- Arguments:
callbackfn ((previousValue: any, currentValue: any, currentIndex: number, array: any) => any) A function to execute for each element in the Sequence. Its return value is discarded.
initialValue (any)
- Returns:
any
-
PySequence.reduceRight(callbackfn, initialValue)#
See Array.reduceRight(). Applies a function against an accumulator
and each value of the Sequence (from right to left) to reduce it to a
single value.
- Arguments:
callbackfn ((previousValue: any, currentValue: any, currentIndex: number, array: any) => any) A function to execute for each element in the Sequence. Its return value is discarded.
initialValue (any)
- Returns:
any
-
PySequence.slice(start, stop)#
See Array.slice(). The Array.slice() method returns a
shallow copy of a portion of a Sequence into a
new array object selected from start to stop (stop not included)
- Arguments:
start (number) Zero-based index at which to start extraction. Negative index counts back from the end of the Sequence.
stop (number) Zero-based index at which to end extraction. Negative index counts back from the end of the Sequence.
- Returns:
any A new array containing the extracted elements.
-
PySequence.some(predicate, thisArg)#
See Array.some(). Tests whether at least one element in the
Sequence passes the test implemented by the provided function.
- Arguments:
predicate ((value: any, index: number, array: any[]) => unknown) A function to execute for each element in the Sequence. It should return a truthy value to indicate the element passes the test, and a falsy value otherwise.
thisArg (any) A value to use as this when executing predicate.
- Returns:
boolean
-
PySequence.toJSON(this)#
- Arguments:
-
- Returns:
unknown[]
-
PySequence.values()#
The Array.values() method returns a new iterator object that
contains the values for each index in the Sequence.
- Returns:
IterableIterator<any> A new iterator object.
-
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_exc.
See type translations of errors for more
information.
Avoid leaking stack Frames
If you make a PyProxy of
sys.last_exc, 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 dont. The easiest way is to only handle the
exception in Python.
- Extends:
-
-
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.
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.canvas.getCanvas2D()#
Get the HTML5 canvas element used for 2D rendering. For now,
Emscripten only supports one canvas element, so getCanvas2D and getCanvas3D
are the same.
- Returns:
undefined | HTMLCanvasElement
-
pyodide.canvas.getCanvas3D()#
Get the HTML5 canvas element used for 3D rendering. For now,
Emscripten only supports one canvas element, so getCanvas2D and getCanvas3D
are the same.
- Returns:
undefined | HTMLCanvasElement
-
pyodide.canvas.setCanvas2D(canvas)#
Set the HTML5 canvas element to use for 2D rendering. For now,
Emscripten only supports one canvas element, so setCanvas2D and setCanvas3D
are the same.
- Arguments:
-
-
pyodide.canvas.setCanvas3D(canvas)#
Set the HTML5 canvas element to use for 3D rendering. For now,
Emscripten only supports one canvas element, so setCanvas2D and setCanvas3D
are the same.
- Arguments:
-