From 7ba425ab6dcadd0f70f5ffa7065e227a82ae14a3 Mon Sep 17 00:00:00 2001 From: jfriend00 Date: Thu, 3 Dec 2026 14:54:14 -0800 Subject: [PATCH] Fix nested @pyscript_executor functions so they run in an executor thread --- custom_components/pyscript/eval.py | 12 +++++++++--- tests/test_unit_eval.py | 27 ++++++++++++++++++++++----- 2 files changed, 31 insertions(+), 8 deletions(-) diff --git a/custom_components/pyscript/eval.py b/custom_components/pyscript/eval.py index 48b1120..281de59 100644 --- a/custom_components/pyscript/eval.py +++ b/custom_components/pyscript/eval.py @@ -1216,6 +1216,8 @@ async def ast_functiondef(self, arg, async_func=False): if len(pyscript_compile.keywords) > 0: raise TypeError(f"@{dec_name}() takes no keyword arguments") arg.decorator_list = other_dec + # in a function, the name is a local variable whose value is kept in a cell + # (EvalLocalVar); exec() below replaces the cell, so keep it to put back local_var = None if arg.name in self.sym_table and isinstance(self.sym_table[arg.name], EvalLocalVar): local_var = self.sym_table[arg.name] @@ -1234,12 +1236,16 @@ async def executor_wrap(*args, **kwargs): return executor_wrap - self.sym_table[arg.name] = executor_wrap_factory(func) + func = executor_wrap_factory(func) else: raise TypeError("@pyscript_executor() needs a regular, not async, function") - if local_var: + + if local_var is not None: + # closures may already hold the cell, so put it back and store func in it self.sym_table[arg.name] = local_var - self.sym_table[arg.name].set(func) + local_var.set(func) + else: + self.sym_table[arg.name] = func return func = EvalFunc(arg, self.code_list, self.code_str, self.global_ctx, async_func) diff --git a/tests/test_unit_eval.py b/tests/test_unit_eval.py index 78915d9..c610c8a 100644 --- a/tests/test_unit_eval.py +++ b/tests/test_unit_eval.py @@ -1217,21 +1217,38 @@ def func_trig(): """ import threading -# will run in the same thread, and return a different thread ident +# will run in the same thread, and return the same thread ident @pyscript_compile() def func1(): return threading.get_ident() # will run in a different thread, and return a different thread ident -@pyscript_compile() +@pyscript_executor() def func2(): return threading.get_ident() -[threading.get_ident() == func1(), threading.get_ident() != func2()] +# defined inside a function or a method, will also run in a different thread +def outer(): + @pyscript_executor + def inner(): + return threading.get_ident() + return inner() + +class Worker: + def run(self): + @pyscript_executor + def inner(): + return threading.get_ident() + return inner() -[True, True] +[ + threading.get_ident() == func1(), + threading.get_ident() != func2(), + threading.get_ident() != outer(), + threading.get_ident() != Worker().run(), +] """, - [True, True], + [True, True, True, True], ], [ """