diff --git a/custom_components/pyscript/eval.py b/custom_components/pyscript/eval.py index b8162e6..5cbde34 100644 --- a/custom_components/pyscript/eval.py +++ b/custom_components/pyscript/eval.py @@ -103,6 +103,7 @@ "sym_table", "sym_table_stack", "curr_func", + "genexp_iter", "code_str", "code_list", "class_sym_table", @@ -354,6 +355,8 @@ def __init__( self.doc_string = ast.get_docstring(func_def) self.num_posonly_arg = len(self.func_def.args.posonlyargs) self.num_posn_arg = self.num_posonly_arg + len(self.func_def.args.args) - len(self.defaults) + # like Python's __class__ cell: holds the class whose body defined this method, for super() + self.class_cell: list[type | None] | None = None self.code_list = code_list self.code_str = code_str self.trigger = [] @@ -811,6 +814,8 @@ async def call(self, ast_ctx, *args, **kwargs): code_str, code_list = ast_ctx.code_str, ast_ctx.code_list ast_ctx.code_str, ast_ctx.code_list = self.code_str, self.code_list prev_func = ast_ctx.curr_func + prev_genexp_iter = ast_ctx.genexp_iter + ast_ctx.genexp_iter = None save_user_locals = ast_ctx.user_locals ast_ctx.user_locals = {} ast_ctx.curr_func = self @@ -824,6 +829,7 @@ async def call(self, ast_ctx, *args, **kwargs): return None finally: ast_ctx.curr_func = prev_func + ast_ctx.genexp_iter = prev_genexp_iter ast_ctx.user_locals = save_user_locals ast_ctx.code_str, ast_ctx.code_list = code_str, code_list if prev_sym_table is not None: @@ -957,6 +963,7 @@ def __init__(self, name: str, global_ctx: "GlobalContext", logger_name: str | No self.local_sym_table: SymTable = {} self.user_locals: SymTable = {} self.curr_func: EvalFunc | None = None + self.genexp_iter = None # the outermost iterator of the generator expression being evaluated self.filename = name self.code_str: str | None = None self.code_list: list[str] | None = None @@ -966,6 +973,7 @@ def __init__(self, name: str, global_ctx: "GlobalContext", logger_name: str | No self.config_entry = Function.hass.data.get(DOMAIN, {}).get(CONFIG_ENTRY, {}) self.dec_eval_depth = 0 self.class_sym_table: SymTable | None = None + self.class_cell: list[type | None] | None = None self.class_global_names: set[str] = set() self.class_pending_annotations: list[tuple[str, ast.expr]] = [] @@ -1122,6 +1130,8 @@ async def ast_classdef(self, arg): self.sym_table_stack.append(self.sym_table) self.sym_table = sym_table prev_class_sym_table, self.class_sym_table = self.class_sym_table, sym_table + 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_pending, self.class_pending_annotations = self.class_pending_annotations, [] try: @@ -1134,18 +1144,27 @@ async def ast_classdef(self, arg): finally: # restore the enclosing scope even if the class body raises and the exception is caught self.class_sym_table = prev_class_sym_table + self.class_cell = prev_class_cell self.class_global_names = prev_class_global_names pending, self.class_pending_annotations = self.class_pending_annotations, prev_pending self.sym_table = self.sym_table_stack.pop() decorators = [await self.aeval(dec) for dec in arg.decorator_list] - sym_table["__init__evalfunc_wrap__"] = None - if "__init__" in sym_table: + init_func = sym_table["__init__"] if "__init__" in sym_table else None + if isinstance(init_func, staticmethod): + init_func = init_func.__func__ + if isinstance(init_func, (EvalFunc, EvalFuncVar)): + # + # Python can't call our async __init__, so rename it; call_func() calls + # it when it creates an instance (a compiled __init__ is left to Python) + # sym_table["__init__evalfunc_wrap__"] = sym_table["__init__"] del sym_table["__init__"] - cls = metaclass(arg.name, tuple(bases), sym_table, **keywords) + # create the class like any other instance, so a pyscript metaclass __new__ or __init__ is called + cls = await self.call_func(metaclass, None, arg.name, tuple(bases), sym_table, **keywords) if inspect.iscoroutine(cls): cls = await cls + class_cell[0] = cls if pending: await self.eval_pending_annotations(cls, arg.name, pending) for dec_func in reversed(decorators): @@ -1227,6 +1246,11 @@ async def executor_wrap(*args, **kwargs): return func = EvalFunc(arg, self.code_list, self.code_str, self.global_ctx, async_func) + if self.sym_table is self.class_sym_table: + func.class_cell = self.class_cell + elif self.curr_func: + # as in Python, a function inside a method shares that method's __class__ + func.class_cell = self.curr_func.class_cell await func.eval_defaults(self) await func.resolve_nonlocals(self) name = func.get_name() @@ -1356,6 +1380,9 @@ async def ast_raise(self, arg): """Execute raise statement.""" if arg.exc: exc = await self.aeval(arg.exc) + if inspect.isclass(exc) and issubclass(exc, BaseException): + # create the instance here, so a pyscript __init__ is called + exc = await self.call_func(exc, None) if arg.cause: cause = await self.aeval(arg.cause) raise exc from cause @@ -1624,6 +1651,8 @@ async def ast_attribute(self, arg): val = await self.aeval(arg.value) if isinstance(arg.ctx, ast.Store): return EvalAttrSet(val, arg.attr) + if arg.attr == "__init__" and (init_func := self.init_attr(val)) is not None: + return init_func return getattr(val, arg.attr) async def ast_name(self, arg): @@ -2039,6 +2068,7 @@ async def ast_generatorexp(self, arg): loop_vars, _ = await self.loopvar_scope_save(arg.generators) scope = {attr: getattr(self, attr) for attr in GENEXP_SCOPE_ATTRS} scope["sym_table_stack"] = self.sym_table_stack.copy() + scope["genexp_iter"] = iters[0] # what Python passes to the generator as its first argument gen = self.genexp_loop(arg, iters, loop_vars, scope, asyncio.get_running_loop()) gen.__name__ = gen.__qualname__ = "" return gen @@ -2084,6 +2114,67 @@ async def ast_call(self, arg): func = func.get() return await self.call_func(func, func_name, *args, **kwargs) + @staticmethod + def class_init(mro): + """Return the renamed pyscript __init__ Python would find first in mro, or None if it's native.""" + for klass in mro: + if "__init__evalfunc_wrap__" in klass.__dict__: + return klass.__dict__["__init__evalfunc_wrap__"] + if "__init__" in klass.__dict__: + return None + return None + + @staticmethod + def bind_init(init_func, obj, cls): + """Bind a renamed __init__ to obj like Python's attribute lookup does; a static one stays unbound.""" + return init_func.__get__(obj, cls) # pylint: disable=unnecessary-dunder-call + + def init_attr(self, val): + """Return the pyscript __init__ for val.__init__, or None to use Python's attribute lookup.""" + if isinstance(val, super): + # + # super(cls, obj).__init__ searches the mro of obj (or of its type) after cls + # + mro = val.__self_class__.__mro__ if val.__self_class__ is not None else () + init_func = self.class_init(mro[mro.index(val.__thisclass__) + 1 :] if mro else ()) + if init_func is None: + return None + obj = None if val.__self__ is val.__self_class__ else val.__self__ + return self.bind_init(init_func, obj, val.__self_class__) + if inspect.isclass(val): + init_func = self.class_init(val.__mro__) + return None if init_func is None else self.bind_init(init_func, None, val) + if "__init__" in getattr(val, "__dict__", {}): + # as in Python, an __init__ set on the instance comes before the class's + return None + init_func = self.class_init(type(val).__mro__) + return None if init_func is None else self.bind_init(init_func, val, type(val)) + + def super_args(self): + """Return the arguments of a zero-argument super(), which Python finds in the calling method.""" + func = self.curr_func + if self.genexp_iter is not None: + # in a generator expression's element, Python's first argument is the outermost iterator + if not func or func.class_cell is None: + raise RuntimeError("super(): __class__ cell not found") + if func.class_cell[0] is None: + raise RuntimeError("super(): empty __class__ cell") + return func.class_cell[0], self.genexp_iter + func_args = func.func_def.args.posonlyargs + func.func_def.args.args if func else [] + if not func or not func_args: + raise RuntimeError("super(): no arguments") + if func.class_cell is None: + raise RuntimeError("super(): __class__ cell not found") + if func.class_cell[0] is None: + raise RuntimeError("super(): empty __class__ cell") + first_arg = self.sym_table.get(func_args[0].arg, EvalLocalVar(func_args[0].arg)) + if isinstance(first_arg, EvalLocalVar): + # a method that defines a function keeps its local variables in EvalLocalVars + if not first_arg.is_defined(): + raise RuntimeError("super(): arg[0] deleted") + first_arg = first_arg.get() + return func.class_cell[0], first_arg + async def call_func(self, func, func_name, *args, **kwargs): """Call a function with the given arguments.""" if func_name is None: @@ -2094,19 +2185,54 @@ async def call_func(self, func, func_name, *args, **kwargs): func_name = func.__name__ except Exception: func_name = "" - arg_str = ", ".join(['"' + elt + '"' if isinstance(elt, str) else str(elt) for elt in args]) - _LOGGER.debug("%s: calling %s(%s, %s)", self.name, func_name, arg_str, kwargs) + 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 + arg_str = kwargs_str = "..." + _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 inspect.isclass(func) and hasattr(func, "__init__evalfunc_wrap__"): - has_init_wrapper = getattr(func, "__init__evalfunc_wrap__") is not None - inst = func(*args, **kwargs) if not has_init_wrapper else func() - if has_init_wrapper: + if func is super and not args and not kwargs: + return super(*self.super_args()) + if inspect.isclass(func): + init_func = self.class_init(func.__mro__) + new_func = func.__new__ + if type(func).__call__ is not type.__call__: + # + # the metaclass has its own __call__, so let it create the instance, + # and then call our __init__, which Python doesn't see # - # since our __init__ function is async, call the renamed one + if init_func is not None: + inst = func() + await self.bind_init(init_func, inst, type(inst)).call(self, *args, **kwargs) + return inst + elif init_func is not None or isinstance(new_func, (EvalFunc, EvalFuncVar)): # - await inst.__init__evalfunc_wrap__.call(self, *args, **kwargs) - return inst + # Python can't call our async __init__ or __new__, so create the instance + # like type.__call__ does: call __new__, and then __init__ if __new__ + # returned an instance of the class + # + if isinstance(new_func, (EvalFunc, EvalFuncVar)): + inst = await new_func.call(self, func, *args, **kwargs) + elif new_func is object.__new__: + # object.__new__ rejects extra arguments, since our __init__ is renamed + inst = object.__new__(func) + else: + # a native __new__ (eg, of str, tuple or Exception) needs the arguments + inst = new_func(func, *args, **kwargs) + if not isinstance(inst, func): + return inst + init_func = self.class_init(type(inst).__mro__) + if init_func is None: + type(inst).__init__(inst, *args, **kwargs) # pylint: disable=unnecessary-dunder-call + return inst + ret = await self.bind_init(init_func, inst, type(inst)).call(self, *args, **kwargs) + if ret is not None: + raise TypeError(f"__init__() should return None, not '{type(ret).__name__}'") + return inst if inspect.iscoroutinefunction(func): return await func(*args, **kwargs) if callable(func): diff --git a/docs/reference.rst b/docs/reference.rst index 853aea9..8226ea6 100644 --- a/docs/reference.rst +++ b/docs/reference.rst @@ -2385,6 +2385,21 @@ it doesn't faithfully mimic Python. Here are some areas where pyscript differs 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, + ``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``, + get the constructor's arguments as they would in Python. What still differs from Python: + + - 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. - 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 c3cbb54..ae254fd 100644 --- a/tests/test_unit_eval.py +++ b/tests/test_unit_eval.py @@ -4,6 +4,7 @@ import asyncio import contextlib from dataclasses import dataclass +import logging import sys from types import FunctionType, ModuleType @@ -4334,3 +4335,496 @@ async def test_generator_expression_errors(hass): await Function.waiter_sync() await Function.waiter_stop() await Function.reaper_stop() + + +# +# each source sets result; pyscript_compile is a no-op decorator when run in CPython +# +CLASS_INIT_SUPER_SOURCES = [ + # zero-argument and two-argument super() in methods and __init__ + """ +class B: + def __init__(self, x): + self.x = x + def f(self): + return "B" +class C(B): + def __init__(self, x, y): + super().__init__(x) + self.y = y + def f(self): + return "C" + super().f() +class D(B): + def __init__(self, x, y): + super(D, self).__init__(x) + self.y = y + def f(self): + return "D" + super(D, self).f() +c, d = C(1, 2), D(3, 4) +result = [c.x, c.y, c.f(), d.x, d.y, d.f()] +""", + # Base.__init__(self, ...), and calling __init__ again on an instance + """ +class B: + def __init__(self, x, k=0): + self.x = x + self.k = k +class C(B): + def __init__(self, x): + B.__init__(self, x, k=5) +c = C(1) +c.__init__(7) +result = [c.x, c.k] +""", + # a subclass without __init__ uses the first one along its parents + """ +class A: + def __init__(self, *args, k=1, **kwargs): + self.args, self.k, self.kwargs = args, k, kwargs +class B(A): + pass +class C(B): + pass +c = C(1, 2, k=3, z=4) +result = [c.args, c.k, c.kwargs, type(c).__name__, isinstance(c, A)] +""", + """ +class A: + def __init__(self): + self.a = 1 +class B(A): + def __init__(self): + super().__init__() + self.b = 2 +class C(B): + pass +c = C() +result = [c.a, c.b] +""", + # a native base, with and without an __init__ of our own + """ +class D(dict): + pass +class E(dict): + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + self.extra = 1 +e = E([("a", 1)], b=2) +result = [D(a=1), dict(e), e.extra] +""", + # custom exceptions keep their message and args + """ +class E1(Exception): + pass +class E2(Exception): + def __init__(self, msg, code): + super().__init__(msg) + self.code = code +class E3(E2): + pass +class E4(Exception): + def __init__(self, msg): + self.msg = msg +class E5(Exception): + def __init__(self): + super().__init__("default") +result = [] +for cls, args in [[E1, ["boom", 1]], [E2, ["bad", 3]], [E3, ["worse", 4]], [E4, ["hi"]]]: + try: + raise cls(*args) + except Exception as exc: + result.append([type(exc).__name__, str(exc), exc.args, getattr(exc, "code", None)]) +try: + raise E5 +except E5 as exc: + result.append([str(exc), exc.args]) +""", + # logging.Handler subclasses + """ +import logging +class H1(logging.Handler): + def __init__(self, tag): + super().__init__() + self.tag = tag +class H2(logging.Handler): + def __init__(self, tag): + logging.Handler.__init__(self, level=5) + self.tag = tag +class H3(logging.Handler): + pass +h1, h2, h3 = H1("t1"), H2("t2"), H3(10) +result = [h1.tag, h1.level, h2.tag, h2.level, h3.level, hasattr(h1, "lock"), hasattr(h3, "filters")] +""", + # threading.Thread subclasses + """ +import threading +class T1(threading.Thread): + def __init__(self, n): + super().__init__(name=n, daemon=True) + self.n = n +class T2(threading.Thread): + pass +t1, t2 = T1("x"), T2(name="y", daemon=True) +result = [t1.name, t1.daemon, t1.n, t2.name, t2.daemon, t1.is_alive()] +""", + # str and namedtuple bases, which need the arguments in __new__ + """ +from collections import namedtuple +class S1(str): + def shout(self): + return self.upper() +class S2(str): + def __init__(self, v): + self.extra = len(v) +class P1(namedtuple("P", "a b")): + def s(self): + return self.a + self.b +class P2(P1): + pass +class P3(namedtuple("P", "a b")): + def __init__(self, a, b): + self.total = a + b +s2, p3 = S2("hi"), P3(1, 2) +result = [S1("hi").shout(), s2, s2.extra, P1(1, 2).s(), P2(3, b=4).s(), tuple(p3), p3.total] +""", + # diamond inheritance and mixins follow the mro + """ +log = [] +class A: + def __init__(self): + log.append("A") +class B(A): + def __init__(self): + log.append("B") + super().__init__() +class C(A): + def __init__(self): + log.append("C") + super().__init__() +class D(B, C): + def __init__(self): + log.append("D") + super().__init__() +class E(B, C): + pass +class F(B, C): + def __init__(self): + log.append("F") + super(B, self).__init__() +D() +E() +F() +result = [log, [k.__name__ for k in D.__mro__]] +""", + """ +class Hello: + def hello(self): + return "hi " + self.name +class Named: + def __init__(self, name, **kwargs): + super().__init__(**kwargs) + self.name = name +class N(Hello, Named, dict): + pass +n = N("bob", a=1) +result = [n.hello(), dict(n)] +""", + # metaclasses: one without __call__, with a pyscript __new__ or __init__, and with a compiled __call__ + """ +class Meta1(type): + pass +class Reg(type): + names = [] + def __init__(cls, name, bases, ns): + super().__init__(name, bases, ns) + Reg.names.append(name) +class Meta2(type): + def __new__(mcs, name, bases, ns): + cls = super().__new__(mcs, name, bases, ns) + cls.tag = name.lower() + return cls +class Meta3(type): + @pyscript_compile + def __call__(cls, *args, **kwargs): + inst = type.__call__(cls, *args, **kwargs) + inst.called = True + return inst +class A(metaclass=Meta1): + def __init__(self, v): + self.v = v +class B(metaclass=Meta2): + def __init__(self, v): + self.v = v +class C(metaclass=Meta3): + def __init__(self, v): + self.v = v +class D(metaclass=Meta3): + pass +class E(metaclass=Reg): + pass +class F(E): + pass +c = C(3) +result = [A(1).v, B(2).v, B.tag, c.v, c.called, D().called, Reg.names, type(Reg("G", (), {})).__name__, Reg.names] +""", + """ +from abc import ABC +class B(ABC): + def __init__(self, v): + self.v = v +class C(B): + def f(self): + return self.v +result = [C(4).f(), isinstance(C(5), B)] +""", + # a pyscript __new__ alone, with __init__, and returning another type + """ +class A: + def __new__(cls, *args): + inst = super().__new__(cls) + inst.made = args + return inst +class B: + def __new__(cls, v): + inst = super().__new__(cls) + inst.order = ["new"] + return inst + def __init__(self, v): + self.order.append("init") + self.v = v +class C(B): + pass +class D: + def __new__(cls, v): + return v + def __init__(self, v): + raise ValueError("not called") +class S(str): + def __new__(cls, v): + return super().__new__(cls, v.upper()) +class T: + @staticmethod + def __new__(cls, v): + inst = super().__new__(cls) + inst.v = v + return inst +b, c = B(1), C(2) +result = [A(1, 2).made, b.order, b.v, c.order, c.v, type(c).__name__, D(5), S("hi"), T(6).v] +""", + # compiled __init__s, also inherited and called through super() + """ +class A: + @pyscript_compile + def __init__(self, v): + self.v = v +class B(A): + pass +class C(A): + def __init__(self, v): + super().__init__(v + 1) + A.__init__(self, self.v + 1) +result = [A(1).v, B(2).v, C(3).v] +""", + # a static __init__, and an __init__ set on the instance + """ +log = [] +class A: + @staticmethod + def __init__(x): + log.append(x) +class B(A): + pass +class C: + def __init__(self): + self.x = 1 +A(3) +B(4) +A.__init__(5) +c = C() +def reset(): + c.x = 2 +c.__init__ = reset +c.__init__() +result = [log, c.x, type(C()).__name__] +""", + # __init__ must return None + """ +class A: + def __init__(self): + return 3 +try: + A() + result = "no error" +except TypeError as exc: + result = str(exc) +""", + # super() in a function defined in a method, in a method with a closure, and in a decorated class + """ +class B: + def f(self): + return "B" +class C(B): + def f(self): + def inner(me): + return super().f() + return "C" + inner(self) + def g(self): + def get(): + return self + return super().f() + type(get()).__name__ +def deco(cls): + class Wrapped(cls): + pass + return Wrapped +@deco +class D(B): + def f(self): + return "D" + super().f() +result = [C().f(), C().g(), D().f(), type(D()).__name__] +""", + # classes defined inside a function + """ +def make(base_v): + class B: + def __init__(self, v): + self.v = v + base_v + class C(B): + def __init__(self, v): + super().__init__(v) + self.w = self.v * 2 + class D(C): + pass + return D +D = make(10) +d = D(1) +result = [d.v, d.w] +""", + # dataclasses keep their generated __init__ + """ +from dataclasses import dataclass, field +@dataclass +class P: + x: int + y: int = 2 + z: list = field(default_factory=list) +@dataclass +class Q: + x: int + @pyscript_compile + def __post_init__(self): + self.double = self.x * 2 +class R(P): + def total(self): + return self.x + self.y +result = [repr(P(1)), Q(3).double, R(3, 4).total()] +""", + # errors from a zero-argument super(), as in Python + """ +def f(x): + return super() +class A: + def f(): + return super() + def g(self): + del self + return super() + def h(self): + return super() + try: + h(1) + except RuntimeError as exc: + empty = str(exc) +result = [A.empty] +for func, args in [[f, [1]], [A.f, []], [A.g, [A()]]]: + try: + func(*args) + except RuntimeError as exc: + result.append(str(exc)) +""", + # zero-argument super() in a generator expression's element uses the generator's iterator, as in Python + """ +class B: + def f(self): + return self.n +class C(B): + def __init__(self, n): + self.n = n + self.done = False + @pyscript_compile + def __iter__(self): + return self + @pyscript_compile + def __next__(self): + if self.done: + raise StopIteration + self.done = True + return 0 + def values(self, other): + return (super().f() for _ in other) + def nested(self, other): + # the inner generator's iterator is a list iterator, but super() is in the outer element + return list(list(super().f() for _ in other) for _ in other) + def outermost(self, other): + # only the outermost iterable is evaluated in the method, so super() there is the method's + return list(0 for _ in [super().f()] if _ == 10 for _ in other) + def cond(self, other): + return list(1 for _ in other if super().f() == 20) + def plain(self): + return list(super().f() for _ in range(2)) + def explicit(self): + return list(super(C, self).f() for _ in range(2)) +result = [list(C(10).values(C(20))), list(C(10).cond(C(20))), C(10).outermost(C(1))] +c = C(10) +for func, args in [[c.plain, []], [c.explicit, []], [c.nested, [C(1)]]]: + try: + result.append(func(*args)) + except (TypeError, RuntimeError) as exc: + result.append(str(exc)) +""", + """ +ONE = [1] # a name, since Python makes a tuple of a literal list +def g(): + return (super().f() for _ in ONE) +class B: + def f(self): + return 1 +class C(B): + def values(self): + return (super().f() for _ in ONE) + def values2(self): + return (list(y for y in [super().f()]) for _ in ONE) +result = [] +for func in [g, C().values, C().values2]: + try: + result.append(list(func())) + except (TypeError, RuntimeError) as exc: + result.append(str(exc)) +""", +] + + +async def test_class_init_super_match_python(hass, caplog): + """Test inherited __init__, Base.__init__ and super() in classes, 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() + TrigTime.init(hass) + DecoratorRegistry.init(hass) + + # debug logging formats the call arguments, which can include an instance whose __init__ hasn't run + for level in [logging.INFO, logging.DEBUG]: + caplog.set_level(level, logger="custom_components.pyscript.eval") + for source in CLASS_INIT_SUPER_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 + "result\n") + assert await ast.eval() == expected_ns["result"], source + + await Function.waiter_sync() + await Function.waiter_stop() + await Function.reaper_stop()