Part of the magic of the Pyodide runtime that PyScript uses is the ability to pass objects back and forth between JavaScript and Python more or less directly. But what exactly the syntax is for doing so isn’t necessarily obvious to new PyScript users.
I’ve written up four recipes to help illustrate this, for passing objects:
- From JavaScript to Python (in Pyodide)
- From JavaScript to Python (in PyScript)
- From Python (in Pyodide) to JavaScript
- From Python (in PyScript) to JavaScript
Due to some current implementation details, the last option isn’t quite as straightforward as it could be; I suspect it will only get easier as PyScript evolves, but I wanted to share a method that works in the current version of PyScript (2022.06.1) for those who need it.
Edit: Like any good blog post, I thought of a better solution to the last problem immediately after posting. The post has now been updated, but to summarize: we can use a JavaScript function to export the Python global namespace from PyScript as a dictionary. This allows JavaScript to dynamically access any variable created in Python.