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, *, stdin_callback, …)

Interactive Pyodide console

ConsoleFuture(syntax_check, …)

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

PyodideConsole(globals, *, stdin_callback, …)

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

FetchResponse(url, js_response)

A wrapper for a Javascript fetch response.

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

pyfetch(url, **kwargs)

Fetch the url and return the response.

open_url(url)

Fetches a given URL synchronously.

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 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: Any)#

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: Any)#

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)pyodide.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)pyodide.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.

from_file(file: io.IOBase)#

Reads from a file into the buffer.

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

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

Example

>>> import pytest; pytest.skip()
>>> from js import Uint8Array
>>> # the JsProxy need to be pre-allocated
>>> x = Uint8Array.new(range(10))
>>> with open('file.bin', 'rb') as fh:
...    x.read_file(fh)
which is equivalent to
>>> x = Uint8Array.new(range(10))
>>> with open('file.bin', 'rb') as fh:
...    chunk = fh.read(size=x.byteLength)
...    x.assign(chunk)
but the latter copies the data twice whereas the former only copies the
data once.
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)pyodide.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_bytes()bytes#

Convert the buffer to a bytes object.

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

to_file(file: io.IOBase)#

Writes the entire buffer to a file.

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

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

Example

>>> import pytest; pytest.skip()
>>> from js import Uint8Array
>>> x = Uint8Array.new(range(10))
>>> with open('file.bin', 'wb') as fh:
...    x.to_file(fh)
which is equivalent to,
>>> with open('file.bin', 'wb') as fh:
...    data = x.to_bytes()
...    fh.write(data)
but the latter copies the data twice whereas the former only copies the
data once.
to_memoryview()memoryview#

Convert the buffer to a memoryview.

Copies the data once. This currently has the same effect as to_py. Present only if the wrapped Javascript object is an ArrayBuffer or an ArrayBuffer view.

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.

to_string(encoding=None)str#

Convert the buffer to a string object.

Copies the data twice.

The encoding argument will be passed to the Javascript [TextDecoder](https://developer.mozilla.org/en-US/docs/Web/API/TextDecoder) constructor. It should be one of the encodings listed in the table here: https://encoding.spec.whatwg.org/#names-and-labels. The default encoding is utf8.

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

class console.Console(globals: Optional[dict] = None, *, stdin_callback: Optional[Callable[[str], None]] = None, stdout_callback: Optional[Callable[[str], None]] = None, stderr_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.

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

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

  • 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]

stdin_callback#

Function to call at each read from sys.stdin.

Type

Callback[[str], None]

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]

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, *, stdin_callback: Optional[Callable[[str], None]] = None, stdout_callback: Optional[Callable[[str], None]] = None, stderr_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. If source is not syntactically correct Python code (after dedenting), returns an empty list.

Return type

List[str]

Examples

>>> from pyodide import find_imports
>>> source = "import numpy as np; import scipy.stats"
>>> find_imports(source)
['numpy', 'scipy']
class http.FetchResponse(url: str, js_response: pyodide.JsProxy)#

A wrapper for a Javascript fetch response.

See also the Javascript fetch Response api docs.

Parameters
  • url – URL to fetch

  • js_response – A JsProxy of the fetch response

property body_used#

Has the response been used yet?

(If so, attempting to retreive the body again will raise an OSError.)

async buffer()pyodide.JsProxy#

Return the response body as a Javascript ArrayBuffer

async bytes()bytes#

Return the response body as a bytes object

clone()pyodide.http.FetchResponse#

Return an identical copy of the FetchResponse.

This method exists to allow multiple uses of response objects. See Response.clone

async json(**kwargs)Any#

Return the response body as a Javascript JSON object.

Any keyword arguments are passed to json.loads.

async memoryview()memoryview#

Return the response body as a memoryview object

property ok#

Was the request successful?

property redirected#

Was the request redirected?

property status#

Response status code

property status_text#

Response status text

async string()str#

Return the response body as a string

property type#

The type of the response.

async unpack_archive(*, extract_dir=None, format=None)#

Treat the data as an archive and unpack it into target directory.

Assumes that the file is an archive in a format that shutil has an unpacker for. The arguments extract_dir and format are passed directly on to shutil.unpack_archive.

Parameters
  • extract_dir (str) – Directory to extract the archive into. If not provided, the current working directory is used.

  • format (str) – The archive format: one of “zip”, “tar”, “gztar”, “bztar”. Or any other format registered with shutil.register_unpack_format(). If not provided, unpack_archive() will use the archive file name extension and see if an unpacker was registered for that extension. In case none is found, a ValueError is raised.

property url#

The url of the response.

It may be different than the url passed to fetch.

http.open_url(url: str)_io.StringIO#

Fetches a given URL synchronously.

The download of binary files is not supported. To download binary files use pyodide.http.pyfetch() which is asynchronous.

Parameters

url (str) – URL to fetch

Returns

the contents of the URL.

Return type

io.StringIO

async http.pyfetch(url: str, **kwargs)pyodide.http.FetchResponse#

Fetch the url and return the response.

This functions provides a similar API to the JavaScript fetch function however it is designed to be convenient to use from Python. The pyodide.http.FetchResponse has methods with the output types already converted to Python objects.

Parameters
pyodide.open_url(url: str)_io.StringIO#

Fetches a given URL synchronously.

The download of binary files is not supported. To download binary files use pyodide.http.pyfetch() which is asynchronous.

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