Skip to content
Merged
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
177 changes: 157 additions & 20 deletions custom_components/pyscript/eval.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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()
Expand All @@ -126,7 +127,7 @@ 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]:
continue
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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."""

Expand Down Expand Up @@ -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
Expand All @@ -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]] = []

Expand Down Expand Up @@ -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:
Expand All @@ -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()

Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -1509,14 +1621,28 @@ 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):
self.global_sym_table[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)
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -2273,18 +2393,35 @@ async def call_func(self, func, func_name, /, *args, **kwargs):
except Exception:
func_name = "<function>"
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):
Expand Down Expand Up @@ -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
)
Expand Down Expand Up @@ -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:
Expand Down
45 changes: 34 additions & 11 deletions docs/reference.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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``,
Expand All @@ -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.
Expand Down
Loading
Loading