Skip to content

Commit

Permalink
feat(Python): Add Pyodide list support
Browse files Browse the repository at this point in the history
  • Loading branch information
thewtex committed Apr 20, 2023
1 parent 6a088a2 commit 13e97d6
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 2 deletions.
11 changes: 9 additions & 2 deletions packages/core/python/itkwasm/itkwasm/pyodide.py
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,9 @@ def web_worker(self, value):

def to_py(js_proxy):
import pyodide
if hasattr(js_proxy, "imageType"):
if isinstance(js_proxy, pyodide.ffi.JsArray):
return [to_py(value) for value in js_proxy]
elif hasattr(js_proxy, "imageType"):
image_dict = js_proxy.to_py()
image_type = ImageType(**image_dict['imageType'])
image_dict['imageType'] = image_type
Expand Down Expand Up @@ -142,7 +144,12 @@ def to_py(js_proxy):
def to_js(py):
import pyodide
import js
if isinstance(py, Image):
if isinstance(py, list):
js_array = pyodide.ffi.to_js([])
for value in py:
js_array.append(to_js(value))
return js_array
elif isinstance(py, Image):
image_dict = asdict(py)
image_dict['direction'] = image_dict['direction'].ravel()
if image_dict['data'] is not None:
Expand Down
33 changes: 33 additions & 0 deletions packages/core/python/itkwasm/test/test_pyodide.py
Original file line number Diff line number Diff line change
Expand Up @@ -256,3 +256,36 @@ async def test_text_file_conversion(selenium, package_wheel):
data_py = fp.read()

assert data_py == data

@run_in_pyodide(packages=['micropip', 'numpy'])
async def test_list_conversion(selenium, package_wheel):
import micropip
await micropip.install(package_wheel)

from itkwasm import TextFile
from itkwasm.pyodide import to_js, to_py
import numpy as np
from pathlib import PurePosixPath

data = "The answer is 42."

def create_text_file(index):
path = PurePosixPath(f'file{index}.txt')
with open(path, 'w') as fp:
fp.write(data)
text_file = TextFile(path)
return text_file

text_files = [create_text_file(index) for index in range(4)]

text_files_js = to_js(text_files)
text_files_py = to_py(text_files_js)

def verify_text_file(text_file):
with open(text_file.path, 'r') as fp:
data_py = fp.read()

assert data_py == data

for text_file in text_files_py:
verify_text_file(text_file)

0 comments on commit 13e97d6

Please sign in to comment.