pyscript.context
Execution context management for PyScript.
This module handles the differences between running in the main browser thread versus running in a Web Worker, providing a consistent API regardless of the execution context.
Key features:
- Detects whether code is running in a worker or main thread. Read this via
the boolean
pyscript.context.RUNNING_IN_WORKER. - Parses and normalizes configuration from
polyscript.configand adds the Python interpreter type via thetypekey inpyscript.context.config. - Provides appropriate implementations of
window,document, andsync. - Sets up JavaScript module import system, including a lazy
js_importfunction. - Manages
PyWorkercreation. - Provides access to the current display target via
pyscript.context.display_target.
Warning
These are key differences between the main thread and worker contexts:
Main thread context:
windowanddocumentare available directly.PyWorkercan be created to spawn worker threads.syncis not available (raisesNotSupported).
Worker context:
windowanddocumentare proxied from main thread (if SharedArrayBuffer available).PyWorkeris not available (raisesNotSupported).syncutilities are available for main thread communication.
RUNNING_IN_WORKER = not hasattr(js, 'document')
module-attribute
Detect execution context: True if running in a worker, False if main thread.
config = json.loads(js.JSON.stringify(_polyscript_config))
module-attribute
Parsed and normalized configuration.
sync = None
module-attribute
Sync utilities for worker-main thread communication (only in workers).
window = polyscript.xworker.window
module-attribute
The window object (proxied if in a worker).
document = window.document
module-attribute
The document object (proxied if in a worker).
js_import = window.Function('return (...urls) => Promise.all(urls.map((url) => import(url)))')()
module-attribute
Function to import JavaScript modules dynamically.
PyWorker(url, **options)
Create a Web Worker running Python code.
This spawns a new worker thread that can execute Python code
found at the url, independently of the main thread. The
**options can be used to configure the worker.
from pyscript import PyWorker
# Create a worker to run background tasks.
# (`type` MUST be either `micropython` or `pyodide`)
worker = PyWorker("./worker.py", type="micropython")
PyWorker can only be created from the main thread, not from within another worker.