Repository navigation
Description
🚀 Feature
I suggest adding hooks to allow customising the conversion between JS and Python awaitables.
Motivation
Currently, Pyodide automatically converts between asyncio and JavaScript awaitables. That means you can directly await JS async functions from Python and vice-versa:
import js
# Call JS async function from Python
result = await js.jsFn(x)
# Allow Python async function to be called from JS
js.pyFn = py_fnBut this doesn't work if you're using a different async library, e.g. Trio, because Python awaitables from different async libraries aren't compatible. I made a proof of concept port of Trio to Pyodide (source code - live demo) - it was made with an LLM so isn't directly suitable for merging into Trio, but it demonstrates it's possible. The analogous calls are:
import trio.pyodide
# Call JS function from Python
result = await trio.pyodide.call(js.jsFn, x)
# Allow Python function to be called from JS
js.pyFn = trio.pyodide.callable_from_js(py_fn)Pitch
Allow setting (and getting) hooks for converting JS->Python and Python->JS awaitables. The hooks would look a bit like this (with a done_callback for js_to_py to allow destroying the temporary proxies Pyodide made for the arguments):
pyodide.ffi.set_awaitable_hooks(
js_to_py=..., # (jsawaitable, done_callback) -> Python awaitable
py_to_js=..., # (pyawaitable) -> JavaScript promise
)
pyodide.ffi.get_awaitable_hooks() # -> the current pair, like sys.get_asyncgen_hooks()By default, they would point at the current asyncio-specific implementation, but if another async library is used then it could override the hooks, and allow the syntax seen in the first code block above.
Alternatives
- Use a context variable for the hooks rather than a global variable. This is more flexible (e.g. it works even if you wanted to run two async libraries at the same time - but would you really want to do that?) but would need a more complex implementation (whenever you create a JS proxy from a callable Python object, you look up the hook store it in the proxy, to be called later if that hook happens to return an awaitable).
- Put per-library conversion code in Pyodide instead of the third-party async libraries itself e.g. add support to detect if Trio is running and, if so, convert to Trio-compatible awaitables instead of
asyncio.Future. Then the hook wouldn't be needed because Pyodide handles the decision itself. But this doesn't feel like the right place for conversion code to go, especially since these third-party async libraries would still need to have Pyodide-specific code in them.
Additional context
This issue was noticed in the context of PEP 818 - Adding the Core of the Pyodide Foreign Function Interface to Python. In the discussion thread, @davidbrochart noticed the problem, and it was suggested that hooks could be added for async conversion. @hoodmane, who is the PEP author, said (very reasonably) that the PEP should only include features that already exist in Pyodide, which is why I'm posting the request here.
In case it's of interest, here are some suggestions about the implementation from an LLM (Claude Fable 5.1). Feel free to ignore if AI text isn't wanted.
JavaScript to Python: one function to rework, two to reroute
wrap_promise,src/core/jsproxy.clines 2777 to 2816. This is the whole coupling on this side. Its body callsasyncio.get_event_loop().create_future(), fetches the future's resolvers from_pyodide._future_helper, and attaches them withcreate_promise_handles. The replacement body is:Promise.resolvethe promise as now, wrap it and thedone_callbackas proxies, and call the installedjs_to_pyhook. Its callers need no change, since they already go through it:JsProxy_Await, line 2819,JsProxy_aexit, line 2356, and the two call paths injsbind.cat line 421 and line 555.- Two places build an asyncio future by hand instead of calling
wrap_promise, and must be rerouted through it:_agen_handle_result, lines 1222 to 1232, which backsasend,athrowandacloseon JavaScript async generators, andJsProxy_aenter, lines 2330 to 2340, which returns an already-resolved future and can wrapPromise.resolve(self)instead. - The default hook is today's behaviour moved into Python, in
_pyodide/_future_helper.py, which already holds the resolver helpers. It needs one new primitive exposed to Python: the JavaScript helpercreate_promise_handles,src/core/pyproxy.cline 1436, which attaches the handlers, owns their lifetimes, and runsdone_callbackafter delivery. Exposing it as something likeattach_promise_handlersis what makes a third-party hook a few lines long, and it carries the ordering rule thatget_async_js_call_done_callback,jsbind.cline 389 relies on to destroy borrowed argument proxies only after the value has been delivered.
Python to JavaScript: one C function and one TypeScript method
_pyproxy_ensure_future,src/core/pyproxy.clines 1130 to 1146. It callsasyncio.ensure_futureand attaches aFutureDoneCallbackthat fires the resolve and reject handles it was given. It becomes "call the installedpy_to_jshook and return the promise". TheFutureDoneCallbacktype, lines 1030 to 1115, then only serves the default and can be rewritten in Python asensure_futureplusPromise.withResolvers()plusadd_done_callback, which is exactly PEP 818'spyawaitable_to_promise.PyAwaitableMethods._ensure_future,src/core/pyproxy.tslines 2571 to 2602. It currently constructs the promise itself and passes the resolve and reject handles down into C. Instead it takes the promise the C side returns and stores it inshared.promise. Everything built on it is untouched:then,catchandfinallyon a PyProxy, and the eager scheduling of coroutines returned to JavaScript at line 553 and line 635.
Plumbing and surface
- Two
PyObject*globals in the C core holding the installed pair, initialised to the defaults, plus a setter in the_pyodide_coremodule. set_awaitable_hooksandget_awaitable_hooksdefined in_pyodide/_core_docs.pybesiderun_syncat line 1701, and listed inpyodide/ffi/__init__.py's__all__.- Nothing in
webloop.pychanges. The loop keeps working as the default hooks' scheduler, and a page that installs other hooks never creates it. - Optional:
run_sync,jsproxy.cline 4546, which also callsensure_future, could route throughpy_to_jsso that it can block on a non-asyncio awaitable too. Separate change.
Two things are untouched and already framework-neutral: the Python-level then, catch and finally_ overloads on a JsProxy from line 2848 onward, which attach callbacks to the raw promise without creating a future, and the typed-signature converters, which the default hook keeps applying through create_promise_handles.
Activity
hoodmane commentedon Oct 28, 2026
Thanks for the proposal. I'm happy to do this modulo whatever bike shedding is necessary.