pyodide.ffi#

Exceptions:

ConversionError

An error thrown when conversion between JavaScript and Python fails.

JsException(*args, **kwargs)

A JavaScript Error.

Classes:

JsArray()

A JsProxy of an Array, NodeList, or TypedArray

JsAsyncGenerator()

A JavaScript AsyncGenerator

JsAsyncIterable()

A JavaScript async iterable object

JsAsyncIterator()

A JsProxy of a JavaScript async iterator.

JsBuffer()

A JsProxy of an array buffer or array buffer view

JsCallable()

JsDomElement()

JsDoubleProxy()

A double proxy created with create_proxy().

JsFetchResponse()

A JsFetchResponse object represents a Response to a fetch() request.

JsGenerator()

A JavaScript generator

JsIterable()

A JavaScript iterable object

JsIterator()

A JsProxy of a JavaScript iterator.

JsMap()

A JavaScript Map

JsMutableMap()

A JavaScript mutable map

JsPromise()

A JsProxy of a Promise or some other thenable JavaScript object.

JsProxy()

A proxy to make a JavaScript object behave like a Python object

JsTypedArray()

Functions:

create_once_callable(obj, /, *[, _may_syncify])

Wrap a Python Callable in a JavaScript function that can be called once.

create_proxy(obj, /, *[, capture_this, ...])

Create a JsProxy of a PyProxy.

destroy_proxies(pyproxies, /)

Destroy all PyProxies in a JavaScript array.

register_js_module(name, jsproxy)

Registers jsproxy as a JavaScript module named name.

to_js(obj, /, *[, depth, pyproxies, ...])

Convert the object to JavaScript.

unregister_js_module(name)

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

exception pyodide.ffi.ConversionError#

Bases: Exception

An error thrown when conversion between JavaScript and Python fails.

class pyodide.ffi.JsArray#

Bases: JsIterable[T], Generic[T], MutableSequence[T]

A JsProxy of an Array, NodeList, or TypedArray

append(object)#

Append object to the end of the list.

Parameters:

object (T) –

Return type:

None

count(x)#

Return the number of times x appears in the list.

Parameters:

x (T) –

Return type:

int

extend(other, /)#

Extend array by appending elements from the iterable.

Parameters:

other (Iterable[T]) –

Return type:

None

index(value, start=0, stop=9223372036854775807)#

Return first index at which value appears in the Array.

Raises ValueError if the value is not present.

Parameters:
  • value (T) –

  • start (int) –

  • stop (int) –

Return type:

int

insert(index, value)#

Insert an item at a given position.

The first argument is the index of the element before which to insert, so a.insert(0, x) inserts at the front of the list, and a.insert(len(a), x) is equivalent to a.append(x).

Parameters:
  • index (int) –

  • value (T) –

Return type:

None

pop(index=-1)#

Remove and return the item at index (default last).

Raises IndexError if list is empty or index is out of range.

Parameters:

index (int) –

Return type:

T

remove(value)#

Remove the first item from the list whose value is equal to x.

It raises a ValueError if there is no such item.

Parameters:

value (T) –

Return type:

None

reverse()#

Reverse the array in place.

Return type:

None

to_py(*, depth=-1, default_converter=None)#

Convert the JsProxy to a native Python object as best as possible.

See JavaScript to Python for more information.

Parameters:
  • depth (int) – Limit the depth of the conversion. If a shallow conversion is desired, set depth to 1.

  • default_converter (Optional[Callable[[JsProxy, Callable[[JsProxy], Any], Callable[[JsProxy, Any], None]], Any]]) – If present, this will be invoked whenever Pyodide does not have some built in conversion for the object. If default_converter raises an error, the error will be allowed to propagate. Otherwise, the object returned will be used as the conversion. default_converter takes three arguments. The first argument is the value to be converted.

Return type:

list[Any]

Examples

Here are a couple examples of converter functions. In addition to the normal conversions, convert Date to datetime:

from datetime import datetime
def default_converter(value, _ignored1, _ignored2):
    if value.constructor.name == "Date":
        return datetime.fromtimestamp(d.valueOf()/1000)
    return value

Don’t create any JsProxies, require a complete conversion or raise an error:

def default_converter(_value, _ignored1, _ignored2):
    raise Exception("Failed to completely convert object")

The second and third arguments are only needed for converting containers. The second argument is a conversion function which is used to convert the elements of the container with the same settings. The third argument is a “cache” function which is needed to handle self referential containers. Consider the following example. Suppose we have a Javascript Pair class:

class Pair {
    constructor(first, second){
        this.first = first;
        this.second = second;
    }
}

We can use the following default_converter to convert Pair to list:

def default_converter(value, convert, cache):
    if value.constructor.name != "Pair":
        return value
    result = []
    cache(value, result);
    result.append(convert(value.first))
    result.append(convert(value.second))
    return result

Note that we have to cache the conversion of value before converting value.first and value.second. To see why, consider a self referential pair:

let p = new Pair(0, 0);
p.first = p;

Without cache(value, result);, converting p would lead to an infinite recurse. With it, we can successfully convert p to a list such that l[0] is l.

class pyodide.ffi.JsAsyncGenerator#

Bases: JsAsyncIterable[T_co], Generic[T_co, T_contra, V_co]

A JavaScript AsyncGenerator

A JavaScript object is treated as an async generator if it’s Symbol.toStringTag is "AsyncGenerator". Most likely this will be because it is a true async generator produced by the JavaScript runtime, but it may be a custom object trying hard to pretend to be an async generator. It should have next(), return(), and throw() methods.

aclose()#

Raises a GeneratorExit at the point where the generator function was paused.

If the generator function then exits gracefully, is already closed, or raises GeneratorExit (by not catching the exception), aclose() returns to its caller. If the generator yields a value, a RuntimeError is raised. If the generator raises any other exception, it is propagated to the caller. aclose() does nothing if the generator has already exited due to an exception or normal exit.

Return type:

Awaitable[None]

asend(value, /)#

Resumes the execution and “sends” a value into the async generator function.

The value argument becomes the result of the current yield expression. The awaitable returned by the asend() method will return the next value yielded by the generator or raises StopAsyncIteration if the asynchronous generator returns. If the generator returned a value, this value is discarded (because in Python async generators cannot return a value).

When asend() is called to start the generator, the argument will be ignored. Unlike in Python, we cannot detect that the generator hasn’t started yet, and no error will be thrown if the argument of a not-started generator is not None.

Parameters:

value (T_contra) –

Return type:

Awaitable[T_co]

athrow(error, /)#

Resumes the execution and raises an exception at the point where the generator was paused.

The awaitable returned by athrow() method will return the next value yielded by the generator or raises StopAsyncIteration if the asynchronous generator returns. If the generator returned a value, this value is discarded (because in Python async generators cannot return a value). If the generator function does not catch the passed-in exception, or raises a different exception, then that exception propagates to the caller.

Parameters:

error (BaseException) –

Return type:

T_co

class pyodide.ffi.JsAsyncIterable#

Bases: JsProxy, Generic[T_co]

A JavaScript async iterable object

A JavaScript object is async iterable if it has a Symbol.asyncIterator method.

class pyodide.ffi.JsAsyncIterator#

Bases: JsProxy, Generic[T_co]

A JsProxy of a JavaScript async iterator.

An object is a JsAsyncIterator if it has a next() method and either has a Symbol.asyncIterator or has no Symbol.iterator

class pyodide.ffi.JsBuffer#

Bases: JsProxy

A JsProxy of an array buffer or array buffer view

assign(rhs, /)#

Assign from a Python buffer into the JavaScript buffer.

Parameters:

rhs (Any) –

Return type:

None

assign_to(to, /)#

Assign to a Python buffer from the JavaScript buffer.

Parameters:

to (Any) –

Return type:

None

from_file(file, /)#

Reads from a file into a buffer.

Will try to read a chunk of data the same size as the buffer from the current position of the file.

Example

>>> None 
>>> from pathlib import Path
>>> Path("file.bin").write_text("abc\x00123ttt")
10
>>> from js import Uint8Array
>>> # the JsProxy need to be pre-allocated
>>> x = Uint8Array.new(10)
>>> with open('file.bin', 'rb') as fh:
...    x.from_file(fh)

which is equivalent to

>>> x = Uint8Array.new(range(10))
>>> with open('file.bin', 'rb') as fh:
...    chunk = fh.read(x.byteLength)
...    x.assign(chunk)

but the latter copies the data twice whereas the former only copies the data once.

Parameters:

file (Union[IO[bytes], IO[str]]) –

Return type:

None

to_bytes()#

Convert a buffer to a bytes object.

Copies the data once.

Return type:

bytes

to_file(file, /)#

Writes a buffer to a file.

Will write the entire contents of the buffer to the current position of the file.

Example

>>> from js import Uint8Array 
>>> from pathlib import Path
>>> Path("file.bin").write_text("abc\x00123ttt")
10
>>> x = Uint8Array.new(range(10))
>>> with open('file.bin', 'wb') as fh:
...    x.to_file(fh)

This is equivalent to

>>> with open('file.bin', 'wb') as fh:
...    data = x.to_bytes()
...    fh.write(data)
10

but the latter copies the data twice whereas the former only copies the data once.

Parameters:

file (Union[IO[bytes], IO[str]]) –

Return type:

None

to_memoryview()#

Convert a buffer to a memoryview.

Copies the data once. This currently has the same effect as to_py().

Return type:

memoryview

to_string(encoding=None)#

Convert a buffer to a string object.

Copies the data twice.

The encoding argument will be passed to the TextDecoder constructor. It should be one of the encodings listed in the table here. The default encoding is utf8.

Parameters:

encoding (Optional[str]) –

Return type:

str

class pyodide.ffi.JsCallable#

Bases: JsProxy

class pyodide.ffi.JsDomElement#

Bases: JsProxy

class pyodide.ffi.JsDoubleProxy#

Bases: JsProxy

A double proxy created with create_proxy().

destroy()#

Destroy the proxy.

Return type:

None

unwrap()#

Unwrap a double proxy created with create_proxy() into the wrapped Python object.

Return type:

Any

exception pyodide.ffi.JsException(*args, **kwargs)#

Bases: JsProxy, Exception

A JavaScript Error.

These are pickleable unlike other JsProxies.

message: str#

The error message

name: str#

The name of the error type

classmethod new(*args)#

Construct a new instance of the JavaScript object

Parameters:

args (Any) –

Return type:

JsException

stack: str#

The JavaScript stack trace

class pyodide.ffi.JsFetchResponse#

Bases: JsProxy

A JsFetchResponse object represents a Response to a fetch() request.

class pyodide.ffi.JsGenerator#

Bases: JsIterable[T_co], Generic[T_co, T_contra, V_co]

A JavaScript generator

A JavaScript object is treated as a generator if its Symbol.toStringTag is "Generator". Most likely this will be because it is a true Generator produced by the JavaScript runtime, but it may be a custom object trying hard to pretend to be a generator. It should have next(), return() and throw() methods.

close()#

Raises a GeneratorExit at the point where the generator function was paused.

If the generator function then exits gracefully, is already closed, or raises GeneratorExit (by not catching the exception), close() returns to its caller. If the generator yields a value, a RuntimeError is raised. If the generator raises any other exception, it is propagated to the caller. close() does nothing if the generator has already exited due to an exception or normal exit.

Return type:

None

send(value)#

Resumes the execution and “sends” a value into the generator function.

The value argument becomes the result of the current yield expression. The send() method returns the next value yielded by the generator, or raises StopIteration if the generator exits without yielding another value. When send() is called to start the generator, the argument will be ignored. Unlike in Python, we cannot detect that the generator hasn’t started yet, and no error will be thrown if the argument of a not-started generator is not None.

Parameters:

value (T_contra) –

Return type:

T_co

throw(error, /)#

Raises an exception at the point where the generator was paused, and returns the next value yielded by the generator function.

If the generator exits without yielding another value, a StopIteration exception is raised. If the generator function does not catch the passed-in exception, or raises a different exception, then that exception propagates to the caller.

In typical use, this is called with a single exception instance similar to the way the raise keyword is used.

For backwards compatibility, however, a second signature is supported, following a convention from older versions of Python. The type argument should be an exception class, and value should be an exception instance. If the value is not provided, the type constructor is called to get an instance. If traceback is provided, it is set on the exception, otherwise any existing __traceback__ attribute stored in value may be cleared.

Parameters:

error (BaseException) –

Return type:

T_co

class pyodide.ffi.JsIterable#

Bases: JsProxy, Generic[T_co]

A JavaScript iterable object

A JavaScript object is iterable if it has a Symbol.iterator method.

class pyodide.ffi.JsIterator#

Bases: JsProxy, Generic[T_co]

A JsProxy of a JavaScript iterator.

An object is a JsAsyncIterator if it has a next() method and either has a Symbol.iterator or has no Symbol.asyncIterator.

class pyodide.ffi.JsMap#

Bases: JsIterable[KT], Generic[KT, VT_co], Mapping[KT, VT_co]

A JavaScript Map

To be considered a map, a JavaScript object must have a get method, it must have a size or a length property which is a number (idiomatically it should be called size) and it must be iterable.

get(key, default, /)#

If key in self, returns self[key]. Otherwise returns default.

Parameters:
  • key (KT) –

  • default (Optional[VT_co]) –

Return type:

VT_co

items()#

Return a ItemsView for the map.

Return type:

ItemsView[KT, VT_co]

keys()#

Return a KeysView for the map.

Return type:

KeysView[KT]

values()#

Return a ValuesView for the map.

Return type:

ValuesView[VT_co]

class pyodide.ffi.JsMutableMap#

Bases: JsMap[KT, VT], Generic[KT, VT], MutableMapping[KT, VT]

A JavaScript mutable map

To be considered a mutable map, a JavaScript object must have a get method, a has method, a size or a length property which is a number (idiomatically it should be called size) and it must be iterable.

Instances of the JavaScript builtin Map class are JsMutableMap s. Also proxies returned by JsProxy.as_object_map() are instances of JsMap .

clear()#

Empty out the map entirely.

Return type:

None

pop(key, default=None, /)#

If key in self, return self[key] and remove key from self. Otherwise returns default.

Parameters:
  • key (KT) –

  • default (Optional[VT]) –

Return type:

VT

popitem()#

Remove some arbitrary key, value pair from the map and returns the (key, value) tuple.

Return type:

tuple[KT, VT]

setdefault(key, default=None)#

If key in self, return self[key]. Otherwise sets self[key] = default and returns default.

Parameters:
  • key (KT) –

  • default (Optional[VT]) –

Return type:

VT

update(other=None, /, **kwargs)#

Updates self from other and kwargs.

Parameters:
  • other (Mapping[KT, VT] | Iterable[tuple[KT, VT]]) – Either a mapping or an iterable of pairs. This can be left out.

  • kwargs (VT) – Extra key-values pairs to insert into the map. Only usable for inserting extra strings.

Return type:

None

If other is present and is a Mapping or has a keys method, does

for k in other:
    self[k] = other[k]

If other is present and lacks a keys method, does

for (k, v) in other:
    self[k] = v

In all cases this is followed by:

for (k, v) in kwargs.items():
    self[k] = v
class pyodide.ffi.JsPromise#

Bases: JsProxy, Generic[T]

A JsProxy of a Promise or some other thenable JavaScript object.

A JavaScript object is considered to be a Promise if it has a then method.

catch(onrejected, /)#

The Promise.catch() API, wrapped to manage the lifetimes of the handler.

Pyodide will automatically release the references to the handler when the promise resolves.

Parameters:

onrejected (Callable[[BaseException], Union[Awaitable[S], S]]) –

Return type:

JsPromise[S]

finally_(onfinally, /)#

The Promise.finally() API, wrapped to manage the lifetimes of the handler.

Pyodide will automatically release the references to the handler when the promise resolves. Note the trailing underscore in the name; this is needed because finally is a reserved keyword in Python.

Parameters:

onfinally (Callable[[], None]) –

Return type:

JsPromise[T]

then(onfulfilled, onrejected=None, /)#

The Promise.then() API, wrapped to manage the lifetimes of the handlers. Pyodide will automatically release the references to the handlers when the promise resolves.

Parameters:
Return type:

JsPromise[S]

class pyodide.ffi.JsProxy#

Bases: object

A proxy to make a JavaScript object behave like a Python object

For more information see the Type translations documentation. In particular, see the list of __dunder__ methods that are (conditionally) implemented on JsProxy.

as_object_map(*, hereditary=False)#

Returns a new JsProxy that treats the object as a map.

The methods __getitem__(), __setitem__(), __contains__(), __len__(), etc will perform lookups via object[key] or similar.

Note that len(x.as_object_map()) evaluates in O(n) time (it iterates over the object and counts how many ownKeys() it has). If you need to compute the length in O(1) time, use a real Map instead.

Parameters:

hereditary (bool) – If True, any “plain old objects” stored as values in the object will be wrapped in as_object_map themselves.

Return type:

JsMutableMap[str, Any]

Examples

>>> from pyodide.code import run_js 
>>> o = run_js("({x : {y: 2}})")

Normally you have to access the properties of o as attributes:

>>> o.x.y
2
>>> o["x"] # is not subscriptable
Traceback (most recent call last):
TypeError: 'pyodide.ffi.JsProxy' object is not subscriptable

as_object_map allows us to access the property with getitem:

>>> o.as_object_map()["x"].y
2

The inner object is not subscriptable because hereditary is False:

>>> o.as_object_map()["x"]["y"]
Traceback (most recent call last):
TypeError: 'pyodide.ffi.JsProxy' object is not subscriptable

When hereditary is True, the inner object is also subscriptable:

>>> o.as_object_map(hereditary=True)["x"]["y"]
2
js_id: int#

An id number which can be used as a dictionary/set key if you want to key on JavaScript object identity.

If two JsProxy are made with the same backing JavaScript object, they will have the same js_id.

new(*args, **kwargs)#

Construct a new instance of the JavaScript object

Parameters:
  • args (Any) –

  • kwargs (Any) –

Return type:

JsProxy

object_entries()#

The JavaScript API Object.entries(object)

Return type:

JsArray[JsArray[Any]]

Examples

>>> from pyodide.code import run_js 
>>> js_obj = run_js("({first: 'aa', second: 22})")
>>> entries = js_obj.object_entries()
>>> [(key, val) for key, val in entries]
[('first', 'aa'), ('second', 22)]
object_keys()#

The JavaScript API Object.keys(object)

Return type:

JsArray[str]

Examples

>>> from pyodide.code import run_js 
>>> js_obj = run_js("({first: 1, second: 2, third: 3})")
>>> keys = js_obj.object_keys()
>>> list(keys)
['first', 'second', 'third']
object_values()#

The JavaScript API Object.values(object)

Return type:

JsArray[Any]

Examples

>>> from pyodide.code import run_js 
>>> js_obj = run_js("({first: 1, second: 2, third: 3})")
>>> values = js_obj.object_values()
>>> list(values)
[1, 2, 3]
to_py(*, depth=-1, default_converter=None)#

Convert the JsProxy to a native Python object as best as possible.

See JavaScript to Python for more information.

Parameters:
  • depth (int) – Limit the depth of the conversion. If a shallow conversion is desired, set depth to 1.

  • default_converter (Optional[Callable[[JsProxy, Callable[[JsProxy], Any], Callable[[JsProxy, Any], None]], Any]]) – If present, this will be invoked whenever Pyodide does not have some built in conversion for the object. If default_converter raises an error, the error will be allowed to propagate. Otherwise, the object returned will be used as the conversion. default_converter takes three arguments. The first argument is the value to be converted.

Return type:

Any

Examples

Here are a couple examples of converter functions. In addition to the normal conversions, convert Date to datetime:

from datetime import datetime
def default_converter(value, _ignored1, _ignored2):
    if value.constructor.name == "Date":
        return datetime.fromtimestamp(d.valueOf()/1000)
    return value

Don’t create any JsProxies, require a complete conversion or raise an error:

def default_converter(_value, _ignored1, _ignored2):
    raise Exception("Failed to completely convert object")

The second and third arguments are only needed for converting containers. The second argument is a conversion function which is used to convert the elements of the container with the same settings. The third argument is a “cache” function which is needed to handle self referential containers. Consider the following example. Suppose we have a Javascript Pair class:

class Pair {
    constructor(first, second){
        this.first = first;
        this.second = second;
    }
}

We can use the following default_converter to convert Pair to list:

def default_converter(value, convert, cache):
    if value.constructor.name != "Pair":
        return value
    result = []
    cache(value, result);
    result.append(convert(value.first))
    result.append(convert(value.second))
    return result

Note that we have to cache the conversion of value before converting value.first and value.second. To see why, consider a self referential pair:

let p = new Pair(0, 0);
p.first = p;

Without cache(value, result);, converting p would lead to an infinite recurse. With it, we can successfully convert p to a list such that l[0] is l.

typeof: str#

Returns the JavaScript type of the JsProxy.

Corresponds to typeof obj; in JavaScript. You may also be interested in the constructor attribute which returns the type as an object.

class pyodide.ffi.JsTypedArray#

Bases: JsBuffer, JsArray[int]

pyodide.ffi.create_once_callable(obj, /, *, _may_syncify=False)#

Wrap a Python Callable in a JavaScript function that can be called once.

After being called the proxy will decrement the reference count of the Callable. The JavaScript function also has a destroy API that can be used to release the proxy without calling it.

Parameters:
Return type:

JsOnceCallable

pyodide.ffi.create_proxy(obj, /, *, capture_this=False, roundtrip=True)#

Create a JsProxy of a PyProxy.

This allows explicit control over the lifetime of the PyProxy from Python: call the destroy() API when done.

Parameters:
  • obj (Any) – The object to wrap.

  • capture_this (bool) – If the object is callable, should this be passed as the first argument when calling it from JavaScript.

  • roundtrip (bool) –

    When the proxy is converted back from JavaScript to Python, if this is True it is converted into a double proxy. If False, it is unwrapped into a Python object. In the case that roundtrip is True it is possible to unwrap a double proxy with the JsDoubleProxy.unwrap() method. This is useful to allow easier control of lifetimes from Python:

    from js import o
    d = {}
    o.d = create_proxy(d, roundtrip=True)
    o.d.destroy() # Destroys the proxy created with create_proxy
    

    With roundtrip=False this would be an error.

Return type:

JsDoubleProxy

pyodide.ffi.destroy_proxies(pyproxies, /)#

Destroy all PyProxies in a JavaScript array.

pyproxies must be a JavaScript Array of PyProxies. Intended for use with the arrays created from the “pyproxies” argument of toJs() and to_js(). This method is necessary because indexing the Array from Python automatically unwraps the PyProxy into the wrapped Python object.

Parameters:

pyproxies (JsArray[Any]) –

Return type:

None

pyodide.ffi.register_js_module(name, jsproxy)#

Registers jsproxy as a JavaScript module named name. The 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 is called by the JavaScript API pyodide.registerJsModule().

Parameters:
  • name (str) – Name of js module

  • jsproxy (Any) – JavaScript object backing the module

Return type:

None

pyodide.ffi.to_js(obj, /, *, depth=-1, pyproxies=None, create_pyproxies=True, dict_converter=None, default_converter=None)#

Convert the object to JavaScript.

This is similar to toJs(), but for use from Python. If the object can be implicitly translated to JavaScript, it will be returned unchanged. If the object cannot be converted into JavaScript, this method will return a JsProxy of a PyProxy, as if you had used create_proxy().

See Python to JavaScript for more information.

Parameters:
  • obj (Any) – The Python object to convert

  • depth (int) – The maximum depth to do the conversion. Negative numbers are treated as infinite. Set this to 1 to do a shallow conversion.

  • pyproxies (Optional[JsProxy]) – Should be a JavaScript Array. If provided, any PyProxies generated will be stored here. You can later use destroy_proxies() if you want to destroy the proxies from Python (or from JavaScript you can just iterate over the Array and destroy the proxies).

  • create_pyproxies (bool) – If you set this to False, to_js() will raise an error rather than creating any pyproxies.

  • dict_converter (Optional[Callable[[Iterable[JsArray[Any]]], JsProxy]]) –

    This converter if provided receives a (JavaScript) iterable of (JavaScript) pairs [key, value]. It is expected to return the desired result of the dict conversion. Some suggested values for this argument:

    • js.Map.new – similar to the default behavior

    • js.Array.from – convert to an array of entries

    • js.Object.fromEntries – convert to a JavaScript object

  • default_converter (Optional[Callable[[Any, Callable[[Any], JsProxy], Callable[[Any, JsProxy], None]], JsProxy]]) – If present will be invoked whenever Pyodide does not have some built in conversion for the object. If default_converter raises an error, the error will be allowed to propagate. Otherwise, the object returned will be used as the conversion. default_converter takes three arguments. The first argument is the value to be converted.

Return type:

Any

Examples

>>> from js import Object, Map, Array 
>>> from pyodide.ffi import to_js 
>>> js_object = to_js({'age': 20, 'name': 'john'}) 
>>> js_object 
[object Map]
>>> js_object.keys(), js_object.values() 
KeysView([object Map]) ValuesView([object Map]) 
>>> [(k, v) for k, v in zip(js_object.keys(), js_object.values())] 
[('age', 20), ('name', 'john')]
>>> js_object = to_js({'age': 20, 'name': 'john'}, dict_converter=Object.fromEntries) 
>>> js_object.age == 20 
True
>>> js_object.name == 'john' 
True
>>> js_object 
[object Object]
>>> js_object.hasOwnProperty("age") 
True
>>> js_object.hasOwnProperty("height") 
False
>>> js_object = to_js({'age': 20, 'name': 'john'}, dict_converter=Array.from_) 
>>> [item for item in js_object] 
[age,20, name,john]
>>> js_object.toString() 
age,20,name,john
>>> class Bird: pass 
>>> converter = lambda value, convert, cache: Object.new(size=1, color='red') if isinstance(value, Bird) else None 
>>> js_nest = to_js([Bird(), Bird()], default_converter=converter) 
>>> [bird for bird in js_nest] 
[[object Object], [object Object]]
>>> [(bird.size, bird.color) for bird in js_nest] 
[(1, 'red'), (1, 'red')]

Here are some examples demonstrating the usage of the default_converter argument.

In addition to the normal conversions, convert JavaScript Date objects to datetime objects:

from datetime import datetime
from js import Date
def default_converter(value, _ignored1, _ignored2):
    if isinstance(value, datetime):
        return Date.new(value.timestamp() * 1000)
    return value

Don’t create any PyProxies, require a complete conversion or raise an error:

def default_converter(_value, _ignored1, _ignored2):
    raise Exception("Failed to completely convert object")

The second and third arguments are only needed for converting containers. The second argument is a conversion function which is used to convert the elements of the container with the same settings. The third argument is a “cache” function which is needed to handle self referential containers. Consider the following example. Suppose we have a Python Pair class:

class Pair:
    def __init__(self, first, second):
        self.first = first
        self.second = second

We can use the following default_converter to convert Pair to Array:

from js import Array

def default_converter(value, convert, cache):
    if not isinstance(value, Pair):
        return value
    result = Array.new()
    cache(value, result)
    result.push(convert(value.first))
    result.push(convert(value.second))
    return result

Note that we have to cache the conversion of value before converting value.first and value.second. To see why, consider a self referential pair:

p = Pair(0, 0); p.first = p;

Without cache(value, result);, converting p would lead to an infinite recurse. With it, we can successfully convert p to an Array such that l[0] === l.

pyodide.ffi.unregister_js_module(name)#

Unregisters a JavaScript module with given name that has been previously registered with pyodide.registerJsModule() or pyodide.ffi.register_js_module(). If a JavaScript module with that name does not already exist, will raise an error. If the module has already been imported, this won’t have much effect unless you also delete the imported module from sys.modules. This is called by the JavaScript API pyodide.unregisterJsModule().

Parameters:

name (str) – Name of the module to unregister

Return type:

None

Functions:

add_event_listener(elt, event, listener)

Wrapper for JavaScript's addEventListener() which automatically manages the lifetime of a JsProxy corresponding to the listener parameter.

clear_interval(interval_retval)

Wrapper for JavaScript's clearInterval() which automatically manages the lifetime of a JsProxy corresponding to the callback parameter.

clear_timeout(timeout_retval)

Wrapper for JavaScript's clearTimeout() which automatically manages the lifetime of a JsProxy corresponding to the callback parameter.

remove_event_listener(elt, event, listener)

Wrapper for JavaScript's removeEventListener() which automatically manages the lifetime of a JsProxy corresponding to the listener parameter.

set_interval(callback, interval)

Wrapper for JavaScript's setInterval() which automatically manages the lifetime of a JsProxy corresponding to the callback parameter.

set_timeout(callback, timeout)

Wrapper for JavaScript's setTimeout() which automatically manages the lifetime of a JsProxy corresponding to the callback param.

pyodide.ffi.wrappers.add_event_listener(elt, event, listener)#

Wrapper for JavaScript’s addEventListener() which automatically manages the lifetime of a JsProxy corresponding to the listener parameter.

Parameters:
Return type:

None

pyodide.ffi.wrappers.clear_interval(interval_retval)#

Wrapper for JavaScript’s clearInterval() which automatically manages the lifetime of a JsProxy corresponding to the callback parameter.

Parameters:

interval_retval (int | JsProxy) –

Return type:

None

pyodide.ffi.wrappers.clear_timeout(timeout_retval)#

Wrapper for JavaScript’s clearTimeout() which automatically manages the lifetime of a JsProxy corresponding to the callback parameter.

Parameters:

timeout_retval (int | JsProxy) –

Return type:

None

pyodide.ffi.wrappers.remove_event_listener(elt, event, listener)#

Wrapper for JavaScript’s removeEventListener() which automatically manages the lifetime of a JsProxy corresponding to the listener parameter.

Parameters:
Return type:

None

pyodide.ffi.wrappers.set_interval(callback, interval)#

Wrapper for JavaScript’s setInterval() which automatically manages the lifetime of a JsProxy corresponding to the callback parameter.

Parameters:
Return type:

int | JsProxy

pyodide.ffi.wrappers.set_timeout(callback, timeout)#

Wrapper for JavaScript’s setTimeout() which automatically manages the lifetime of a JsProxy corresponding to the callback param.

Parameters:
Return type:

int | JsProxy