PyScript Next runtime configuration: Global namespace synchronization across backends
0 reputation · 29 Sept 2023, 02:37 UTC
0 reputation · 29 Sept 2023, 02:37 UTC
PyScript Next (version 2023.11.1+) has transitioned to a decoupled configuration model using the <py-config> tag. This modular approach allows developers to switch between the Pyodide and MicroPython backends depending on the required footprint and library support.
While the <py-config> schema streamlines environment setup, there is uncertainty regarding how the global Python namespace synchronizes with the JavaScript window object when switching backends. The behavior of object exposure and interoperability may differ between the full C-extension support of Pyodide and the lightweight implementation of MicroPython.
33775 reputation · 29 Sept 2023, 08:08 UTC
In PyScript Next, the synchronization of the Python global namespace with the JavaScript window object is not consistent across Pyodide and MicroPython backends. While the <py-config> tag handles environment setup, the underlying mechanism for object exposure and interoperability differs significantly due to the architecture of each runtime.
The uncertainty stems from how each runtime handles the bridge between Python memory and the JavaScript engine:
window, Pyodide creates proxy objects that allow for deep interaction. It supports complex C-extension-based libraries but carries higher memory overhead for each synchronized object.When writing a configuration intended to work across both backends, consider these specific constraints:
window. Stick to primitive types (dictionaries, lists, strings) that represent global state.To maintain a backend-agnostic environment, do not rely on the runtime's automatic global exposure. Instead, use an explicit state-management pattern:
// Explicitly sync state in JS
function syncToJS(data) {
window.pyAppState = data;
}
// In Python
from pyscript import window
import json
def update_state(new_val):
window.pyAppState = json.dumps(new_val)
Are you attempting to synchronize real-time data streams between multiple users, or just local configuration on load?
Use comments to ask for clarification. Post a solution as an answer.
33,775 reputation · 29 Sept 2023, 14:22 UTC
The <py-config> backend option in PyScript Next 2023.11.1+ only controls which runtime is loaded and how packages/imports are initialized. It does not normalize how Python globals become visible to JavaScript.
With Pyodide you get the window.pyodide API and PyProxy objects with toJs/fromJs conversion. With the MicroPython backend the surface is window.pyscript and a lightweight custom bridge with limited type support and no PyProxy semantics. Automatic mirroring of Python globals to window is therefore backend-specific and version-sensitive.
For backend-agnostic code, validate exposure explicitly per backend via the PyScript JS API and pyscript.ready, rather than assuming window contains the same Python names.