Python API

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

Javascript Modules

By default there are two Javascript modules. More can be added with pyodide.registerJsModule. You can import these modules using the Python import statement in the normal way.

js

The global Javascript scope.

pyodide_js

The Javascript Pyodide module.

Exceptions:

JsException

A wrapper around a Javascript Error to allow it to be thrown in Python.

Classes:

JsProxy()

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

WebLoop()

A custom event loop for use in Pyodide.

WebLoopPolicy()

A simple event loop policy for managing WebLoop based event loops.

Functions:

repr_shorten(value[, limit, split, separator])

Compute the string representation of value and shorten it if necessary.

create_once_callable(obj)

Wrap a Python callable in a Javascript function that can be called once.

create_proxy(obj)

Create a JsProxy of a PyProxy.

eval_code(code[, globals, locals, …])

Runs a code string.

eval_code_async(code[, globals, locals, …])

Runs a code string asynchronously.

find_imports(code)

Finds the imports in a string of code

open_url(url)

Fetches a given URL

register_js_module(name, jsproxy)

Registers jsproxy as a Javascript module named name.

to_js(obj[, depth])

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.register_js_module.

exception pyodide.JsException

A wrapper around a Javascript Error to allow it to be thrown in Python. See Translating Errors.

property js_error

The original Javascript error

class pyodide.JsProxy

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

For more information see Type translations documentation.

assign(rhs: ReadBuffer)

Assign from a Python buffer into the Javascript buffer.

Present only if the wrapped Javascript object is an ArrayBuffer or an ArrayBuffer view.

assign_to(to: ReadWriteBuffer)

Assign to a Python buffer from the Javascript buffer.

Present only if the wrapped Javascript object is an ArrayBuffer or an ArrayBuffer view.

catch(onrejected: Callable)Promise

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

Present only if the wrapped Javascript object has a “then” method. Pyodide will automatically release the references to the handler when the promise resolves.

finally_(onfinally: Callable)Promise

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

Present only if the wrapped Javascript object has a “then” method. 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.

new(*args, **kwargs)pyodide.JsProxy

Construct a new instance of the Javascript object

object_entries()pyodide.JsProxy

The Javascript API Object.entries(object)

object_keys()pyodide.JsProxy

The Javascript API Object.keys(object)

object_values()pyodide.JsProxy

The Javascript API Object.values(object)

then(onfulfilled: Callable, onrejected: Callable)Promise

The Promise.then API, wrapped to manage the lifetimes of the handlers.

Present only if the wrapped Javascript object has a “then” method. Pyodide will automatically release the references to the handlers when the promise resolves.

to_py(depth: int = - 1)Any

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

By default does a deep conversion, if a shallow conversion is desired, you can use proxy.to_py(1). See Javascript to Python for more information.

console.repr_shorten(value: Any, limit: int = 1000, split: Optional[int] = None, separator: str = '...')

Compute the string representation of value and shorten it if necessary.

If it is longer than limit then return the firsts split characters and the last split characters seperated by ‘…’. Default value for split is limit // 2.

pyodide.create_once_callable(obj: Callable)pyodide.JsProxy

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.

pyodide.create_proxy(obj: Any)pyodide.JsProxy

Create a JsProxy of a PyProxy.

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

pyodide.eval_code(code: str, globals: Optional[Dict[str, Any]] = None, locals: Optional[Dict[str, Any]] = None, return_mode: str = 'last_expr', quiet_trailing_semicolon: bool = True, filename: str = '<exec>')Any

Runs a code string.

Parameters
  • code (str) – The Python code to run.

  • globals (dict) – The global scope in which to execute code. This is used as the globals parameter for exec. See the exec documentation for more info. If the globals is absent, it is set equal to a new empty dictionary.

  • locals (dict) –

    The local scope in which to execute code. This is used as the locals parameter for exec. As with exec, if locals is absent, it is set equal to globals. See the exec documentation for more info.

  • return_mode (str) –

    Specifies what should be returned, must be one of 'last_expr', 'last_expr_or_assign' or 'none'. On other values an exception is raised.

    • 'last_expr' – return the last expression

    • 'last_expr_or_assign' – return the last expression or the last assignment.

    • 'none' – always return None.

  • quiet_trailing_semicolon (bool) – Whether a trailing semicolon should ‘quiet’ the result or not. Setting this to True (default) mimic the CPython’s interpreter behavior ; whereas setting it to False mimic the IPython’s interpreter behavior.

  • filename (str) – The file name to use in error messages and stack traces

Returns

If the last nonwhitespace character of code is a semicolon return None. If the last statement is an expression, return the result of the expression. (Use the return_mode and quiet_trailing_semicolon parameters to modify this default behavior.)

Return type

Any

async pyodide.eval_code_async(code: str, globals: Optional[Dict[str, Any]] = None, locals: Optional[Dict[str, Any]] = None, return_mode: str = 'last_expr', quiet_trailing_semicolon: bool = True, filename: str = '<exec>')Any

Runs a code string asynchronously.

Uses PyCF_ALLOW_TOP_LEVEL_AWAIT to compile to code.

Parameters
  • code (str) – The Python code to run.

  • globals (dict) –

    The global scope in which to execute code. This is used as the globals parameter for exec. See the exec documentation for more info. If the globals is absent, it is set equal to a new empty dictionary.

  • locals (dict) –

    The local scope in which to execute code. This is used as the locals parameter for exec. As with exec, if locals is absent, it is set equal to globals. See the exec documentation for more info.

  • return_mode (str) –

    Specifies what should be returned, must be one of 'last_expr', 'last_expr_or_assign' or 'none'. On other values an exception is raised.

    • 'last_expr' – return the last expression

    • 'last_expr_or_assign' – return the last expression or the last assignment.

    • 'none' – always return None.

  • quiet_trailing_semicolon (bool) – Whether a trailing semicolon should ‘quiet’ the result or not. Setting this to True (default) mimic the CPython’s interpreter behavior ; whereas setting it to False mimic the IPython’s interpreter behavior.

  • filename (str) – The file name to use in error messages and stack traces

Returns

If the last nonwhitespace character of code is a semicolon return None. If the last statement is an expression, return the result of the expression. (Use the return_mode and quiet_trailing_semicolon parameters to modify this default behavior.)

Return type

Any

pyodide.find_imports(code: str)List[str]

Finds the imports in a string of code

Parameters

code (str) – the Python code to run.

Returns

A list of module names that are imported in the code.

Return type

List[str]

Examples

>>> from pyodide import find_imports
>>> code = "import numpy as np; import scipy.stats"
>>> find_imports(code)
['numpy', 'scipy']
pyodide.open_url(url: str)_io.StringIO

Fetches a given URL

Parameters

url (str) – URL to fetch

Returns

the contents of the URL.

Return type

io.StringIO

pyodide.register_js_module(name: str, jsproxy: pyodide.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 (JsProxy) – Javascript object backing the module

pyodide.to_js(obj: Any, depth: int = - 1)pyodide.JsProxy

Convert the object to Javascript.

This is similar to PyProxy.toJs, but for use from Python. If the object would 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 pyodide.create_proxy.

See Python to Javascript for more information.

pyodide.unregister_js_module(name: str)

Unregisters a Javascript module with given name that has been previously registered with pyodide.registerJsModule or pyodide.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 js module

class webloop.WebLoop

A custom event loop for use in Pyodide.

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

run_forever and run_until_complete cannot block like a normal event loop would because we only have one thread so blocking would stall the browser event loop and prevent anything from ever happening.

We defer all work to the browser event loop using the setTimeout function. To ensure that this event loop doesn’t stall out UI and other browser handling, we want to make sure that each task is scheduled on the browser event loop as a task not as a microtask. setTimeout(callback, 0) enqueues the callback as a task so it works well for our purposes.

See Event Loop Methods.

class webloop.WebLoopPolicy

A simple event loop policy for managing WebLoop based event loops.