Skip to content

Commit

Permalink
Expose a "js" module and a small pyodide polyfill (#54)
Browse files Browse the repository at this point in the history
* Expose as "js" module

* Pyodide polyfill

* Add test

---------

Co-authored-by: Thorsten Beier <[email protected]>
  • Loading branch information
martinRenou and DerThorsten authored Feb 6, 2024
1 parent 3df1bf1 commit f420f59
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 1 deletion.
21 changes: 20 additions & 1 deletion include/pyjs/pycpp/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ def _js_mod__getattr__(name: str) -> Any:
raise AttributeError(f"has no attribute {name}")
return ret

js = sys.modules["pyjs.js"] = types.ModuleType("js")
js = sys.modules["js"] = sys.modules["pyjs.js"] = types.ModuleType("js")
js.__getattr__ = _js_mod__getattr__

def _module_mod__getattr__(name: str) -> Any:
Expand All @@ -25,6 +25,25 @@ def _module_mod__getattr__(name: str) -> Any:
_module = sys.modules["pyjs._module"] = types.ModuleType("_module")
_module.__getattr__ = _module_mod__getattr__

# Expose a small pyodide polyfill
def _pyodide__getattr__(name: str) -> Any:
if name == "to_js":
from pyjs import to_js
return to_js

raise AttributeError(
"This is not the real Pyodide. We are providing a small Pyodide polyfill for conveniance."
"If you are missing an important Pyodide feature, please open an issue in https://github.com/emscripten-forge/pyjs/issues"
)

pyodide = sys.modules["pyodide"] = types.ModuleType("pyodide")
pyodide.ffi = sys.modules["pyodide.ffi"] = types.ModuleType("ffi")
pyodide.ffi.JsException = RuntimeError
pyodide.ffi.JsArray = object
pyodide.ffi.JsProxy = object
pyodide.__getattr__ = _pyodide__getattr__
pyodide.ffi.__getattr__ = _pyodide__getattr__


install_submodules()
del install_submodules
Expand Down
14 changes: 14 additions & 0 deletions tests/tests/test_pyjs.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import json
import operator
import os
import sys
from types import NoneType
import asyncio

Expand Down Expand Up @@ -36,6 +37,19 @@ def test_js_function_creation():
assert ret == "hello_world"


def test_pyodide_polyfill():
# Test imports
from pyodide.ffi import JsException, to_js
if pyjs.to_py(pyjs._module._IS_BROWSER_MAIN_THREAD):
from js import console, window
if pyjs.to_py(pyjs._module._IS_BROWSER_WORKER_THREAD):
from js import console, postMessage

with pytest.raises(AttributeError):
from pyodide import ffi
ffi.foo


def test_create_once_callable_nullary():
def pyfunc():
return "hello_from_pyfunc"
Expand Down

0 comments on commit f420f59

Please sign in to comment.