From 09bf1da0a42ed10053a44a433c7cd803365f32d1 Mon Sep 17 00:00:00 2001 From: "Yuichiro Tachibana (Tsuchiya)" Date: Thu, 2 May 2024 19:06:43 +0900 Subject: [PATCH] Make TjsProxy extend collections.abc.Mapping --- transformers_js_py/proxies.py | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) diff --git a/transformers_js_py/proxies.py b/transformers_js_py/proxies.py index 18b9c19..c13c50a 100644 --- a/transformers_js_py/proxies.py +++ b/transformers_js_py/proxies.py @@ -1,4 +1,5 @@ import re +from collections.abc import Mapping from typing import Any, Awaitable, Union import js @@ -62,7 +63,7 @@ def to_js(obj: Any) -> Any: ) -class TjsProxy: +class TjsProxy(Mapping): def __init__(self, js_obj: pyodide.ffi.JsProxy): self._js_obj = js_obj self._is_class = self._js_obj.typeof == "function" and rx_class_def_code.match( @@ -90,8 +91,8 @@ def __getattr__(self, name: str) -> Any: res = getattr(self._js_obj, name) return wrap_or_unwrap_proxy_object(res) - def __getitem__(self, key: Any) -> Any: - res = self._js_obj[key] + def __getitem__(self, name: Any) -> Any: + res = getattr(self._js_obj, name) return wrap_or_unwrap_proxy_object(res) def __setitem__(self, key: Any, value: Any) -> None: @@ -105,9 +106,11 @@ def __setattr__(self, name: str, value: Any) -> None: value = to_js(value) setattr(self._js_obj, name, value) - def __repr__(self) -> str: - dictified_self = {k: getattr(self, k) for k in self._js_obj.object_keys()} - return "".format(repr(dictified_self)) + def __iter__(self): + return iter(self._js_obj.object_keys()) + + def __len__(self): + return len(self._js_obj.object_keys()) class TjsRawImageClassProxy(TjsProxy):