JavaScript API
Contents
JavaScript API#
Backward compatibility of the API is not guaranteed at this point.
Globals#
Functions:
async |
Load the main Pyodide wasm module and initialize it. |
- globalThis.loadPyodide(options)#
Load the main Pyodide wasm module and initialize it.
Only one copy of Pyodide can be loaded in a given JavaScript global scope because Pyodide uses global variables to load packages. If an attempt is made to load a second copy of Pyodide,
loadPyodide
will throw an error. (This can be fixed once Firefox adopts support for ES6 modules in webworkers.)- Arguments
options._node_mounts (
string[]()
) –options.args (
string[]()
) –options.fullStdLib (
boolean()
) – Load the full Python standard library. Setting this to false excludes unvendored modules from the standard library. Default: falseoptions.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. Defaults to the url that pyodide is loaded from with the file name (pyodide.js or pyodide.mjs) removed. It is recommended that you leave this undefined, providing an incorrect value can cause broken behavior.options.jsglobals (
object()
) –options.lockFileURL (
string()
) – The URL from which Pyodide will load the Pyodide “repodata.json” lock file. Defaults to${indexURL}/repodata.json
. You can produce custom lock files withmicropip.freeze
options.stderr (
(msg: string) => void()
) – Override the standard error output callback. Default: undefinedoptions.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. Default: undefined
- Returns
Promise<PyodideInterface> – The pyodide module.
pyodide#
Attributes:
An alias to the Emscripten ERRNO_CODES map of standard error codes. |
|
An alias to the Emscripten File System API. |
|
An alias to the Emscripten Path API. |
|
The Pyodide version. |
|
An alias to the global Python namespace. |
|
The list of packages that Pyodide has loaded. |
|
An alias to the Python |
Functions:
Throws a KeyboardInterrupt error if a KeyboardInterrupt has been requested via the interrupt buffer. |
|
|
|
|
Is the argument a |
async |
Load a package or a list of packages over the network. |
async |
Inspect a Python code chunk and use |
async |
Mounts FileSystemDirectoryHandle in to the target directory. |
|
Imports a module and returns it. |
|
Tell Pyodide about Comlink. |
|
Registers the JavaScript object |
|
Runs a string of Python code from JavaScript, using |
async |
Run a Python code string with top level await using
|
|
Sets the interrupt buffer to be |
|
Convert the JavaScript object to a Python object as best as possible. |
|
Unpack an archive into a target directory. |
|
Unregisters a JavaScript module with given name that has been previously
registered with |
Classes:
A class to allow access to a Python data buffers from JavaScript. |
|
A JavaScript error caused by a Python exception. |
- pyodide.ERRNO_CODES#
type: any
An alias to the Emscripten ERRNO_CODES map of standard 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 ofFS.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
, andsplitPath
.
- pyodide.default#
type: string
The Pyodide version.
The version here follows PEP440 which is different from the one in package.json, as we want to compare this with the version of Pyodide Python package without conversion.
- pyodide.globals#
type: PyProxy
An alias to the global Python namespace.
For example, to access a variable called
foo
in the Python global scope, usepyodide.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, andpyodide.loadedPackages[package_name]
to access install location for a particularpackage_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.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.
- pyodide.initializeNativeFS(module)#
- Arguments
module (
Module()
) –
- pyodide.isPyProxy(jsobj)#
Is the argument a
PyProxy
?- Arguments
jsobj (
any()
) – Object to test.
- Returns
boolean (typeguard for PyProxy) – Is
jsobj
aPyProxy
?
- pyodide.loadPackage(names, options, errorCallbackDeprecated)#
Load a package or a list of packages over the network. This installs the package in the virtual filesystem. The package needs to be imported from Python before it can be used.
- Arguments
names (
string|PyProxy|string[]()
) – Either a single package name or URL or a list of them. URLs can be absolute or relative. The URLs must have file name<package-name>.js
and there must be a file called<package-name>.data
in the same directory. The argument can be aPyProxy
of a list, in which case the list will be converted to JavaScript and thePyProxy
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)errorCallbackDeprecated (
{}()
) –
- Returns
Promise<void> –
- pyodide.loadPackagesFromImports(code, options, errorCallbackDeprecated)#
Inspect a Python code chunk and use
pyodide.loadPackage()
to install any known packages that the code chunk imports. Uses the Python APIpyodide.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 callpyodide.loadPackage(['numpy'])
.- Arguments
code (
string()
) – The code to inspect.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)errorCallbackDeprecated (
{}()
) –
- Returns
Promise<void> –
- pyodide.mountNativeFS(path, fileSystemHandle)#
Mounts FileSystemDirectoryHandle in to the target directory.
- Arguments
path (
string()
) – The absolute path of the target mount directory. If the directory does not exist, it will be created.fileSystemHandle.isSameEntry (
Function()
) –fileSystemHandle.queryPermission (
Function()
) –fileSystemHandle.requestPermission (
Function()
) –
- Returns
Promise<NativeFS> –
- 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
- pyodide.registerComlink(Comlink)#
Tell Pyodide about Comlink. Necessary to enable importing Comlink proxies into Python.
- Arguments
Comlink (
any()
) –
- pyodide.registerJsModule(name, module)#
Registers the JavaScript object
module
as a JavaScript module namedname
. 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 fromsys.modules
. This calls the {any}`pyodide_py` APIpyodide.register_js_module()
.- Arguments
name (
string()
) – Name of the JavaScript module to addmodule (
object()
) – JavaScript object backing the module
- pyodide.runPython(code, options)#
Runs a string of Python code from JavaScript, using
pyodide.code.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.Positional globals argument
In Pyodide v0.19, this function took the globals parameter as a positional argument rather than as a named argument. In v0.20 this will still work but it is deprecated. It will be removed in v0.21.
- Arguments
code (
string()
) – Python code to evaluateoptions.globals (
PyProxy()
) – An optional Python dictionary to use as the globals. Defaults topyodide.globals
.
- Returns
any – The result of the Python code translated to JavaScript. See the documentation for
pyodide.code.eval_code
for more info.
- pyodide.runPythonAsync(code, options)#
Run a Python code string with top level await using
pyodide.code.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 doesn’t 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("./repodata.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.Positional globals argument
In Pyodide v0.19, this function took the globals parameter as a positional argument rather than as a named argument. In v0.20 this will still work but it is deprecated. It will be removed in v0.21.
- Arguments
code (
string()
) – Python code to evaluateoptions.globals (
PyProxy()
) – An optional Python dictionary to use as the globals. Defaults topyodide.globals
.
- Returns
Promise<any> – The result of the Python code translated to JavaScript.
- 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 aSharedArrayBuffer
shared with the main browser thread (or another worker). In that case, signalsignum
may be sent by writingsignum
into the interrupt buffer. Ifsignum
does not satisfy 0 <signum
<NSIG
it will be silently ignored. NSIG is 65 (internally signals are indicated by a bitflag).You can disable interrupts by calling setInterruptBuffer(undefined).
If you wish to trigger a
KeyboardInterrupt
, writeSIGINT
(a 2), into the interrupt buffer.By default
SIGINT
raises aKeyboardInterrupt
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 likeSIGKILL
andSIGSEGV
are ignored by default and can be used for any purpose you like.- Arguments
interrupt_buffer (
TypedArray()
) –
- pyodide.toPy(obj, options)#
Convert the JavaScript object to a Python object as best as possible.
This is similar to
JsProxy.to_py
but for use from JavaScript. If the object is immutable or aPyProxy
, 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()
) –options.depth (
number()
) – Optional argument to limit the depth of the conversion.options.defaultConverter (
(value: any, converter: {}, cacheConversion: {}) => any()
) – Optional argument to convert objects with no default conversion. See the documentation ofJsProxy.to_py
.
- Returns
any – The object converted to Python.
- pyodide.unpackArchive(buffer, format, options)#
Unpack an archive into a target directory.
Positional globals argument :class: warning
In Pyodide v0.19, this function took the extract_dir parameter as a positional argument rather than as a named argument. In v0.20 this will still work but it is deprecated. It will be removed in v0.21.
- Arguments
buffer (
TypedArray|ArrayBuffer()
) – 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()
orpyodide.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 fromsys.modules
. This calls thepyodide_py
APIpyodide.unregister_js_module()
.- Arguments
name (
string()
) – Name of the JavaScript module to remove
- class pyodide.PyBuffer()#
A class to allow access to a Python data buffers from JavaScript. These are produced by
PyProxy.getBuffer
and cannot be constructed directly. When you are done, release it with therelease
method. See 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])]);
Contiguity
If the buffer is not contiguous, the
data
TypedArray will contain data that is not part of the buffer. Modifying this data may lead to undefined behavior.Readonly buffers
If
buffer.readonly
istrue
, you should not modify the buffer. Modifying a readonly buffer may lead to undefined behavior.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 );
- PyBuffer.c_contiguous#
type: boolean
Is it C contiguous?
- PyBuffer.data#
type: TypedArray
The actual data. A typed array of an appropriate size backed by a segment of the WASM memory.
The
type
argument ofPyProxy.getBuffer
determines which sort ofTypedArray
this is. By defaultPyProxy.getBuffer
will look at the format string to determine the most appropriate option.
- PyBuffer.f_contiguous#
type: boolean
Is it Fortran contiguous?
- PyBuffer.format#
type: string
The format string for the buffer. See the Python documentation on format strings.
- PyBuffer.itemsize#
type: number
How large is each entry (in bytes)?
- PyBuffer.nbytes#
type: number
The total number of bytes the buffer takes up. This is equal to
buff.data.byteLength
.
- PyBuffer.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.
- PyBuffer.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]
atpybuf.data[pybuf.offset]
- PyBuffer.readonly#
type: boolean
If the data is readonly, you should not modify it. There is no way for us to enforce this, but it may cause very weird behavior.
- PyBuffer.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]
.
- PyBuffer.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 amultiIndexToIndex
function above.
- PyBuffer.release()#
Release the buffer. This allows the memory to be reclaimed.
- class pyodide.PythonError(message, error_address)#
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 Errors for more information.
Avoid Stack Frames
If you make a
PyProxy
ofsys.last_value
, you should be especially careful todestroy()
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.- Arguments
message (
string()
) –error_address (
number()
) –
PyProxy#
A PyProxy is an object that allows idiomatic use of a Python object from JavaScript. See Proxying from Python into JavaScript.
Attributes:
Functions:
This translates to the Python code |
|
|
The apply() method calls the specified function with a given this value, and arguments provided as an array (or an array-like object). |
|
The bind() method creates a new function that, when called, has its
|
|
Calls the function with a given this value and arguments provided individually. |
|
Call the function with key word arguments. |
Returns a |
|
async |
Runs |
|
Make a new PyProxy pointing to the same Python object. |
|
This translates to the Python code |
|
Destroy the |
async |
Runs |
|
This translates to the Python code |
|
Get a view of the buffer data which is usable from JavaScript. |
|
This translates to the Python code |
Check whether the PyProxy is awaitable. |
|
|
Check whether the PyProxy is a buffer. |
Check whether the PyProxy is a Callable. |
|
Check whether the PyProxy is iterable. |
|
Check whether the PyProxy is iterable. |
|
|
This translates to the Python code |
|
This translates to the Python code |
Check whether the |
|
Check whether the |
|
Check whether the |
|
Check whether the |
|
async |
Runs |
|
Converts the |
|
- PyProxy.[toStringTag]#
type: string
- PyProxy.length#
type: number
- PyProxy.type#
type: string
- PyProxy.[iterator]()#
This translates to the Python code
iter(obj)
. Return an iterator associated to the proxy. See the documentation for Symbol.iterator.Present only if the proxied Python object is iterable (i.e., has an
__iter__
method).This will be used implicitly by
for(let x of proxy){}
.- Returns
Iterator<any, any, any> –
- PyProxy.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 the JavaScript apply function.
Present only if the proxied Python object is callable.
- Arguments
thisArg (
any()
) – The this argument. Has no effect unless the PyProxy hascaptureThis
set. IfcaptureThis
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.
- PyProxy.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 the documentation for the JavaScript bind function.If the PyProxy does not have
captureThis
set, thethis
parameter will be discarded. If it does havecaptureThis
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 thethis
parameter to the target functionfunc
when the bound function is called.jsargs (
any()
) – Extra arguments to prepend to arguments provided to the bound function when invokingfunc
.
- Returns
PyProxy –
- PyProxy.call(thisArg, ...jsargs)#
Calls the function with a given this value and arguments provided individually. Like the JavaScript call function.
Present only if the proxied Python object is callable.
- Arguments
thisArg (
any()
) – Thethis
argument. Has no effect unless the PyProxy hascaptureThis
set. IfcaptureThis
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.
- PyProxy.callKwargs(...jsargs)#
Call the function with key word arguments. The last argument must be an object with the keyword arguments. Present only if the proxied Python object is callable.
- Arguments
jsargs (
any()
) –
- Returns
any –
- PyProxy.captureThis()#
Returns a
PyProxy
that passesthis
as the first argument to the Python function. The returnedPyProxy
has the internalcaptureThis
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.
- Returns
PyProxy – The resulting
PyProxy
. It has the same lifetime as the originalPyProxy
but passesthis
to the wrapped function. For example: .. code-block:: js 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
- PyProxy.catch(onRejected)#
Runs
asyncio.ensure_future(awaitable)
and executesonRejected(error)
if the future fails.See the documentation for Promise.catch.
Present only if the proxied Python object is awaitable.
- Arguments
onRejected (
{}()
) – A handler called with the error as an argument if the awaitable fails.
- Returns
Promise<any> – The resulting Promise.
- PyProxy.copy()#
Make a new PyProxy pointing to the same Python object. Useful if the PyProxy is destroyed somewhere else.
- Returns
PyProxy –
- PyProxy.delete(key)#
This translates to the Python code
del obj[key]
.Present only if the proxied Python object has a
__delitem__
method.- Arguments
key (
any()
) – The key to delete.
- PyProxy.destroy(destroyed_msg)#
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 todestroy
the proxy explicitly.- Arguments
destroyed_msg (
string()
) – The error message to print if use is attempted after destroying. Defaults to “Object has already been destroyed”.
- PyProxy.finally(onFinally)#
Runs
asyncio.ensure_future(awaitable)
and executesonFinally(error)
when the future resolves.See the documentation for Promise.finally.
Present only if the proxied Python object is awaitable.
- Arguments
onFinally (
{}()
) – A handler that is called with zero arguments when the awaitable resolves.
- Returns
Promise<any> – A Promise that resolves or rejects with the same result as the original Promise, but only after executing the
onFinally
handler.
- PyProxy.get(key)#
This translates to the Python code
obj[key]
.Present only if the proxied Python object has a
__getitem__
method.- Arguments
key (
any()
) – The key to look up.
- Returns
any – The corresponding value.
- PyProxy.getBuffer(type)#
Get a view of the buffer data which is usable from JavaScript. No copy is ever performed.
Present only if the proxied Python object supports the Python Buffer Protocol.
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 suboffets (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
. DataViews have 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 thePyBuffer.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 absentgetBuffer
will try to determine the appropriate output type based on the buffer format string.
- Returns
PyBuffer –
PyBuffer
- PyProxy.has(key)#
This translates to the Python code
key in obj
.Present only if the proxied Python object has a
__contains__
method.- Arguments
key (
any()
) – The key to check for.
- Returns
boolean – Is
key
present?
- PyProxy.isAwaitable()#
Check whether the PyProxy is awaitable. A Typescript type guard, if this function returns true Typescript considers the PyProxy to be a
Promise
.- Returns
boolean (typeguard for PyProxyAwaitable) –
- PyProxy.isBuffer()#
Check whether the PyProxy is a buffer. A Typescript type guard for
PyProxy.getBuffer
.- Returns
boolean (typeguard for PyProxyBuffer) –
- PyProxy.isCallable()#
Check whether the PyProxy is a Callable. A Typescript type guard, if this returns true then Typescript considers the Proxy to be callable of signature
(args... : any[]) => PyProxy | number | bigint | string | boolean | undefined
.- Returns
boolean (typeguard for PyProxyCallable) –
- PyProxy.isIterable()#
Check whether the PyProxy is iterable. A Typescript type guard for
PyProxy.[iterator]
.- Returns
boolean (typeguard for PyProxyIterable) –
- PyProxy.isIterator()#
Check whether the PyProxy is iterable. A Typescript type guard for
PyProxy.next
.- Returns
boolean (typeguard for PyProxyIterator) –
- PyProxy.new PyProxyClass()#
- PyProxy.next(arg=undefined)#
This translates to the Python code
next(obj)
. Returns the next value of the generator. See the documentation for Generator.prototype.next. The argument will be sent to the Python generator.This will be used implicitly by
for(let x of proxy){}
.Present only if the proxied Python object is a generator or iterator (i.e., has a
send
or__next__
method).- Arguments
arg (
any()
) –
- Returns
IteratorResult<any, any> – An Object with two properties:
done
andvalue
. When the generator yieldssome_value
,next
returns{done : false, value : some_value}
. When the generator raises aStopIteration(result_value)
exception,next
returns{done : true, value : result_value}
.
- PyProxy.set(key, value)#
This translates to the Python code
obj[key] = value
.Present only if the proxied Python object has a
__setitem__
method.- Arguments
key (
any()
) – The key to set.value (
any()
) – The value to set it to.
- PyProxy.supportsGet()#
Check whether the
PyProxy.get
method is available on this PyProxy. A Typescript type guard.- Returns
boolean (typeguard for PyProxyWithGet) –
- PyProxy.supportsHas()#
Check whether the
PyProxy.has
method is available on this PyProxy. A Typescript type guard.- Returns
boolean (typeguard for PyProxyWithHas) –
- PyProxy.supportsLength()#
Check whether the
PyProxy.length
getter is available on this PyProxy. A Typescript type guard.- Returns
boolean (typeguard for PyProxyWithLength) –
- PyProxy.supportsSet()#
Check whether the
PyProxy.set
method is available on this PyProxy. A Typescript type guard.- Returns
boolean (typeguard for PyProxyWithSet) –
- PyProxy.then(onFulfilled, onRejected)#
Runs
asyncio.ensure_future(awaitable)
, executesonFulfilled(result)
when theFuture
resolves successfully, executesonRejected(error)
when theFuture
fails. Will be used implicitly byawait obj
.See the documentation for Promise.then
Present only if the proxied Python object is awaitable.
- Arguments
onFulfilled (
{}()
) – A handler called with the result as an argument if the awaitable succeeds.onRejected (
{}()
) – A handler called with the error as an argument if the awaitable fails.
- Returns
Promise<any> – The resulting Promise.
- 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 useproxy.toJs({depth : 1})
. See Explicit Conversion of PyProxy for more info.- Arguments
options.create_pyproxies (
boolean()
) – If false,toJs
will throw aConversionError
rather than producing aPyProxy
.options.depth (
number()
) – How many layers deep to perform the conversion. Defaults to infiniteoptions.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: {}, cacheConversion: {}) => any()
) – Optional argument to convert objects with no default conversion. See the documentation ofpyodide.ffi.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 entries, and(it) => new Map(it)
converts it to aMap
(which is the default behavior).
- Returns
any – The JavaScript object resulting from the conversion.
- PyProxy.toString()#
- Returns
string –