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.
|
The global Javascript scope. |
The Javascript Pyodide module. |
Exceptions:
A wrapper around a Javascript Error to allow it to be thrown in Python. |
Classes:
|
A proxy to make a Javascript object behave like a Python object |
|
A custom event loop for use in Pyodide. |
A simple event loop policy for managing WebLoop based event loops. |
Functions:
|
Compute the string representation of |
|
Wrap a Python callable in a Javascript function that can be called once. |
|
Create a |
|
Runs a code string. |
|
Runs a code string asynchronously. |
|
Finds the imports in a string of code |
|
Fetches a given URL |
|
Registers |
|
Convert the object to Javascript. |
|
Unregisters a Javascript module with given name that has been previously registered with |
-
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
-
property
-
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 firstssplit
characters and the lastsplit
characters seperated by ‘…’. Default value forsplit
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 aPyProxy
.This allows explicit control over the lifetime of the
PyProxy
from Python: call thedestroy
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 theglobals
parameter forexec
. See the exec documentation for more info. If theglobals
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 forexec
. As withexec
, iflocals
is absent, it is set equal toglobals
. 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 returnNone
.
quiet_trailing_semicolon (
bool
) – Whether a trailing semicolon should ‘quiet’ the result or not. Setting this toTrue
(default) mimic the CPython’s interpreter behavior ; whereas setting it toFalse
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 returnNone
. If the last statement is an expression, return the result of the expression. (Use thereturn_mode
andquiet_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 forexec
. See the exec documentation for more info. If theglobals
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 forexec
. As withexec
, iflocals
is absent, it is set equal toglobals
. 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 returnNone
.
quiet_trailing_semicolon (
bool
) – Whether a trailing semicolon should ‘quiet’ the result or not. Setting this toTrue
(default) mimic the CPython’s interpreter behavior ; whereas setting it toFalse
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 returnNone
. If the last statement is an expression, return the result of the expression. (Use thereturn_mode
andquiet_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 namedname
. 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 fromsys.modules
. This is called by the javascript APIpyodide.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 aJsProxy
of aPyProxy
, as if you had usedpyodide.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
orpyodide.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 fromsys.modules
. This is called by the Javascript APIpyodide.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
andrun_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.