For some reason, importing canvas directly in Python (either in pyodide.runPython() or in py-script) breaks the import functionality with a TypeError:
import canvas
Python exception:
Traceback (most recent call last):
File "/lib/python3.10/site-packages/_pyodide/_base.py", line 429, in eval_code
.run(globals, locals)
File "/lib/python3.10/site-packages/_pyodide/_base.py", line 300, in run
coroutine = eval(self.code, globals, locals)
File "<exec>", line 2, in <module>
File "<frozen importlib._bootstrap>", line 1075, in _handle_fromlist
JsException: TypeError: Cannot read properties of undefined (reading 'name')
And registerJsModule also fails with the “cannot read properties of undefined” error.
As a hack you can always do something like :
for (const property in canvas){
window[property] = canvas[property]
}
Which will make all the properties defined in canvas.js into global objects that you can import into Pyodide. It’s definitely feels crude though.
Well, after all that fooling around, it turns out the issue with “Cannot read properties of undefined” is fixed in Pyodide 0.21.0a3 as per Issue #2901.
So when Pyodide 0.21 is released, you could just do:
Unfortunately, contrary to what the reporter of that issue said, it seems loading runtimes from a URL via py-config is currently disabled (as of 2022.06.1), so I had to make the example above work by building pyscript from source with the default runtime source set to https://pyodide-cdn2.iodide.io/dev/full/pyodide.js)
But leaving this here for the future, since importing js modules like python modules feels just swell.
Dropping back in to say - the PyScript core devs just merged PR #719, updating Pyodide to Version 21.1. So if you link to the unstable PyScript release, you can try that functionality today, or it will be available in the next PyScript release.