Python API#

Using JavaScript from Python, with the pyjs module: everything below is available as pyjs.<name>. The API follows PEP 818 and pyodide: the same names are also importable as js, jstypes.ffi, pyodide.ffi and pyodide.code, so code written for pyodide runs unchanged.

import pyjs

pyjs.js.console.log("hello from python")
add = pyjs.js.Function("a", "b", "return a + b")
add(1, 2)  # 3

Accessing JavaScript#

Numbers, strings, booleans, undefined (None) and null (jsnull) are converted when they cross over; every other JavaScript value is a JSProxy in Python: attributes, items, calls, iteration and await go to JavaScript.

pyjs.js#
class pyjs_core.JSProxy#

A JavaScript value in Python (any object or function; numbers, strings, booleans, undefined and null become Python values instead).

Attribute access, proxy[key], calls, len, in, iteration, await and comparisons go to JavaScript. Depending on what the JavaScript object can do, the proxy also has the methods of JSArray, JSMap, JSCallable, JSPromise, … (isinstance works with those classes).

property js_id: int#

an int, equal for two proxies exactly if they are the same JavaScript object

new(*args: Any, **kwargs: Any) → Any#

JavaScript’s new proxy(*args) (only for functions / classes).

to_py(*, depth: int = -1, default_converter: Any = None) → Any#

A deep copy as Python objects: Array -> list, Map and plain Object -> dict, Set -> set, typed array / ArrayBuffer -> memoryview. See pyjs.to_py.

property typeof: str#

the JavaScript typeof of the object, e.g. "object"

pyjs.jsnull#
class pyjs.JSNull#

The type of jsnull, the Python value of JavaScript’s null.

JavaScript has two “nothing” values, undefined and null. Python has one, None, which stands for undefined. null is this separate object, so that both survive a round trip. Like None it is false in a condition and there is only one of it.

class pyjs.JSBigInt#

An int that is always converted to a JavaScript BigInt.

A plain int becomes a JavaScript number when that can hold it exactly and a BigInt only when it is too large. Use this type where JavaScript requires a BigInt also for small values. A BigInt coming from JavaScript arrives as this type. Arithmetic on it gives a JSBigInt again (JSBigInt(2) + 1 is JSBigInt(3)), as in JavaScript.

What a proxy can do#

A proxy gets the methods of the classes below that fit its JavaScript object (isinstance(proxy, JSArray) works too).

class pyjs.JSCallable#

The proxy of a JavaScript function or class.

  • proxy(1, 2) calls the function (the core does that, in C++)

  • proxy.new(1, 2) is JavaScript’s new proxy(1, 2): creates an instance of a class

  • a JavaScript function stored in a Python class works as a method, see __get__

class pyjs.JSArray#

A JavaScript Array. It behaves like a Python list: indexing with negative indices and slices, len, in, iteration, and the list methods below. The JavaScript methods (push, map, …) are available too, except where a list method has the same name (pop, reverse, index): there the Python meaning wins.

append(item)#

Add item at the end.

clear()#

Remove all items.

extend(items)#

Add every item of the iterable items at the end.

insert(index, item)#

Insert item before position index.

pop(index=-1)#

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

remove#
reverse()#

Reverse the order of the items, in place.

class pyjs.JSTypedArray#

A JavaScript typed array (Uint8Array, Float64Array, …): a JSBuffer whose items can be read and written by index and by slice. Its length is fixed.

class pyjs.JSBuffer#

A JavaScript typed array, DataView or ArrayBuffer: a block of bytes.

assign(source)#

Copy the bytes of the Python buffer source (bytes, memoryview, numpy array, …) into this JavaScript buffer. Both must have the same size in bytes and, for a typed array, the same item type.

assign_to(target)#

Copy the bytes of this JavaScript buffer into the writable Python buffer target (bytearray, numpy array, …). Both must have the same size in bytes and, for a typed array, the same item type.

to_bytes()#

A copy of the bytes, as bytes.

to_memoryview()#

The data as memoryview with the item type of the typed array (a Float64Array gives items of type "d").

It is a copy: the bytes are copied ONCE, out of the JavaScript buffer into a new Python bytes object (js_to_bytes; a JavaScript buffer lives outside the wasm memory, Python cannot look at it in place). The memoryview on top is no further copy, only a typed view of those bytes (cast). Changing the JavaScript buffer afterwards does not change the memoryview, and the other way round (use assign / assign_to to write).

to_string(encoding='utf-8')#

The bytes decoded as text. Bytes that are no valid text in that encoding are a ValueError.

class pyjs.JSMap#

A JavaScript object that works like a Map (it has get, has, size and can be iterated). It behaves like a read-only Python mapping: proxy[key], key in proxy, len, iteration over the keys, and the methods below.

get(key, default=None)#

The value for key, or default if there is no such key.

items()#

A view of the (key, value) pairs.

keys()#

A view of the keys.

values()#

A view of the values.

class pyjs.JSMutableMap#

A JSMap that can be changed (it also has set and delete): proxy[key] = value, del proxy[key] and the dict methods below.

clear()#

Remove all entries.

pop(key, *default)#

Remove key and return its value; without such a key: default if given, else KeyError.

popitem#
setdefault#
update#
class pyjs.JSPromise#

A JavaScript promise (anything with a then method): it can be awaited.

class pyjs.JSIterable#

A JavaScript object that can be iterated (for x in proxy).

class pyjs.JSIterator#

A JavaScript iterator (next(proxy)).

send(value)#

next(value) of the iterator: the next value, StopIteration at the end (like a Python generator’s send).

class pyjs.JSGenerator#

A JavaScript generator (an iterator that also has return and throw), with the methods of a Python generator.

close()#

Finish the generator early (JavaScript’s return()).

send(value)#

Resume the generator: its current yield evaluates to value. Returns the next yielded value; raises StopIteration at the end. (value gets a lasting proxy: the generator may keep it.)

throw(exc, value=None, traceback=None)#

Raise an exception inside the generator, at its current yield. Returns the next yielded value.

class pyjs.JSAsyncIterable#

A JavaScript object with [Symbol.asyncIterator]: async for x in proxy.

class pyjs.JSAsyncIterator#

A JavaScript iterator whose next() returns promises: await anext(proxy).

class pyjs.JSAsyncGenerator#

A JavaScript async generator, with the methods of a Python async generator.

async aclose()#

Like JSGenerator.close; to be awaited.

asend(value)#

Like JSGenerator.send; to be awaited.

athrow(exc, value=None, traceback=None)#

Like JSGenerator.throw; to be awaited.

class pyjs.JSDoubleProxy#

What create_proxy(obj) returns: a proxy of a proxy.

Two kinds of proxies cross the border:

  • a PyProxy is how JavaScript sees a Python object

  • a JSProxy is how Python sees a JavaScript object

create_proxy(obj) makes a PyProxy for the Python object obj that lives until it is destroyed explicitly (normally a PyProxy passed to a JavaScript function is destroyed when the call returns). That PyProxy is a JavaScript object, so Python can only hold it through a JSProxy. The result is a JSProxy of a PyProxy of obj: a double proxy:

Python                     JavaScript
JSDoubleProxy  --------->  PyProxy  --------->  obj (Python)

Why it is useful: Python keeps a handle on the JavaScript side of the reference. Pass it to JavaScript (button.addEventListener("click", proxy)): JavaScript gets the PyProxy and calls obj through it. Later proxy.destroy() releases the PyProxy and with it the reference to obj, which can then be freed. proxy.unwrap() gives obj back.

unwrap()#

The Python object behind the two proxies: create_proxy(obj) .unwrap() is obj.

Python objects for JavaScript#

A Python object passed to a JavaScript function is only usable during that call. For JavaScript to keep it (an event handler, a callback stored for later), make a proxy that lasts.

pyjs.create_proxy(obj, *, roundtrip=True)#

Give JavaScript a lasting reference to the Python object obj.

A Python object passed to a JavaScript function is normally only usable by JavaScript during that call (its proxy is destroyed when the call returns, so that nothing leaks). When JavaScript has to keep it (an event handler, a callback called later, a value stored in a JavaScript object) pass create_proxy(obj) instead.

The result must be released with its destroy() method once JavaScript does not need it any more; obj cannot be freed before that.

What the result is: always a JSDoubleProxy. The lasting reference is a JavaScript object (a PyProxy of obj), and Python can only hold a JavaScript object through a JSProxy: so a proxy (JSProxy) of a proxy (PyProxy) of obj. It is what you pass to JavaScript (JavaScript gets the PyProxy) and what you call destroy() on. See JSDoubleProxy.

roundtrip: what Python gets when this PyProxy comes BACK from JavaScript later, e.g. read from an Array it was stored in, or passed as argument to a Python function:

  • roundtrip=True (the default, as in pyodide): the JSDoubleProxy again. So code that finds the proxy again can still destroy it; proxy.unwrap() gives obj.

  • roundtrip=False: obj itself, as for any other PyProxy coming back. Convenient when Python only wants to use the object, but that value cannot destroy the PyProxy (keep the JSDoubleProxy for that).

import js
from pyjs import create_proxy

data = [1, 2]
arr = js.Array.new()

# roundtrip=True (the default): a JSDoubleProxy comes back
p = create_proxy(data)
arr.push(p)
back = arr[0]                 # a JSDoubleProxy of the same PyProxy as p
assert back.unwrap() is data
back.destroy()                # (the same as p.destroy())

# roundtrip=False: the object itself comes back
p = create_proxy(data, roundtrip=False)
arr[0] = p
assert arr[0] is data
p.destroy()                   # only p can destroy it

Example:

import js
from pyjs import create_proxy

def on_click(event):
    print("clicked")

button = js.document.createElement("button")
handler = create_proxy(on_click)
button.addEventListener("click", handler)
button.click()                # prints "clicked"
button.removeEventListener("click", handler)
handler.destroy()
pyjs.create_once_callable(func)#

A JavaScript function that calls the Python callable func, once.

Like create_proxy for a callback that is called exactly one time (a timeout, a promise callback): the reference to func is released by that call, nothing has to be destroyed by hand. A second call raises an error.

pyjs.destroy_proxies(proxies)#

Destroy every proxy of proxies. Two kinds of argument:

  • a Python list (any iterable) of create_proxy results: each is destroyed with its destroy()

  • a JavaScript Array, which Python sees as one JSProxy: the Array that to_js(obj, pyproxies=arr) filled with the PyProxies it created. Its items are destroyed in JavaScript (see _destroy_in_js).

Converting values#

pyjs.to_js(obj, *, depth=-1, pyproxies=None, create_pyproxies=True, dict_converter=None, default_converter=None, eager_converter=None)#

Convert a Python value into JavaScript objects (a deep copy).

list / tuple -> Array, dict -> Object, set -> Set, buffers (bytes, numpy arrays, …) -> typed array. None, bool, numbers, str and JSProxy objects are returned as they are: they are converted automatically when passed to JavaScript. Other objects become proxies, including other sequences (range, deque, …), as in pyodide: to_js(list(r)) copies one.

Parameters:
  • obj – the value to convert.

  • depth – how many levels of containers to convert, -1 for all. At most 200 levels of nesting are followed: a deeper structure raises RecursionError (the call stack of a browser is small).

  • pyproxies – a JavaScript Array (js.Array.new()). The proxies created for objects that cannot be converted are appended, so that the caller can destroy them later (destroy_proxies).

  • create_pyproxies – if False, raise ConversionError instead of creating a proxy.

  • dict_converter – what a dict becomes: called with a JavaScript array of [key, value] pairs, e.g. js.Map.new for a Map. Default: a plain Object.

  • default_converter – called as default_converter(obj, convert, cache_conversion) for objects that are none of the containers above, instead of creating a proxy.

  • eager_converter – like default_converter, but called for every container first.

Example:

import js
from pyjs import to_js

js_obj = to_js({"a": [1, 2]})
assert js.JSON.stringify(js_obj) == '{"a":[1,2]}'
js_map = to_js({"a": 1}, dict_converter=js.Map.new)
assert js_map.get("a") == 1
pyjs.to_py(obj, *, depth=-1, default_converter=None)#

Convert a JavaScript value into Python objects (a deep copy).

Parameters:
  • obj – a JSProxy. Any other value is returned as is, so this can be called on whatever JavaScript returned.

  • depth – how many levels of containers to convert, -1 for all. With depth=1 an array of arrays becomes a list of proxies. At most 200 levels of nesting are followed: a deeper structure raises RecursionError (the call stack of a browser is small).

  • default_converter – called as default_converter(js_obj, convert, cache_conversion) for objects that are none of the containers above; returns their conversion. convert(value) converts a nested value, cache_conversion(js_obj, py_obj) registers the result early (needed for self referencing objects).

Example:

import js
from pyjs import to_py

js_array = js.Function("return [1, 2, {a: 3}]")()
assert to_py(js_array) == [1, 2, {"a": 3}]
pyjs.buffer_to_js_typed_array(buffer, view=False)#

A JavaScript typed array for a contiguous 1d buffer of numbers (bytes, array.array, a numpy array, …); the item type decides which one (float64 -> Float64Array).

Parameters:
  • buffer – the buffer.

  • view – False: the typed array holds a copy of the items. True: it is a view of the memory of buffer, without copying. Fast, but only valid while buffer is alive and unchanged in size, and until the WebAssembly memory grows (any allocation can do that): use it right away and do not keep it. Only for writable buffers: a JavaScript typed array cannot be read-only, so a view of bytes (or any read-only buffer) would let JavaScript change an object Python assumes immutable. TypeError for those.

class pyjs.ConversionError#

A value cannot be converted: to_js with create_pyproxies=False, a dict key that has no JavaScript equivalent, …

Running JavaScript and Python code#

pyjs.run_js(code)#

Evaluate JavaScript code in the global scope and return the value of its last expression.

Example:

from pyjs import run_js

assert run_js("1 + 2") == 3
add = run_js("(a, b) => a + b")
assert add(1, 2) == 3
pyjs.eval_code(source, globals=None, locals=None, *, return_mode='last_expr', quiet_trailing_semicolon=True, filename='<exec>', flags=0, dedent=True)#

Run Python source and return the value of its last expression (None if it ends with a statement).

Parameters:
  • source – the code, any number of lines.

  • locals (globals /) – the namespaces to run in, as for exec (default: a new namespace).

  • return_mode – “last_expr” (the value of a last expression), “last_expr_or_assign” (also of a last assignment) or “none”.

  • quiet_trailing_semicolon – a last line ending with ; returns None.

  • filename – the file name in tracebacks.

  • flags – compiler flags (compile).

  • dedent – remove the indentation all lines share first.

Example:

from pyjs import eval_code

assert eval_code("x = 20\nx + 1") == 21
async pyjs.eval_code_async(source, globals=None, locals=None, *, return_mode='last_expr', quiet_trailing_semicolon=True, filename='<exec>', flags=0, dedent=True)#

Like eval_code, for code that uses await at the top level.

The code runs with module level semantics (like the asyncio REPL and IPython): assignments go to globals, each statement runs exactly once.

Waiting for promises: run_sync (JSPI)#

await works on JavaScript promises in async code. Plain (synchronous) Python code can block on a promise with run_sync, where the browser supports JSPI (JavaScript Promise Integration). Any number of Python call stacks can wait in run_sync at the same time; they continue in whatever order their promises settle.

pyjs.run_sync(awaitable)#

Block until awaitable is done and return its result (JSPI only).

awaitable is a JavaScript promise (or thenable) or a Python awaitable. The WebAssembly stack is suspended (JavaScript Promise Integration) until it settles: the browser event loop keeps running in the meantime. A rejected promise raises a JSException. Requires can_run_sync(), raises a RuntimeError otherwise.

Example:

import js
import pyjs

def page_status():
    # a plain (sync) function waiting for a JavaScript promise
    response = pyjs.run_sync(js.fetch(js.location.href))
    return response.status

page_status()  # 200
pyjs.can_run_sync() → bool#

Whether run_sync can be used here.

True if JSPI is used (see jspi_enabled) and the current Python code was entered from JavaScript in a way that allows suspending: e.g. a step of an asyncio task (the event loop enters with a promising call), but not a plain synchronous callback (an event handler, runPython, …). Any number of Python call stacks can be suspended in run_sync at the same time; they resume in any order.

pyjs.jspi_enabled() → bool#

Whether JSPI (JavaScript Promise Integration) is used: the browser supports it (WebAssembly.Suspending / WebAssembly.promising) and it was not switched off. Without JSPI, run_sync is not available.

The asyncio event loop#

class pyjs.WebLoop#

The asyncio event loop of pyjs (adapted from pyodide’s).

Schedules tasks on the browser event loop. Does no lifecycle management and runs forever.

run_forever cannot block like a normal event loop would: there is one thread, so blocking would stall the browser event loop and prevent anything from ever happening. run_until_complete blocks only where the Python stack can be suspended (JSPI, pyjs.can_run_sync), see there.

We defer all work to the browser event loop. To ensure that this event loop doesn’t stall out UI and other browser handling, each callback is scheduled on the browser event loop as a task (not as a microtask): call_soon runs the callback as a separate browser task as soon as possible (without the >= 4ms clamping of nested setTimeout(callback, 0)), call_later uses setTimeout(callback, delay).

See the asyncio event loop methods: https://docs.python.org/3/library/asyncio-eventloop.html#asyncio-event-loop

pyjs.set_main_loop_callback(py_callback, fps=0)#

Call py_callback(dt) repeatedly from the emscripten main loop (fps 0: once per browser animation frame).

pyjs.cancel_main_loop()#

Cancel the main loop callback.

Graphics: WebGL2 / OpenGL ES 3, SDL2#

The runtime contains emscripten’s WebGL2 (OpenGL ES 3) and SDL2 support, so extension modules using GLES 3 or SDL2 (e.g. via ctypes or C++) work in the browser. They render into the canvas set with set_canvas.

pyjs.set_canvas(canvas) → None#

Make canvas the target of emscripten’s GL / SDL / html5 code.

Sets Module.canvas (used by SDL2) and registers it as "#canvas" (used by emscripten_webgl_create_context("#canvas", ...) and html5 event functions), so C / C++ code in extension modules renders into it.

Parameters:

canvas – a JS HTMLCanvasElement (main thread) or OffscreenCanvas.

pyjs.request_animation_frame_loop(callback) → AnimationFrameLoop#

Call callback(time_ms) once per browser animation frame.

Uses emscripten_request_animation_frame_loop (requestAnimationFrame). The loop runs while callback returns something truthy; it stops when it returns something falsy, raises (the exception is printed), or the returned handle’s cancel() is called. Each frame is a synchronous call from JS into Python, like the asyncio task steps.

Parameters:

callback – callback(time_ms: float) -> bool.

Returns:

an AnimationFrameLoop handle (running, cancel()).

class pyjs.AnimationFrameLoop(callback)#

Handle of a loop started by request_animation_frame_loop.

cancel()#

Stop the loop before the next frame.

property running: bool#

True until the loop stopped (callback returned falsy, raised, or cancel).

JavaScript errors#

A value thrown by JavaScript (or a rejected promise that is awaited) is raised as JSException. Its name is the JavaScript error class ("TypeError", "AbortError", …), message its message.

class pyjs.JSException(js_error, message=None)#

A value thrown by JavaScript (usually an Error), raised in Python.

name#

the kind of error, the name property of the JavaScript error: "TypeError", "RangeError", "AbortError", … and "Error" for thrown values that have no name.

message#

the message property of the JavaScript error; for thrown values that are no errors, the value as text.

stack#

the JavaScript stack trace, if the error has one, else None.

js_error#

the thrown value itself: a JSProxy of the error object, or the Python value for a thrown string / number / …