Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
54 changes: 43 additions & 11 deletions custom_components/pyscript/eval.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import ast
import asyncio
import builtins
from collections.abc import Iterator, MutableMapping
import functools
import importlib
import inspect
Expand Down Expand Up @@ -284,6 +285,38 @@ def strip_qualname_prefix(code, prefix):
return code.replace(co_qualname=code.co_qualname.removeprefix(prefix), co_consts=consts)


class _LocalSymTable(MutableMapping[str, Any]):
"""Read-through view of a local sym_table that unwraps EvalLocalVar entries for exec()."""

def __init__(self, sym_table: SymTable) -> None:
"""Initialize with the enclosing function's local symbol table."""
self.sym_table = sym_table
self.assigned: SymTable = {}

def __getitem__(self, key: str) -> Any:
"""Return assigned value or unwrapped EvalLocalVar value."""
if key in self.assigned:
return self.assigned[key]
val = self.sym_table[key]
return val.get() if isinstance(val, EvalLocalVar) else val

def __setitem__(self, key: str, value: Any) -> None:
"""Record an assignment made by exec() without mutating sym_table."""
self.assigned[key] = value

def __delitem__(self, key: str) -> None:
"""Delete an assigned entry."""
del self.assigned[key]

def __iter__(self) -> Iterator[str]:
"""Iterate over all keys visible in the local symbol table."""
return iter(self.sym_table.keys() | self.assigned.keys())

def __len__(self) -> int:
"""Return total number of keys visible in the local symbol table."""
return len(self.sym_table.keys() | self.assigned.keys())


class EvalLocalVar:
"""Wrapper for local variable symtable entry."""

Expand Down Expand Up @@ -1216,15 +1249,15 @@ 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]
code = compile(ast.Module(body=[arg], type_ignores=[]), filename=self.filename, mode="exec")
exec(code, self.global_sym_table, self.sym_table) # pylint: disable=exec-used
# in a function, locals are kept in EvalLocalVar cells; unwrap them for exec()
# so defaults/decorators see values rather than cells, and don't overwrite the cell
exec_locals: MutableMapping[str, Any] = (
_LocalSymTable(self.sym_table) if self.in_local_scope() else self.sym_table
)
exec(code, self.global_sym_table, exec_locals) # pylint: disable=exec-used

func = self.sym_table[arg.name]
func = exec_locals[arg.name]
if dec_name == "pyscript_executor":
if not inspect.iscoroutinefunction(func):

Expand All @@ -1240,10 +1273,9 @@ async def executor_wrap(*args, **kwargs):
else:
raise TypeError("@pyscript_executor() needs a regular, not async, function")

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
local_var.set(func)
if arg.name in self.sym_table and isinstance(self.sym_table[arg.name], EvalLocalVar):
# closures may already hold the cell, so store func in it
self.sym_table[arg.name].set(func)
else:
self.sym_table[arg.name] = func
return
Expand Down
46 changes: 46 additions & 0 deletions tests/test_unit_eval.py
Original file line number Diff line number Diff line change
Expand Up @@ -1252,6 +1252,40 @@ def inner():
],
[
"""
def outer():
i = 3
k = 4

scale = lambda n: lambda f: lambda x=None: (f() if x is None else f(x)) * n

@pyscript_compile
def inner_pos(x=i):
return x * 10

@pyscript_compile
def inner_kw(*, x=i):
return x * 10

@pyscript_compile
@scale(k)
def inner_dec(x=i):
return x * 10

@pyscript_executor
def inner_exec(x=i):
return x * 10

def call_inner():
return inner_pos()

return [inner_pos(), inner_kw(), inner_dec(), inner_exec(), call_inner()]

outer()
""",
[30, 30, 120, 30, 30],
],
[
"""
def twice(func):
def twice_func(*args, **kwargs):
func(*args, **kwargs)
Expand Down Expand Up @@ -2432,6 +2466,18 @@ def func2():
],
[
"""
i = 99
def outer():
@pyscript_compile
def inner(x=i):
return x
i = 3
outer()
""",
ED(NameError, "name 'i' is not defined", lineno=5, col_offset=4, end_col_offset=16),
],
[
"""
@pyscript_compile(1)
def func():
pass
Expand Down