From 9e70fda3c8fdac651c70f5d7b7624fa4659fdf22 Mon Sep 17 00:00:00 2001 From: jfriend00 Date: Wed, 2 Dec 2026 22:11:38 -0800 Subject: [PATCH 1/2] Make special methods of pyscript classes work when Python calls them --- custom_components/pyscript/eval.py | 179 ++++++- docs/reference.rst | 45 +- tests/test_unit_eval.py | 781 +++++++++++++++++++++++++++++ 3 files changed, 973 insertions(+), 32 deletions(-) diff --git a/custom_components/pyscript/eval.py b/custom_components/pyscript/eval.py index a115e10..89265f6 100644 --- a/custom_components/pyscript/eval.py +++ b/custom_components/pyscript/eval.py @@ -13,6 +13,7 @@ import traceback from types import CellType, CodeType, FunctionType, MethodType, TracebackType from typing import TYPE_CHECKING, Any +import weakref from .const import ( ALLOWED_IMPORTS, @@ -106,7 +107,7 @@ async def eval_func(arg_str, eval_globals=None, eval_locals=None): eval_ast.sym_table = eval_globals else: eval_ast.sym_table_stack = ast_ctx.sym_table_stack.copy() - if ast_ctx.sym_table == ast_ctx.global_sym_table: + if ast_ctx.sym_table is ast_ctx.global_sym_table: eval_ast.sym_table = ast_ctx.sym_table else: eval_ast.sym_table = ast_ctx.sym_table.copy() @@ -126,9 +127,9 @@ async def eval_func(arg_str, eval_globals=None, eval_locals=None): # # save variables only in the locals scope # - if eval_globals is None and eval_ast.sym_table != ast_ctx.sym_table: + if eval_globals is None and eval_ast.sym_table is not ast_ctx.sym_table: for var, value in eval_ast.sym_table.items(): - if var in ast_ctx.global_sym_table and value == ast_ctx.global_sym_table[var]: + if var in ast_ctx.global_sym_table and value is ast_ctx.global_sym_table[var]: continue if var not in ast_ctx.sym_table and ( ast_ctx.curr_func is None or var not in ast_ctx.curr_func.local_names @@ -162,7 +163,7 @@ def ast_locals_factory(ast_ctx): """Generate a locals() function with given ast_ctx.""" async def locals_func(): - if ast_ctx.sym_table == ast_ctx.global_sym_table: + if ast_ctx.sym_table is ast_ctx.global_sym_table: return ast_ctx.sym_table local_sym_table = ast_ctx.sym_table.copy() local_sym_table.update(ast_ctx.user_locals) @@ -426,6 +427,108 @@ def unwrap_stop_iteration(exc): return exc +# special methods that pyscript leaves as they are: it calls __init__ and __new__ itself, __del__ +# runs whenever the object is freed, Python calls __getattribute__, __setattr__ and __delattr__ for +# every attribute access, which pyscript handles itself (eg, for @property), and the async ones +# already return awaitables +SPECIAL_METHODS_UNCHANGED = frozenset( + { + "__init__", + "__new__", + "__del__", + "__getattribute__", + "__setattr__", + "__delattr__", + "__aenter__", + "__aexit__", + "__anext__", + "__await__", + } +) + + +def is_special_method(name): + """Return True for a special method name that pyscript makes callable by Python.""" + return len(name) > 4 and name[:2] == name[-2:] == "__" and name not in SPECIAL_METHODS_UNCHANGED + + +# special methods that can still wait when pyscript code calls them (eg, in a with statement), +# as they could before pyscript made special methods callable by Python +SPECIAL_METHODS_CAN_WAIT = frozenset({"__enter__", "__exit__"}) + +# those pyscript methods, keyed by the regular function that stands in for each one +CAN_WAIT_METHODS: weakref.WeakKeyDictionary = weakref.WeakKeyDictionary() + + +def script_traceback(stop, exc): + """Return the traceback of StopIteration stop, with the script frames of exc, which replaced it, first.""" + stop_tb, frames, tb = EXC_TRACEBACK(stop), [], exc.__traceback__ + while tb: + frames.append(tb) + tb = tb.tb_next + for tb in reversed(frames): + stop_tb = TracebackType(stop_tb, tb.tb_frame, tb.tb_lasti, tb.tb_lineno) + return stop_tb + + +def make_special_method(func_var, qualname): + """ + Return a regular function that Python can call for a pyscript special method. + + Python calls a special method itself and needs its result right away, so this runs the + method to the end at once, as generator expressions do with their elements, and a method + that has to wait (eg, for task.sleep()) raises RuntimeError. When pyscript code calls + __enter__ or __exit__ (eg, in a with statement), call_func() calls the pyscript method + itself instead, so those can still wait. + """ + loop = asyncio.get_running_loop() + + def special_method(*args, **kwargs): + try: + running_loop = asyncio.get_running_loop() + except RuntimeError: + running_loop = None + if running_loop is not loop: + # pyscript code isn't thread safe, so it can't run in another thread (eg, task.executor) + raise RuntimeError(f"{qualname}() is a pyscript method, so it can only run in the event loop") + coro = func_var(*args, **kwargs) + stop = None + try: + coro.send(None) + except StopIteration as exc: + return exc.value + except RuntimeError as exc: + # the method raised StopIteration (eg, to end iteration in __next__) + stop = unwrap_stop_iteration(exc) + if stop is exc: + raise + stop_tb = script_traceback(stop, exc) + else: + # + # the method has to wait, which can't be done here, so stop it; whatever it + # was waiting for (eg, a task or a service call) carries on by itself + # + try: + coro.close() + finally: + # raise this even if the method's cleanup (eg, a finally block) tries to wait too + raise RuntimeError( + f"{qualname}() can't wait (eg, for task.sleep()): it runs as a regular function," + " so Python can call it" + ) + # raised outside the handler, so it keeps its own __cause__ and __context__ + raise EXC_WITH_TRACEBACK(stop, stop_tb) + + special_method.__name__ = qualname.rsplit(".", 1)[-1] + special_method.__qualname__ = qualname + special_method.__doc__ = func_var.__doc__ + # share the method's attributes (eg, __isabstractmethod__ from @abstractmethod, or a decorator's) + special_method.__dict__ = func_var.__dict__ + if special_method.__name__ in SPECIAL_METHODS_CAN_WAIT: + CAN_WAIT_METHODS[special_method] = func_var + return special_method + + class EvalName: """Identifier that hasn't yet been resolved.""" @@ -834,6 +937,9 @@ async def __call__(self, /, *args, **kwargs): class AstEval: """Python interpreter AST object evaluator.""" + # set while call_func() formats a call's arguments for debug logging, which can run pyscript code + formatting_call_args = False + def __init__(self, name: str, global_ctx: "GlobalContext", logger_name: str | None = None) -> None: """Initialize an interpreter execution context.""" self.name = name @@ -860,6 +966,7 @@ def __init__(self, name: str, global_ctx: "GlobalContext", logger_name: str | No self.class_sym_tables: list[SymTable] = [] self.class_cell: list[type | None] | None = None self.class_global_names: set[str] = set() + self.class_name: str | None = None self.loop_scopes: tuple[LoopScope, ...] = () self.class_pending_annotations: list[tuple[str, ast.expr]] = [] @@ -1020,6 +1127,7 @@ async def ast_classdef(self, arg): class_cell: list[type | None] = [None] prev_class_cell, self.class_cell = self.class_cell, class_cell prev_class_global_names, self.class_global_names = self.class_global_names, set() + prev_class_name, self.class_name = self.class_name, arg.name prev_pending, self.class_pending_annotations = self.class_pending_annotations, [] try: for arg1 in arg.body: @@ -1034,6 +1142,7 @@ async def ast_classdef(self, arg): self.class_sym_tables.pop() self.class_cell = prev_class_cell self.class_global_names = prev_class_global_names + self.class_name = prev_class_name pending, self.class_pending_annotations = self.class_pending_annotations, prev_pending self.sym_table = self.sym_table_stack.pop() @@ -1184,6 +1293,8 @@ async def executor_wrap(*args, **kwargs): sym_table = self.global_sym_table else: sym_table = self.sym_table + if sym_table is self.class_sym_table: + func_var = self.class_body_value(name, func_var) if name in sym_table and isinstance(sym_table[name], EvalLocalVar): sym_table[name].set(func_var) else: @@ -1375,8 +1486,9 @@ async def with_items(self, arg, items, async_attr): if item.optional_vars: await self.recurse_assign(item.optional_vars, value) val = await self.with_items(arg, items[1:], async_attr) - except (asyncio.CancelledError, KeyboardInterrupt, SystemExit): - # unlike Python, the exit can't suppress these, so tasks can always be stopped + except (asyncio.CancelledError, GeneratorExit, KeyboardInterrupt, SystemExit): + # unlike Python, the exit can't suppress these, so tasks can always be stopped, and so can + # a special method or a generator expression element that tries to wait (GeneratorExit) await self.call_func(exit_func, exit_attr, manager, *sys.exc_info()) raise except Exception as err: # pylint: disable=broad-exception-caught @@ -1509,6 +1621,20 @@ def binds_global(self, var_name): return var_name in self.class_global_names return bool(self.curr_func and var_name in self.curr_func.global_names) + def class_body_value(self, name, value): + """Return what a class body binds to name: a function Python can call, for a pyscript special method.""" + if not is_special_method(name): + return value + if isinstance(value, (classmethod, staticmethod)): + # eg, __init_subclass__ written with @classmethod + func = self.class_body_value(name, value.__func__) + return value if func is value.__func__ else type(value)(func) + # pylint: disable-next=unidiomatic-typecheck + if type(value) is EvalFuncVar and not value.get_func().async_func: + # an async special method returns an awaitable, as in Python + return make_special_method(value, f"{self.class_name}.{name}") + return value + def assign_name(self, var_name, val): """Bind a plain variable name to val, updating an existing EvalLocalVar in place.""" if self.binds_global(var_name): @@ -1516,7 +1642,7 @@ def assign_name(self, var_name, val): return if self.sym_table is self.class_sym_table: # a class body binds plainly in the class namespace (see binds_global) - self.sym_table[var_name] = val + self.sym_table[var_name] = self.class_body_value(var_name, val) return if var_name in self.sym_table and isinstance(self.sym_table[var_name], EvalLocalVar): self.sym_table[var_name].set(val) @@ -2108,13 +2234,7 @@ def genexp_loop(self, arg, iters, loop_vars, gen_vars, gen_scope, scope, loop): stop = unwrap_stop_iteration(exc) if stop is exc: raise - # keep the script frames, which are on the RuntimeError's traceback, before its own - stop_tb, frames, tb = EXC_TRACEBACK(stop), [], exc.__traceback__ - while tb: - frames.append(tb) - tb = tb.tb_next - for tb in reversed(frames): - stop_tb = TracebackType(stop_tb, tb.tb_frame, tb.tb_lasti, tb.tb_lineno) + stop_tb = script_traceback(stop, exc) else: # # the element has to wait, which can't be done here, so stop it; whatever @@ -2273,18 +2393,35 @@ async def call_func(self, func, func_name, /, *args, **kwargs): except Exception: func_name = "" if _LOGGER.isEnabledFor(logging.DEBUG): - try: - arg_str = ", ".join(['"' + elt + '"' if isinstance(elt, str) else str(elt) for elt in args]) - kwargs_str = str(kwargs) - except Exception: - # eg, an instance whose __init__ hasn't run yet, or whose __str__ is a pyscript method + if AstEval.formatting_call_args: + # eg, a pyscript __str__ that calls functions while another call's arguments are formatted arg_str = kwargs_str = "..." + else: + AstEval.formatting_call_args = True + try: + arg_str = ", ".join( + ['"' + elt + '"' if isinstance(elt, str) else str(elt) for elt in args] + ) + kwargs_str = str(kwargs) + except Exception: + # eg, an instance whose __init__ hasn't run yet + arg_str = kwargs_str = "..." + finally: + AstEval.formatting_call_args = False _LOGGER.debug("%s: calling %s(%s, %s)", self.name, func_name, arg_str, kwargs_str) if isinstance(func, (EvalFunc, EvalFuncVar)): return await func.call(self, *args, **kwargs) if isinstance(func, MethodType) and is_pyscript_func(func.__func__): # eg, a pyscript function wrapped by classmethod(), bound to the class return await func.__func__.call(self, func.__self__, *args, **kwargs) + target = func.__func__ if isinstance(func, MethodType) else func + if isinstance(target, FunctionType) and target.__name__ in SPECIAL_METHODS_CAN_WAIT: + method = CAN_WAIT_METHODS.get(target) + if method is not None: + # eg, a with statement or super().__enter__(): call the pyscript method, which can wait + if target is not func: + return await method.call(self, func.__self__, *args, **kwargs) + return await method.call(self, *args, **kwargs) if func is super and not args and not kwargs: return super(*self.super_args()) if inspect.isclass(func): @@ -2326,7 +2463,7 @@ async def call_func(self, func, func_name, /, *args, **kwargs): if inspect.iscoroutinefunction(func): return await func(*args, **kwargs) if callable(func): - if func == time.sleep: # pylint: disable=comparison-with-callable + if func is time.sleep: _LOGGER.warning( "%s calls blocking time.sleep(); replaced with asyncio.sleep()", self.filename ) @@ -2591,7 +2728,7 @@ def set_local_sym_table(self, sym_table): def set_global_ctx(self, global_ctx): """Set the global context.""" self.global_ctx = global_ctx - if self.sym_table == self.global_sym_table: + if self.sym_table is self.global_sym_table: self.global_sym_table = global_ctx.get_global_sym_table() self.sym_table = self.global_sym_table else: diff --git a/docs/reference.rst b/docs/reference.rst index bbc46ca..81df819 100644 --- a/docs/reference.rst +++ b/docs/reference.rst @@ -2645,12 +2645,35 @@ it doesn't faithfully mimic Python. Here are some areas where pyscript differs currently possible to have Python modules and packages call pyscript functions. The workaround is to move your callbacks from pyscript and make them native Python functions; see `Importing <#importing>`__, call a function with the ``@pyscript_compile`` decorator, or a lambda (which is also compiled). -- Continuing that point, special methods (e.g., ``__eq__``) in a class created in `pyscript` will not work since - they are async functions and Python will not be able to call them. The two workarounds are to - use the ``@pyscript_compile`` decorator so the method is compiled to a native (non-async) Python - function, or write your class in native Python and import it into ``pyscript``; see `Importing <#importing>`__. -- ``__init__`` and ``__new__`` are the exceptions: pyscript calls them itself when your code creates an - instance, the way Python does. A class without ``__init__`` uses the first one along its parents, +- These work as in Python for classes created in pyscript, using the special methods shown: + + - ``==``, ``<`` and the other comparisons, also in ``sorted()``, ``min()`` and ``max()`` (``__eq__``, + ``__lt__`` and so on) + - sets and dictionary keys (``__hash__``) + - ``str()``, ``repr()``, f-strings and ``format()`` (``__str__``, ``__repr__``, ``__format__``) + - ``len()``, ``in`` and ``if obj:`` (``__len__``, ``__contains__``, ``__bool__``) + - ``for`` loops, ``list()`` and ``next()`` (``__iter__``, ``__next__``) + - ``obj[key]`` (``__getitem__``, ``__setitem__``, ``__delitem__``) + - ``+``, ``*`` and the other operators (``__add__``, ``__mul__`` and so on) + - calling an instance, ``obj()`` (``__call__``) + - ``with`` statements (``__enter__``, ``__exit__``) + - reading an attribute the object doesn't have (``__getattr__``) + - methods that library code calls, such as a dataclass's ``__post_init__`` + + These limitations apply: + + - A special method can't wait, so it can't call ``task.sleep()``, ``task.wait_until()``, + ``task.executor()`` or a ``@pyscript_executor`` function, or make a service call with + ``blocking=True``; if it waits, it raises ``RuntimeError``. Import modules at the top of the file, + not inside a special method. ``__enter__`` and ``__exit__`` can wait when used in a ``with`` + statement, and so can ``__init__``, ``__new__`` and ``async def`` special methods. Any method whose + name starts and ends with two underscores counts as a special method. + - ``__getattribute__``, ``__setattr__``, ``__delattr__`` and ``__del__`` don't work, and neither does a + pyscript function added to a class after it's created (e.g., ``MyClass.__eq__ = my_eq``). For these, + use the ``@pyscript_compile`` decorator, or write the class in native Python and import it; see + `Importing <#importing>`__. +- pyscript calls ``__init__`` and ``__new__`` itself when your code creates an instance, the way Python + does. A class without ``__init__`` uses the first one along its parents, ``super().__init__(...)``, ``super(Cls, self).__init__(...)`` and ``Base.__init__(self, ...)`` work, and so does ``super()`` without arguments in methods (and in functions defined inside methods). Native base classes, such as ``Exception``, ``dict``, ``str``, ``namedtuple``, ``logging.Handler`` and ``threading.Thread``, @@ -2659,11 +2682,11 @@ it doesn't faithfully mimic Python. Here are some areas where pyscript differs - an instance created by native Python code (e.g., ``collections.defaultdict(MyClass)``) doesn't run a pyscript ``__init__``; only ``obj.__init__`` written out in pyscript finds it, not ``getattr(obj, "__init__")``. - - ``super()`` without arguments doesn't work in ``@pyscript_compile`` functions or lambdas. - - a metaclass ``__call__`` written in pyscript doesn't work. A compiled metaclass ``__call__`` is called - without the constructor's arguments, and the pyscript ``__init__`` is then called with them, on every - call (so a singleton metaclass runs ``__init__`` again each time). - - a dataclass ``__post_init__`` written in pyscript isn't called; use ``@pyscript_compile`` for it. + - ``super()`` without arguments doesn't work in ``@pyscript_compile`` functions or lambdas, or in a + method called while its class is still being created (e.g., by ``__init_subclass__``). + - a metaclass ``__call__`` of a class with a pyscript ``__init__`` is called without the constructor's + arguments, and the ``__init__`` is then called with them, on every call (so a singleton metaclass + runs ``__init__`` again each time). - The ``import`` function in ``pyscript`` fails to import certain complex packages. This is an open bug and it would be great if someone with some Python expertise could help fix it. In the meantime, the workaround is to import the module in a native Python file, and then import that shim module into pyscript. diff --git a/tests/test_unit_eval.py b/tests/test_unit_eval.py index 6ba2f13..78915d9 100644 --- a/tests/test_unit_eval.py +++ b/tests/test_unit_eval.py @@ -8897,6 +8897,12 @@ async def test_stop_iteration_limits(hass): 'File "test", line 5, in None\n native(4)\n', ' File "test", line 3, in native\nStopIteration: 4\n', ], + # from a special method that Python calls + [ + 'class Countdown:\n def __next__(self):\n raise StopIteration("done")\n\nnext(Countdown())\n', + 'File "test", line 3, in __next__\n raise StopIteration("done")\n', + "StopIteration: done\n", + ], ] @@ -8996,3 +9002,778 @@ async def test_stop_iteration_uncaught_report(hass, caplog): await Function.waiter_sync() await Function.waiter_stop() await Function.reaper_stop() + + +# +# special methods of pyscript classes, which Python calls itself; each source sets result, and is +# also run in CPython, where pyscript_compile is a no-op decorator +# +SPECIAL_METHOD_SOURCES = [ + # comparisons, hashing, ordering, and NotImplemented falling back to the other operand + """ +class Money: + def __init__(self, cents): + self.cents = cents + def __eq__(self, other): + if not isinstance(other, Money): + return NotImplemented + return self.cents == other.cents + def __hash__(self): + return hash(self.cents) + def __lt__(self, other): + return self.cents < other.cents + def __repr__(self): + return f"Money({self.cents})" +a, b = Money(1), Money(2) +result = [ + a == Money(1), a == b, a != b, a == 1, a in [b, Money(1)], b in {Money(2)}, len({a, Money(1), b}), + repr(sorted([Money(3), a, b])), repr(max([a, Money(5), b])), {Money(1): "x"}[a], [b, a].index(Money(1)), +] +""", + # a subclass's reflected __eq__ goes first, and NotImplemented falls back to the base class's + """ +class Base: + calls = [] + def __init__(self, v): + self.v = v + def __eq__(self, other): + Base.calls.append(type(self).__name__) + return isinstance(other, Base) and self.v == other.v +class Derived(Base): + def __eq__(self, other): + Base.calls.append("Derived") + return NotImplemented +result = [Base(1) == Derived(1), Base.calls] +""", + # functools.total_ordering; __eq__ without __hash__ makes instances unhashable, as in Python + """ +import functools +@functools.total_ordering +class Version: + def __init__(self, text): + self.parts = tuple(int(part) for part in text.split(".")) + def __eq__(self, other): + return self.parts == other.parts + def __lt__(self, other): + return self.parts < other.parts + def __str__(self): + return ".".join(str(part) for part in self.parts) +versions = [Version("1.10"), Version("1.2"), Version("1.9.1")] +try: + hash(versions[0]) + hashable = True +except TypeError: + hashable = False +result = [[str(v) for v in sorted(versions)], Version("2.0") >= Version("1.99"), Version("1.2") <= Version("1.2"), hashable] +""", + # arithmetic, reflected operators, conversions, truth value and formatting + """ +class Temp: + def __init__(self, degrees): + self.degrees = degrees + def __add__(self, other): + return Temp(self.degrees + (other.degrees if isinstance(other, Temp) else other)) + def __radd__(self, other): + return self + other + def __neg__(self): + return Temp(-self.degrees) + def __float__(self): + return float(self.degrees) + def __bool__(self): + return self.degrees != 0 + def __format__(self, spec): + return format(self.degrees, spec) + " C" + def __str__(self): + return f"{self:.1f}" + def __repr__(self): + return f"Temp({self.degrees!r})" +t = Temp(20.25) +result = [ + str(t + 1), str(1 + t), repr(sum([Temp(1), Temp(2)])), f"{-t:.0f}", float(t), bool(Temp(0)), + Temp(0) or "zero", f"{t!r}", repr([t]), "%s" % t, "{}".format(t), +] +""", + # __index__ for subscripts, range(), hex() and repetition; __round__ and __floor__ + """ +import math +class Level: + def __init__(self, n): + self.n = n + def __index__(self): + return self.n + def __round__(self, ndigits=None): + return round(self.n / 3, ndigits) + def __floor__(self): + return self.n // 4 +lv = Level(5) +result = [["a", "b", "c", "d", "e", "f"][lv], list(range(lv)), hex(lv), round(lv, 2), math.floor(lv), "ab" * Level(2)] +""", + # subclasses of float and str that override special methods and call super() + """ +class Celsius(float): + def __str__(self): + return f"{float(self):.1f} C" + def __add__(self, other): + return Celsius(super().__add__(other)) + __radd__ = __add__ +class Tag(str): + def __repr__(self): + return "Tag(" + super().__repr__() + ")" +t = sum([Celsius(20.5), Celsius(1.25)]) +result = [type(t).__name__, str(t), repr([Tag("a")]), str(Celsius(3) + 1)] +""", + # a container: len, items, slices, membership, iteration, unpacking + """ +class Bag: + def __init__(self, items): + self.items = list(items) + def __len__(self): + return len(self.items) + def __getitem__(self, index): + return self.items[index] + def __setitem__(self, index, value): + self.items[index] = value + def __delitem__(self, index): + del self.items[index] + def __contains__(self, item): + return item in self.items + def __iter__(self): + return iter(self.items) + def __reversed__(self): + return reversed(self.items) +bag = Bag([1, 2, 3, 4]) +bag[0] = 10 +del bag[1] +first, *rest = bag +result = [ + len(bag), bool(Bag([])), 3 in bag, 5 in bag, bag[-1], bag[0:2], list(bag), list(reversed(bag)), + first, rest, sum(x for x in bag), [x * 2 for x in bag], dict(zip(bag, "abc")), +] +""", + # an iterator: StopIteration ends the loop, in pyscript for loops and in Python's built-ins + """ +class Countdown: + def __init__(self, start): + self.current = start + def __iter__(self): + return self + def __next__(self): + if self.current <= 0: + raise StopIteration + self.current -= 1 + return self.current + 1 +def loop(): + seen = [] + for n in Countdown(3): + seen.append(n) + return seen +it = Countdown(2) +result = [list(Countdown(3)), loop(), next(it), next(it), next(it, "done"), sorted(Countdown(4)), max(Countdown(5))] +""", + # a StopIteration raised by __next__ keeps its cause + """ +class Fetcher: + def __init__(self, keys, data): + self.keys = iter(keys) + self.data = data + def __iter__(self): + return self + def __next__(self): + key = next(self.keys) + try: + return self.data[key] + except KeyError as exc: + raise StopIteration("missing " + key) from exc +it = Fetcher(["a", "b"], {"a": 1}) +first = next(it) +try: + next(it) +except StopIteration as exc: + stop = [exc.args, type(exc.__cause__).__name__, exc.__suppress_context__] +result = [first, stop, list(Fetcher(["a", "b", "c"], {"a": 1, "c": 3}))] +""", + # iteration through __getitem__ (bounded, since it never ends if __getitem__ can't raise + # IndexError), __missing__ in a dict subclass, and a list subclass + """ +import itertools +class Squares: + def __getitem__(self, index): + if index >= 4: + raise IndexError(index) + return index * index +class Defaults(dict): + def __missing__(self, key): + return key.upper() +class Loud(list): + def __getitem__(self, index): + return super().__getitem__(index) * 10 + def __len__(self): + return super().__len__() + 100 +d = Defaults(a="1") +result = [list(itertools.islice(Squares(), 10)), d["a"], d["b"], d.get("b"), Loud([1, 2])[1], len(Loud([1]))] +""", + # a Mapping, whose native mixin methods call the pyscript special methods + """ +import collections.abc +class Registry(collections.abc.Mapping): + def __init__(self, data): + self.data = dict(data) + def __getitem__(self, key): + return self.data[key] + def __len__(self): + return len(self.data) + def __iter__(self): + return iter(sorted(self.data)) +reg = Registry({"b": 2, "a": 1}) +result = [dict(reg), reg.get("a"), reg.get("z", 0), "a" in reg, list(reg.items()), reg == {"a": 1, "b": 2}] +""", + # generator expressions in special methods, and special methods in generator expressions + """ +class Item: + def __init__(self, v): + self.v = v + def __eq__(self, other): + return self.v == other.v +class Group: + def __init__(self, items): + self.items = list(items) + def __iter__(self): + return (x for x in self.items) + def __len__(self): + return sum(1 for _ in self.items) + def __contains__(self, item): + return any(x == item for x in self.items) +group = Group([Item(1), Item(2)]) +result = [len(group), Item(2) in group, Item(5) in group, [x.v for x in group], sum(1 for x in group if x == Item(2))] +""", + # special methods that use other pyscript objects' special methods + """ +class P: + def __init__(self, v): + self.v = v + def __eq__(self, other): + return self.v == other.v + def __hash__(self): + return hash(self.v) + def __repr__(self): + return f"P({self.v})" +class Pair: + def __init__(self, a, b): + self.a = a + self.b = b + def __eq__(self, other): + return (self.a, self.b) == (other.a, other.b) + def __hash__(self): + return hash((self.a, self.b)) + def __repr__(self): + return f"Pair({self.a!r}, {self.b!r})" +pairs = [Pair(P(1), P(2)), Pair(P(1), P(2)), Pair(P(2), P(1))] +result = [pairs[0] == pairs[1], pairs[0] == pairs[2], len(set(pairs)), repr({P(3): [pairs[2]]})] +""", + # a __repr__ that calls functions with self, which debug logging formats on each call + """ +class Node: + def __init__(self, name): + self.name = name + def __repr__(self): + return f"<{type(self).__name__} {self.name} {isinstance(self, Node)}>" +def describe(node): + return repr(node) +result = [describe(Node("a")), repr([Node("b")])] +""", + # calling instances, also as a key function, in map() and through functools.partial + """ +import functools +class ByField: + def __init__(self, name): + self.name = name + def __call__(self, item): + return item[self.name] +rows = [{"n": "b", "v": 2}, {"n": "a", "v": 3}] +result = [ + ByField("v")(rows[0]), [r["n"] for r in sorted(rows, key=ByField("n"))], list(map(ByField("v"), rows)), + functools.partial(ByField("n"))(rows[1]), +] +""", + # calling an instance whose class also defines __eq__ + """ +class Rule: + def __init__(self, limit): + self.limit = limit + def __eq__(self, other): + return self.limit == other.limit + def __call__(self, value): + return value > self.limit +result = [Rule(0)(1), list(filter(Rule(1), [0, 1, 2, 3])), Rule(1) == Rule(1)] +""", + # an async special method returns an awaitable, as in Python + """ +import inspect +class AsyncAdder: + async def __call__(self, x): + return x + 1 +coro = AsyncAdder()(1) +result = [inspect.iscoroutine(coro)] +coro.close() +""", + # context managers, in a with statement and in a native contextlib.ExitStack + """ +import contextlib +events = [] +class Suspended: + def __init__(self, name): + self.name = name + def __enter__(self): + events.append(f"pause {self.name}") + return self + def __exit__(self, exc_type, exc, tb): + events.append(f"resume {self.name}") + return exc_type is KeyError +with contextlib.ExitStack() as stack: + for name in ["a", "b"]: + stack.enter_context(Suspended(name)) + events.append("body") +with Suspended("c") as s: + raise KeyError("x") +result = [events, s.name] +""", + # an exception's cause, and an __exit__ run by native code that raises + """ +import contextlib +class Strict: + def __init__(self, v): + self.v = v + def __eq__(self, other): + if not isinstance(other, Strict): + try: + other.v + except AttributeError as exc: + raise TypeError("can't compare") from exc + return self.v == other.v +class Closer: + def __enter__(self): + return self + def __exit__(self, exc_type, exc, tb): + raise KeyError("closing") +errors = [] +try: + Strict(1) == 5 +except TypeError as exc: + errors.append([type(exc).__name__, str(exc), type(exc.__cause__).__name__]) +try: + with contextlib.ExitStack() as stack: + stack.enter_context(Closer()) + raise ValueError("body") +except KeyError as exc: + errors.append([type(exc).__name__, str(exc), type(exc.__context__).__name__]) +result = errors +""", + # a native wrapper of __enter__ runs, and a bound method of a callable without a __name__ works + """ +import functools +import types +calls = [] +@pyscript_compile +def logged(func): + @functools.wraps(func) + def wrapper(*args): + calls.append(func.__name__) + return func(*args) + return wrapper +class Res: + def __enter__(self): + return "res" + def __exit__(self, *args): + return False +Res.__enter__ = logged(Res.__enter__) +with Res() as value: + pass +result = [value, calls, types.MethodType(functools.partial(max, 0), 5)()] +""", + # a dataclass __post_init__, an Enum __str__ and an exception's __str__ + """ +import dataclasses +import enum +@dataclasses.dataclass +class Visit: + name: str + minutes: int = 0 + def __post_init__(self): + self.name = self.name.title() +class Color(enum.Enum): + RED = 1 + def __str__(self): + return self.name.lower() +class DeviceError(Exception): + def __init__(self, device, code): + super().__init__(device, code) + self.device = device + self.code = code + def __str__(self): + return f"{self.device} failed with code {self.code}" +try: + raise DeviceError("pump", 7) +except DeviceError as exc: + message = str(exc) +result = [repr(Visit("front door", 3)), f"{Color.RED}", message] +""", + # super() in special methods, and a subclass that inherits them + """ +class Base: + def __init__(self, value): + self.value = value + def __repr__(self): + return f"{type(self).__name__}({self.value})" + def __eq__(self, other): + return type(self) is type(other) and self.value == other.value +class Child(Base): + def __repr__(self): + return "child " + super().__repr__() +class Other(Base): + pass +result = [repr(Child(1)), Child(1) == Child(1), Child(1) == Base(1), repr([Other(2)]), Other(2) == Other(2)] +""", + # @abstractmethod on a special method, and the attributes a decorator sets on one + """ +import abc +import functools +class Shape(abc.ABC): + @abc.abstractmethod + def __len__(self): + pass +class Square(Shape): + pass +def counted(func): + @functools.wraps(func) + def wrapper(*args): + wrapper.calls += 1 + return func(*args) + wrapper.calls = 0 + return wrapper +class Box: + def __init__(self, items): + self.items = items + @counted + def __len__(self): + return len(self.items) +try: + Square() + made = True +except TypeError: + made = False +box = Box([1, 2]) +result = [made, sorted(Shape.__abstractmethods__), len(box), len(box), Box.__len__.calls, Box.__len__.__wrapped__.__name__] +""", + # __init_subclass__ and __class_getitem__, which Python makes class methods + """ +class Plugin: + registry = [] + def __init_subclass__(cls, kind="plain", **kwargs): + super().__init_subclass__(**kwargs) + cls.kind = kind + Plugin.registry.append(f"{cls.__name__}:{kind}") + def __class_getitem__(cls, item): + return f"{cls.__name__}[{item.__name__}]" +class Light(Plugin, kind="light"): + pass +class Fan(Plugin): + pass +result = [Plugin.registry, Light.kind, Fan.kind, Light[int]] +""", + # descriptors: __set_name__ when the class is created, then __get__, __set__ and __delete__ + """ +class Field: + def __set_name__(self, owner, name): + self.private = "_" + name + def __get__(self, obj, objtype=None): + return self if obj is None else getattr(obj, self.private, 0) + def __set__(self, obj, value): + if value < 0: + raise ValueError("negative") + setattr(obj, self.private, value) + def __delete__(self, obj): + setattr(obj, self.private, -1) +class Thermostat: + target = Field() +t = Thermostat() +out = [t.target] +t.target = 5 +out.append(t.target) +try: + t.target = -1 +except ValueError as exc: + out.append(str(exc)) +del t.target +result = out + [t.target, Thermostat.target.private] +""", + # a metaclass's special methods, and an Enum whose __lt__ native code uses + """ +import heapq +from enum import Enum +class RegistryMeta(type): + def __iter__(cls): + return iter(sorted(cls.items)) + def __len__(cls): + return len(cls.items) + def __repr__(cls): + return f"" +class Devices(metaclass=RegistryMeta): + items = {"fan": 1, "attic": 2} +class Level(Enum): + LOW = 1 + HIGH = 3 + MID = 2 + def __lt__(self, other): + return self.value < other.value +heap = [] +for level in Level: + heapq.heappush(heap, level) +result = [list(Devices), len(Devices), repr(Devices), [heapq.heappop(heap).name for _ in range(3)]] +""", + # a pyscript @property read in a special method, and native code that sorts pyscript objects + """ +class Temp: + def __init__(self, f): + self.f = f + @property + def c(self): + return round((self.f - 32) * 5 / 9) + def __eq__(self, other): + return self.c == other.c + def __hash__(self): + return hash(self.c) + def __lt__(self, other): + return self.c < other.c +@pyscript_compile +def coldest(temps): + return [min(temps).f, len(set(temps))] +result = [Temp(212) == Temp(212.5), coldest([Temp(50), Temp(32), Temp(32.4)])] +""", + # eval() in a method, whose locals include an object with a strict __eq__ + """ +class Strict: + def __init__(self, v): + self.v = v + def __eq__(self, other): + if type(other) is not Strict: + raise TypeError("Strict only compares with Strict") + return self.v == other.v + __hash__ = object.__hash__ + def run(self, expr): + return eval(expr) +result = [Strict(3).run("self.v * 2"), Strict(1) == Strict(1)] +""", + # __getattr__, which Python calls when the normal lookup fails + """ +class Proxy: + def __init__(self, data): + self.data = data + def __getattr__(self, name): + if name in self.data: + return self.data[name] + raise AttributeError(name) +proxy = Proxy({"a": 1}) +result = [proxy.a, getattr(proxy, "b", "default"), hasattr(proxy, "b"), hasattr(proxy, "data")] +""", + # special methods assigned in the class body, and written with @classmethod + """ +import abc +class Version: + def __init__(self, n): + self.n = n + def equals(self, other): + return self.n == other.n + def less(self, other): + return self.n < other.n + __eq__ = equals + __lt__ = less +class Tagged: + tags = [] + @classmethod + def __init_subclass__(cls, tag=None, **kwargs): + super().__init_subclass__(**kwargs) + Tagged.tags.append(tag) + @classmethod + def __class_getitem__(cls, item): + return f"{cls.__name__}[{item.__name__}]" +class TaggedA(Tagged, tag="a"): + pass +class Quacker(abc.ABC): + @classmethod + def __subclasshook__(cls, other): + if hasattr(other, "quack"): + return True + return NotImplemented +class Duck: + def quack(self): + return "quack" +result = [ + Version(1) == Version(1), Version(1) == Version(2), [v.n for v in sorted([Version(3), Version(1), Version(2)])], + Version(1).equals(Version(1)), Tagged.tags, TaggedA[str], issubclass(Duck, Quacker), isinstance(3, Quacker), +] +""", + # a metaclass __call__, here making each class a singleton + """ +class Singleton(type): + instances = {} + def __call__(cls, *args, **kwargs): + if cls not in Singleton.instances: + Singleton.instances[cls] = super().__call__(*args, **kwargs) + return Singleton.instances[cls] +class Manager(metaclass=Singleton): + pass +first = Manager() +second = Manager() +result = [first is second, type(first).__name__] +""", +] + + +async def test_special_methods_match_python(hass, caplog): + """Test special methods of pyscript classes, which Python calls itself, compared with CPython.""" + hass.data[DOMAIN] = {CONFIG_ENTRY: MockConfigEntry(domain=DOMAIN, data={CONF_ALLOW_ALL_IMPORTS: True})} + Function.init(hass) + State.init(hass) + State.register_functions() + DecoratorRegistry.init(hass) + + # debug logging formats each call's arguments, which runs pyscript __str__ and __repr__ methods + for level in [logging.INFO, logging.DEBUG]: + caplog.set_level(level, logger="custom_components.pyscript.eval") + for source in SPECIAL_METHOD_SOURCES: + expected_ns = {"pyscript_compile": lambda func: func} + exec(compile(source, "test", "exec"), expected_ns) # pylint: disable=exec-used + global_ctx = GlobalContext("test", global_sym_table={}, manager=GlobalContextMgr) + ast = AstEval("test", global_ctx=global_ctx) + Function.install_ast_funcs(ast) + ast.parse(source) + await ast.eval() + assert global_ctx.global_sym_table["result"] == expected_ns["result"], source + assert ast.sym_table is ast.global_sym_table and not ast.sym_table_stack, source + + await Function.waiter_sync() + await Function.waiter_stop() + await Function.reaper_stop() + + +SPECIAL_METHOD_WAIT_TESTS = [ + """ +class Slow: + def __eq__(self, other): + task.sleep(0.01) + return True +result = Slow() == Slow() +""", + """ +def slow_text(): + task.sleep(0) + return "slow" +class Slow: + def __str__(self): + return slow_text() +result = str(Slow()) +""", + """ +import asyncio +class Slow: + def __len__(self): + asyncio.sleep(0) + return 1 +result = len(Slow()) +""", + """ +class Slow: + def __eq__(self, other): + try: + task.sleep(0.01) + finally: + task.sleep(0) + return True +result = Slow() == Slow() +""", + """ +import threading +lock = threading.Lock() +class Slow: + def __str__(self): + with lock: + task.sleep(0.01) + return "slow" +try: + result = str(Slow()) +finally: + # the with statement released the lock when the method was stopped + unlocked = not lock.locked() +""", +] + + +async def test_special_method_errors(hass): + """Test the errors for a special method that waits or runs in another thread, and the ones that can wait.""" + hass.data[DOMAIN] = {CONFIG_ENTRY: MockConfigEntry(domain=DOMAIN, data={CONF_ALLOW_ALL_IMPORTS: True})} + Function.init(hass) + State.init(hass) + State.register_functions() + TaskFunctions.register_functions() + + global_ctx = GlobalContext("test", global_sym_table={}, manager=GlobalContextMgr) + ast = AstEval("test", global_ctx=global_ctx) + Function.install_ast_funcs(ast) + for source in SPECIAL_METHOD_WAIT_TESTS: + ast.parse("x = 'keep'\n" + source) + with pytest.raises(RuntimeError, match=r"^Slow\.__\w+__\(\) can't wait"): + await ast.eval() + assert "result" not in global_ctx.global_sym_table, source + assert global_ctx.global_sym_table.pop("unlocked", True), source + assert ast.sym_table is ast.global_sym_table and not ast.sym_table_stack, source + # later code runs normally + ast.parse("result = [x, sum(x for x in range(4))]") + await ast.eval() + assert global_ctx.global_sym_table.pop("result") == ["keep", 6], source + + # __enter__ and __exit__ can wait when pyscript code calls them, and an async method can wait too + ast.parse( + """ +class Ctx: + def __enter__(self): + task.sleep(0.01) + return "entered" + def __exit__(self, *args): + task.sleep(0.01) + return True +class Sub(Ctx): + def __enter__(self): + return "sub " + super().__enter__() +class AsyncAdder: + async def __call__(self, x): + task.sleep(0.01) + return x + 1 +async def add_one(): + return await AsyncAdder()(1) +with Sub() as value: + raise KeyError("suppressed by __exit__") +result = [value, add_one()] +""" + ) + await ast.eval() + assert global_ctx.global_sym_table.pop("result") == ["sub entered", 2] + + # a special method can only run in the event loop's thread + ast.parse( + """ +class Money: + def __init__(self, cents): + self.cents = cents + def __lt__(self, other): + return self.cents < other.cents +task.executor(sorted, [Money(2), Money(1)]) +""" + ) + with pytest.raises( + RuntimeError, match=r"^Money\.__lt__\(\) is a pyscript method, so it can only run in the event loop$" + ): + await ast.eval() + + await Function.waiter_sync() + await Function.waiter_stop() + await Function.reaper_stop() From 64f8bae085007d0cfcd030c35e59b282492c4c62 Mon Sep 17 00:00:00 2001 From: jfriend00 Date: Wed, 2 Dec 2026 22:42:21 -0800 Subject: [PATCH 2/2] Preserve existing behavior for eval() --- custom_components/pyscript/eval.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/custom_components/pyscript/eval.py b/custom_components/pyscript/eval.py index 89265f6..48b1120 100644 --- a/custom_components/pyscript/eval.py +++ b/custom_components/pyscript/eval.py @@ -129,7 +129,7 @@ async def eval_func(arg_str, eval_globals=None, eval_locals=None): # if eval_globals is None and eval_ast.sym_table is not ast_ctx.sym_table: for var, value in eval_ast.sym_table.items(): - if var in ast_ctx.global_sym_table and value is ast_ctx.global_sym_table[var]: + if var in ast_ctx.global_sym_table and value == ast_ctx.global_sym_table[var]: continue if var not in ast_ctx.sym_table and ( ast_ctx.curr_func is None or var not in ast_ctx.curr_func.local_names