diff --git a/custom_components/pyscript/eval.py b/custom_components/pyscript/eval.py index 88d24d4..dc04ff4 100644 --- a/custom_components/pyscript/eval.py +++ b/custom_components/pyscript/eval.py @@ -839,21 +839,38 @@ async def check_for_closure(self, arg): class EvalFuncVar: """Class for a callable pyscript function.""" + # keep our own fields out of __dict__, so functools.wraps() can't copy them onto a wrapper + __slots__ = ("__dict__", "__weakref__", "ast_ctx", "func") + def __init__(self, func: EvalFunc) -> None: """Initialize instance with given EvalFunc function.""" self.func = func self.ast_ctx: AstEval | None = None + @property + def __name__(self): + """Return the function name, like a Python function.""" + return self.func.get_name() + + @__name__.setter + def __name__(self, name): + """Set the function name, eg by functools.wraps().""" + self.func.set_name(name) + + @property + def __doc__(self): + """Return the function doc string, like a Python function.""" + return self.func.get_doc_string() + + @__doc__.setter + def __doc__(self, doc_string): + """Set the function doc string, eg by functools.wraps().""" + self.func.doc_string = doc_string + def get_func(self) -> EvalFunc: """Return the EvalFunc function.""" return self.func - def remove_func(self): - """Remove and return the EvalFunc function.""" - func = self.func - self.func = None - return func - async def call(self, ast_ctx, *args, **kwargs): """Call the EvalFunc function.""" return await self.func.call(ast_ctx, *args, **kwargs) @@ -896,6 +913,10 @@ async def __call__(self, *args, **kwargs): class EvalFuncVarClassInst(EvalFuncVar): """Class for a callable pyscript class instance function.""" + __slots__ = ("class_inst",) + # our class doc string would otherwise hide the __doc__ property, which returns the method's + __doc__ = EvalFuncVar.__doc__ + def __init__(self, func: EvalFunc, ast_ctx: "AstEval", class_inst: Any) -> None: """Initialize instance with given EvalFunc function.""" super().__init__(func) @@ -1190,17 +1211,30 @@ async def executor_wrap(*args, **kwargs): dec_trig, dec_other, dec_dm = await func.eval_decorators(self) self.dec_eval_depth += 1 for dec_func in dec_other: - func = await self.call_func(dec_func, None, func) + if isinstance(func, EvalFunc): + # pass decorators an EvalFuncVar, like a Python function object; functools.wraps() + # then only updates its __dict__, not the fields of the wrapper's EvalFunc + func = EvalFuncVar(func) + func.set_ast_ctx(self) + func_arg = func + func = await self.call_func(dec_func, None, func_arg) if isinstance(func, EvalFuncVar): # set the function name back to its original instead of the decorator function we just called func.set_name(name) - func = func.remove_func() - dec_trig += func.decorators - dec_dm += func.dm_decorators + if func is not func_arg: + dec_trig += func.get_func().decorators + dec_dm += func.get_func().dm_decorators elif isinstance(func, EvalFunc): func.set_name(name) self.dec_eval_depth -= 1 if isinstance(func, EvalFunc): + func = EvalFuncVar(func) + if isinstance(func, EvalFuncVar): + # keep the EvalFuncVar a decorator returned, since the decorator may hold + # references to it and may have set attributes like __wrapped__ on it + func_var = func + func_var.set_ast_ctx(self) + func = func_var.get_func() func.decorators = dec_trig func.dm_decorators = dec_dm if self.dec_eval_depth == 0: @@ -1209,14 +1243,9 @@ async def executor_wrap(*args, **kwargs): await func.trigger_init(self.global_ctx, name) except Exception as e: self.log_exception(e) - func_var = EvalFuncVar(func) - func_var.set_ast_ctx(self) if len(dec_dm) > 0: await self.get_global_ctx().create_decorator_manager(dec_dm, self, func_var) - else: - func_var = EvalFuncVar(func) - func_var.set_ast_ctx(self) else: func_var = func diff --git a/tests/test_unit_eval.py b/tests/test_unit_eval.py index 0ef8d9b..2e39916 100644 --- a/tests/test_unit_eval.py +++ b/tests/test_unit_eval.py @@ -1217,6 +1217,187 @@ def func(incr): ], [ """ +from functools import wraps + +errors = [] + +def catch_all(func): + @wraps(func) + def wrapper(*args, **kwargs): + try: + return func(*args, **kwargs) + except Exception as exc: + errors.append(str(exc)) + return "caught" + return wrapper + +@catch_all +def fails(value): + raise ValueError(f"bad value {value}") + +[fails(1), fails(value=2), errors] +""", + ["caught", "caught", ["bad value 1", "bad value 2"]], + ], + [ + """ +from functools import wraps + +calls = [] + +def trace(func): + @wraps(func) + def wrapper(*args, **kwargs): + calls.append([args, kwargs]) + return func(*args, **kwargs) * 10 + return wrapper + +@trace +def add(a, b=2, *, c=3): + return a + b + c + +[add(1), add(1, 5, c=7), add(a=4, b=0, c=0), calls] +""", + [60, 130, 40, [[(1,), {}], [(1, 5), {"c": 7}], [(), {"a": 4, "b": 0, "c": 0}]]], + ], + [ + """ +from functools import wraps + +calls = [] + +def trace(func): + @wraps(func) + def wrapper(*args, **kwargs): + calls.append(f"trace {func.__name__}") + return func(*args, **kwargs) + return wrapper + +def double(func): + def double_wrapper(*args, **kwargs): + calls.append("double") + return 2 * func(*args, **kwargs) + return double_wrapper + +@double +@trace +def inc1(x): + return x + 1 + +@trace +@trace +def inc2(x): + return x + 2 + +[inc1(1), inc2(1), calls] +""", + [4, 3, ["double", "trace inc1", "trace inc2", "trace inc2"]], + ], + [ + """ +registry = [] + +def register(func): + registry.append(func) + return func + +@register +@register +def inc(x): + return x + 1 + +[inc(1), registry[0](2), registry[0] is inc, registry[1] is inc] +""", + [2, 3, True, True], + ], + [ + """ +from functools import wraps + +def trace(func): + @wraps(func) + def wrapper(*args, **kwargs): + return func(*args, **kwargs) + return wrapper + +@trace +def inc(x): + '''Add one to x.''' + return x + 1 + +[inc.__name__, inc.__doc__, inc.__wrapped__(1), inc.__wrapped__.__name__, "__wrapped__" in vars(inc)] +""", + ["inc", "Add one to x.", 2, "inc", True], + ], + [ + """ +from functools import wraps + +errors = [] + +def catch_all(func): + @wraps(func) + def wrapper(*args, **kwargs): + try: + return func(*args, **kwargs) + except Exception as exc: + errors.append(str(exc)) + return -1 + return wrapper + +class Counter: + def __init__(self): + self.count = 0 + + @catch_all + def incr(self, step): + if step < 0: + raise ValueError(f"bad step {step}") + self.count += step + return self.count + +counter = Counter() +[counter.incr(2), counter.incr(-1), counter.incr(3), errors, Counter.incr.__name__] +""", + [2, -1, 5, ["bad step -1"], "incr"], + ], + [ + """ +from functools import wraps + +def trace(func): + @wraps(func) + def wrapper(*args, **kwargs): + return func(*args, **kwargs) + return wrapper + +class Counter: + def incr(self): + '''Add one.''' + return 1 + + @trace + def decr(self): + '''Take one away.''' + return -1 + + def reset(self): + return 0 + +counter = Counter() +[ + counter.incr.__doc__, + counter.decr.__doc__, + counter.decr.__name__, + counter.reset.__doc__, + Counter.incr.__doc__, + Counter.decr.__doc__, +] +""", + ["Add one.", "Take one away.", "decr", None, "Add one.", "Take one away."], + ], + [ + """ def f1(value): i = 1 def f2(value):