PyScript Async Control Flow and Browser Cancellation Integration
0 reputation · 25 Nov 2021, 07:09 UTC
0 reputation · 25 Nov 2021, 07:09 UTC
The goal is to ensure graceful handling of asynchronous task cancellation within PyScript.
The precise propagation of JavaScript cancellation signals back into the Python runtime remains uncertain across different host browser environments.
Does PyScript guarantee that external JavaScript cancellation events correctly map to Python's `asyncio` cancellation mechanisms?
37775 reputation · 25 Nov 2021, 11:13 UTC
No. Do not assume PyScript guarantees that arbitrary external JavaScript cancellation events are automatically mapped into Python asyncio cancellation inside a running coroutine. Treat browser-to-Python cancellation as an integration boundary that usually needs an explicit bridge.
clearTimeout before it fires does not, by itself, cancel a Python task. A Python asyncio.sleep or task continues according to the Python/Pyodide event-loop integration unless Python code calls task.cancel() or otherwise signals it.asyncio.Task, the coroutine should observe asyncio.CancelledError at the next await/suspension point, not synchronously at an arbitrary bytecode instruction.If the timer is cleared before firing, expect no Python cancellation. If the timer fires and its JavaScript handler invokes a Python cancellation callback, expect cooperative cancellation at the next await. If the coroutine is in a long synchronous Python block, cancellation is delayed until control returns to the event loop; CPU-bound sections may not be interruptible promptly.
Keep a reference to the task, expose a tiny cancel callback to JavaScript using the interop API for your pinned PyScript/Pyodide release, and have the browser AbortSignal/timer/page-event handler call it. API names vary by release, so treat this as shape, not copy-paste certainty:
import asyncio
task = None
async def job():
try:
while True:
await asyncio.sleep(0.1)
# do a slice of work
except asyncio.CancelledError:
# cleanup, then re-raise
raise
finally:
# release local resources
pass
def cancel_from_browser():
if task is not None and not task.done():
task.cancel()
task = asyncio.create_task(job())
# expose cancel_from_browser to JS with the interop mechanism for your pinned versionsJavaScript side, conceptually: an AbortSignal listener or timer callback calls the exposed Python cancel function. Do not rely on finally during page unload for durable side effects; navigation can tear down the context without giving Python a graceful CancelledError.
For browser-originated cancellation, yes: explicit wrapping/bridging is the safe default. Pure Python task.cancel() remains the normal mechanism for Python-originated cancellation. asyncio.wait_for or timeout-style helpers can cancel an inner Python task on a Python-side deadline, but they do not prove an external browser AbortSignal was wired through. Do not swallow CancelledError; clean up and re-raise so task semantics remain intact.
finally, and task.done()/task.cancelled().clearTimeout before firing; timer fires and callback cancels the task; CPU-bound loop with and without await asyncio.sleep(0).One missing detail changes the recommendation: which PyScript/Pyodide versions and browser/main-thread-versus-worker host are you targeting? If production depends on this, pin those and verify against their docs before shipping.
Use comments to ask for clarification. Post a solution as an answer.
37,775 reputation · 25 Nov 2021, 17:07 UTC
PyScript schedules CPython asyncio through Pyodide/WebAssembly on the browser JavaScript event loop, but browser cancellation signals are not automatically delivered as asyncio.CancelledError. AbortController, pagehide, beforeunload, or tab closure may tear down the WASM context without raising cancellation in Python. You need an explicit bridge, such as pyscript.ffi.create_proxy calling task.cancel() or wrapping with asyncio.wait_for, and the error only surfaces at the next await point; it cannot interrupt synchronous CPython or C extension code. Verify by creating an asyncio.Task, exposing a cancel proxy, triggering it from setTimeout or a button, and confirming CancelledError is caught. Behavior is version-sensitive across PyScript, Pyodide, and the host browser, so check the installed release notes before relying on it.