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.

Classes:

CodeRunner(source, *, return_mode[, mode])

This class allows fine control over the execution of a code block.

JsProxy()

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

Console(globals, *, stdout_callback, …)

Interactive Pyodide console

ConsoleFuture(syntax_check, …)

A future with extra fields used as the return value for Console apis.

PyodideConsole(globals, *, stdout_callback, …)

A subclass of Console that uses pyodide.loadPackagesFromImports before running the code.

WebLoop()

A custom event loop for use in Pyodide.

WebLoopPolicy()

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

Exceptions:

ConversionError

An error thrown when conversion between Javascript and Python fails.

JsException

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

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.

destroy_proxies(pyproxies)

Destroy all PyProxies in a Javascript array.

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

Runs a string as Python source code.

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

Runs a code string asynchronously.

find_imports(source)

Finds the imports in a Python source code string

open_url(url)

Fetches a given URL

register_js_module(name, jsproxy)

Registers jsproxy as a Javascript module named name.

should_quiet(source)

Should we suppress output?

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

class pyodide.CodeRunner(source: str, *, return_mode: str = 'last_expr', mode='exec', quiet_trailing_semicolon: bool = True, filename: str = '<exec>', flags: int = 0)

This class allows fine control over the execution of a code block.

It is primarily intended for REPLs and other sophisticated consumers that may wish to add their own AST transformations, separately signal to the user when parsing is complete, etc. The simpler eval_code and eval_code_async apis should be prefered when their flexibility suffices.

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

  • 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' by default.

    • '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) – Specifies whether a trailing semicolon should suppress the result or not. When this is True executing "1+1 ;" returns None, when it is False, executing "1+1 ;" return 2. True by default.

  • filename (str) – The file name to use in error messages and stack traces. '<exec>' by default.

  • mode (str) – The “mode” to compile in. One of "exec", "single", or "eval". Defaults to "exec". For most purposes it’s unnecessary to use this argument. See the documentation for the built in compile <https://docs.python.org/3/library/functions.html#compile> function.

  • flags (int) – The flags to compile with. See the documentation for the built in compile <https://docs.python.org/3/library/functions.html#compile> function.

  • Attributes

    astThe ast from parsing source. If you wish to do an ast transform,

    modify this variable before calling CodeRunner.compile.

    codeOnce you call CodeRunner.compile the compiled code will

    be avaible in the code field. You can modify this variable before calling CodeRunner.run to do a code transform.

compile()

Compile the current value of self.ast and store the result in self.code.

Can only be used once. Returns self (chainable).

run(globals: Optional[Dict[str, Any]] = None, locals: Optional[Dict[str, Any]] = None)

Executes self.code.

Can only be used after calling compile. The code may not use top level await, use CodeRunner.run_async for code that uses top level await.

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

  • locals (dict) –

    The local scope in which to execute code. This is used as the locals parameter for exec. If locals is absent, the value of globals is used. See the exec documentation for more info.

Returns

If the last nonwhitespace character of source 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 run_async(globals: Optional[Dict[str, Any]] = None, locals: Optional[Dict[str, Any]] = None)

Runs self.code which may use top level await.

Can only be used after calling CodeRunner.compile. If self.code uses top level await, automatically awaits the resulting coroutine.

Parameters
  • globals (dict) –

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

  • locals (dict) –

    The local scope in which to execute code. This is used as the locals parameter for exec. If locals is absent, the value of globals is used. See the exec documentation for more info.

Returns

If the last nonwhitespace character of source 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

exception pyodide.ConversionError

An error thrown when conversion between Javascript and Python fails.

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 the Type translations documentation. In particular, see the list of __dunder__ methods that are (conditionally) implemented on JsProxy.

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(depth=1). See Javascript to Python for more information.

class console.Console(globals: Optional[dict] = None, *, stdout_callback: Optional[Callable[[str], None]] = None, stderr_callback: Optional[Callable[[str], None]] = None, stdin_callback: Optional[Callable[[str], None]] = None, persistent_stream_redirection: bool = False, filename: str = '<console>')

Interactive Pyodide console

An interactive console based on the Python standard library code.InteractiveConsole that manages stream redirections and asynchronous execution of the code.

The stream callbacks can be modified directly as long as persistent_stream_redirection isn’t in effect.

Parameters
  • globals (dict) – The global namespace in which to evaluate the code. Defaults to a new empty dictionary.

  • stdout_callback (Callable[[str], None]) – Function to call at each write to sys.stdout. Defaults to None.

  • stderr_callback (Callable[[str], None]) – Function to call at each write to sys.stderr. Defaults to None.

  • stdin_callback (Callable[[str], None]) – Function to call at each read from sys.stdin. Defaults to None.

  • persistent_stream_redirection (bool) – Should redirection of standard streams be kept between calls to runcode? Defaults to False.

  • filename (str) – The file name to report in error messages. Defaults to <console>.

globals

The namespace used as the global

Type

Dict[str, Any]

stdout_callback

Function to call at each write to sys.stdout.

Type

Callback[[str], None]

stderr_callback

Function to call at each write to sys.stderr.

Type

Callback[[str], None]

stdin_callback

Function to call at each read from sys.stdin.

Type

Callback[[str], None]

buffer

The list of strings that have been pushed to the console.

Type

List[str]

completer_word_break_characters

The set of characters considered by complete to be word breaks.

Type

str

complete(source: str)Tuple[List[str], int]

Use Python’s rlcompleter to complete the source string using the globals namespace.

Finds last “word” in the source string and completes it with rlcompleter. Word breaks are determined by the set of characters in completer_word_break_characters.

Parameters

source (str) – The source string to complete at the end.

Returns

  • completions (List[str]) – A list of completion strings.

  • start (int) – The index where completion starts.

Examples

>>> shell = Console()
>>> shell.complete("str.isa")
(['str.isalnum(', 'str.isalpha(', 'str.isascii('], 0)
>>> shell.complete("a = 5 ; str.isa")
(['str.isalnum(', 'str.isalpha(', 'str.isascii('], 8)
formatsyntaxerror(e: Exception)str

Format the syntax error that just occurred.

This doesn’t include a stack trace because there isn’t one. The actual error object is stored into sys.last_value.

formattraceback(e: Exception)str

Format the exception that just occurred.

The actual error object is stored into sys.last_value.

persistent_redirect_streams()

Redirect stdin/stdout/stderr persistently

persistent_restore_streams()

Restore stdin/stdout/stderr if they have been persistently redirected

push(line: str)_pyodide.console.ConsoleFuture

Push a line to the interpreter.

The line should not have a trailing newline; it may have internal newlines. The line is appended to a buffer and the interpreter’s runsource() method is called with the concatenated contents of the buffer as source. If this indicates that the command was executed or invalid, the buffer is reset; otherwise, the command is incomplete, and the buffer is left as it was after the line was appended.

The return value is the result of calling Console.runsource on the current buffer contents.

redirect_streams()

A context manager to redirect standard streams.

This supports nesting.

async runcode(source: str, code: _pyodide._base.CodeRunner)Any

Execute a code object and return the result.

runsource(source: str, filename: str = '<console>')_pyodide.console.ConsoleFuture

Compile and run source code in the interpreter.

Returns

Return type

ConsoleFuture

class console.ConsoleFuture(syntax_check: Union[Literal[incomplete], Literal[syntax - error], Literal[complete]])

A future with extra fields used as the return value for Console apis.

syntax_check

One of "incomplete", "syntax-error", or "complete". If the value is "incomplete" then the future has already been resolved with result equal to None. If the value is "syntax-error", the Future has already been rejected with a SyntaxError. If the value is "complete", then the input complete and syntactically correct.

Type

str

formatted_error

If the Future is rejected, this will be filled with a formatted version of the code. This is a convenience that simplifies code and helps to avoid large memory leaks when using from Javascript.

Type

str

class console.PyodideConsole(globals: Optional[dict] = None, *, stdout_callback: Optional[Callable[[str], None]] = None, stderr_callback: Optional[Callable[[str], None]] = None, stdin_callback: Optional[Callable[[str], None]] = None, persistent_stream_redirection: bool = False, filename: str = '<console>')

A subclass of Console that uses pyodide.loadPackagesFromImports before running the code.

console.repr_shorten(value: Any, limit: int = 1000, split: Optional[int] = None, separator: str = '...')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.destroy_proxies(pyproxies: pyodide.JsProxy)

Destroy all PyProxies in a Javascript array.

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

pyodide.eval_code(source: 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>', flags: int = 0)Any

Runs a string as Python source code.

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

  • globals (dict) –

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

  • locals (dict) –

    The local scope in which to execute code. This is used as the locals parameter for exec. If locals is absent, the value of globals is used. 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' by default.

    • '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) – Specifies whether a trailing semicolon should suppress the result or not. When this is True executing "1+1 ;" returns None, when it is False, executing "1+1 ;" return 2. True by default.

  • filename (str) – The file name to use in error messages and stack traces. '<exec>' by default.

Returns

If the last nonwhitespace character of source 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(source: 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>', flags: int = 0)Any

Runs a code string asynchronously.

Uses PyCF_ALLOW_TOP_LEVEL_AWAIT to compile the code.

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

  • globals (dict) –

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

  • locals (dict) –

    The local scope in which to execute code. This is used as the locals parameter for exec. If locals is absent, the value of globals is used. 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' by default.

    • '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) – Specifies whether a trailing semicolon should suppress the result or not. When this is True executing "1+1 ;" returns None, when it is False, executing "1+1 ;" return 2. True by default.

  • filename (str) – The file name to use in error messages and stack traces. '<exec>' by default.

Returns

If the last nonwhitespace character of source 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(source: str)List[str]

Finds the imports in a Python source code string

Parameters

source (str) – The Python source code to inspect for imports.

Returns

A list of module names that are imported in source.

Return type

List[str]

Examples

>>> from pyodide import find_imports
>>> source = "import numpy as np; import scipy.stats"
>>> find_imports(source)
['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)

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.should_quiet(source: str)bool

Should we suppress output?

Returns True if the last nonwhitespace character of code is a semicolon.

Examples

>>> should_quiet('1 + 1')
False
>>> should_quiet('1 + 1 ;')
True
>>> should_quiet('1 + 1 # comment ;')
False
pyodide.to_js(obj: Any, *, depth: int = - 1, pyproxies: Optional[pyodide.JsProxy] = None, create_pyproxies: bool = True, dict_converter: Optional[Callable[[Iterable[pyodide.JsProxy]], pyodide.JsProxy]] = None)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.

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

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

  • pyproxies (JsProxy, default = None) – 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, default=True) – If you set this to False, to_js will raise an error

  • dict_converter (Callable[[Iterable[JsProxy]], JsProxy], defauilt = None) –

    This converter if provided recieves 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

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.