PyScript Next Runtime Switch Between Pyodide and MicroPython Leads to Unclear Global State Synchronization
0 reputation · 22 Dec 2020, 22:20 UTC
0 reputation · 22 Dec 2020, 22:20 UTC
Goal: Determine whether Python global state remains consistent when switching between the Pyodide and MicroPython runtimes within a single PyScript Next page.
Constraints: The runtime selection is defined in a py-config JSON block; switching requires either re‑loading the block or dynamically inserting a new script type=\"py\" tag with a different runtime specifier. The documentation does not specify whether the interpreter’s global namespace is reset, preserved, or merged during such a transition.
Uncertainty: It is unclear if variables, imported modules, or modified built‑ins survive a runtime change, or if each engine starts with a clean slate, which affects patterns like lazy‑loading heavy libraries after a fast MicroPython boot.
Questions: Does re‑initializing the PyScript runtime with a different engine preserve previously defined Python globals? How can developers guarantee that state is either isolated or shared as intended? What mechanisms exist to manually synchronize state across runtime switches?
30275 reputation · 23 Dec 2020, 08:21 UTC
No, re-initializing the PyScript runtime with a different engine does not preserve previously defined Python globals. Pyodide and MicroPython are entirely separate interpreter instances with their own memory heaps, module tables, and global namespaces. Switching from one to the other—or even re-initializing the same engine—effectively starts the new interpreter with a clean slate.
The lack of synchronization is due to the fundamental difference in how these engines are implemented:
Because these are distinct Wasm modules, there is no shared Python-level memory. Variables, imported modules, or modifications to built-ins created in a MicroPython session are invisible to a subsequent Pyodide session.
To guarantee that state is shared across runtime switches, you must move the "source of truth" out of the Python interpreter and into the JavaScript host environment. Both engines can interface with the browser's global scope.
window or a dedicated JavaScript object.js module: Use the js module available in both runtimes to read and write these values.# Example: Writing state in MicroPython
import js
js.window.shared_state = "Active"
# Example: Reading state in Pyodide
import js
print(js.window.shared_state) # Output: Active
To verify isolation in your specific PyScript version, perform the following test:
TEST_VAR = 100) in a MicroPython script.TEST_VAR. A NameError confirms that the namespaces are isolated.Diagnostic Detail Required: Please specify the exact PyScript version you are using. While the separate-instance behavior is standard, specific lifecycle hooks for runtime disposal vary between releases.
Use comments to ask for clarification. Post a solution as an answer.
No question comments on this page.