Skip to content

Make special methods of pyscript classes work when Python calls them - #940

Merged
craigbarratt merged 2 commits into
custom-components:masterfrom
jfriend00:special-methods
Dec 3, 2026
Merged

craigbarratt merged 2 commits into
custom-components:masterfrom
jfriend00:special-methods

Conversation

@jfriend00

@jfriend00 jfriend00 commented Dec 3, 2026 •

Copy link
Copy Markdown
Contributor

Make special methods of pyscript classes work when Python calls them

What happens today

The docs say special methods in a pyscript class (__eq__, __lt__, __hash__, __str__, __len__, __iter__, __call__, ...) won't work, apart from __init__ and __new__, and suggest @pyscript_compile or a native Python class instead. Nothing stops you from writing one, though. It's a pyscript function, so it's async, and Python gets a coroutine when it calls it. Some uses fail with an error; others silently give wrong answers:

class Money:
    def __init__(self, cents):
        self.cents = cents

    def __eq__(self, other):
        return self.cents == other.cents

    def __lt__(self, other):
        return self.cents < other.cents

    def __str__(self):
        return f"{self.cents} cents"

Money(1) == Money(2)                                       # True (Python: False)
Money(1) in [Money(2), Money(3)]                           # True (Python: False)
[m.cents for m in sorted([Money(3), Money(1), Money(2)])]  # [2, 1, 3] (Python: [1, 2, 3])
str(Money(5))  # TypeError: __str__ returned non-string (type coroutine)

The same goes for obj[key], for loops, len(), operators, calling an instance, a with statement in native code such as contextlib.ExitStack (which skips __enter__ and __exit__), and a dataclass's __post_init__ (never called). The workaround, @pyscript_compile, gives up pyscript's features in the method.

Defining a special method is enough to cause trouble, even in code that never calls it, because library code and pyscript itself call special methods to compare, sort, hash and format objects. So the wrong answers can show up far from the class. Two examples from pyscript's own code:

  • Calling an instance of a class that has a pyscript __eq__ never runs the call. pyscript first checks func == time.sleep (to replace blocking sleeps), the __eq__ returns a coroutine, which counts as true, and so the call becomes asyncio.sleep() with the same arguments, after a warning that the code calls blocking time.sleep().
  • An uncaught exception whose class has a pyscript __str__ is logged with <exception str() failed> in place of its message.

Both work with this change.

What I changed

This uses the approach HoneyBearTech's #917 introduced for generator expression elements: run the pyscript coroutine to the end at once, by sending None into it. When a class body defines a special method (with def, or by assigning a pyscript function to a special name), pyscript stores a regular function in its place that does this, so Python can call it like any other method. A special method that has to wait (e.g., for task.sleep()) can't finish at once, so it's stopped and raises:

RuntimeError: Money.__eq__() can't wait (eg, for task.sleep()): it runs as a regular function, so Python can call it

__enter__ and __exit__ are the exception: when pyscript code calls them (a with statement, super().__enter__()), call_func() still awaits the original method, so they can wait, as they can today.

Left as they are: __init__ and __new__ (pyscript already calls them itself), the async special methods (__aenter__, __aexit__, __anext__, __await__ and any async def one, which Python uses with await), __getattribute__, __setattr__ and __delattr__ (Python calls them on every attribute access, and pyscript's @property support depends on whether a class overrides them), and __del__.

Code that doesn't use special methods runs as before: the change adds checks for whether something is a pyscript special method, and branches only when it is. The one exception is deliberate: a with block now also calls __exit__ when GeneratorExit stops it, as Python does (see below), which also affects a generator expression element that tries to wait.

Discussion: which special methods can wait

This is the main design choice. I picked the first of these:

  1. No special method can wait, except __enter__ and __exit__ when pyscript code calls them. Everything else follows Python, where special methods are called synchronously, and today's with statements keep working.
  2. Any special method can wait when pyscript code calls it directly (obj.__str__(), obj()), but not when Python calls it (str(obj)). The same method would then work or fail depending on how it's called.
  3. No special method can wait, with included. Simplest, but it would break existing with blocks whose __enter__ or __exit__ waits (e.g., a service call with blocking=True in __exit__).

Existing code this needed to change

  • call_func()'s debug logging formats every argument, which now runs pyscript __repr__ and __str__ methods. When one of those calls a function with self, the formatting recursed, and the work could grow exponentially. Nested formatting now prints ....
  • call_func() checked func == time.sleep, which runs a pyscript __eq__ whenever an instance of a class that has one is called (the first example above); it uses is.
  • eval(), exec(), locals() and set_global_ctx() compared symbol tables with == or !=, which can call a pyscript __eq__ with interpreter internals; they use is and is not, which is what they mean.
  • A with block now calls __exit__ when GeneratorExit stops it, so a special method stopped for waiting (or a generator expression element, from Support generator expressions, evaluated lazily (#564) #917) releases its locks.
  • The code in genexp_loop() that keeps the script frames of a StopIteration moved into script_traceback(), which special methods use too, so an uncaught StopIteration from __next__ is reported at its own line.

Known gaps

  • Zero-argument super() doesn't work in a method called while its class is still being created (e.g., when __init_subclass__ creates an instance of the new subclass). pyscript fills the class reference after type() returns, while Python fills __classcell__ inside type.__new__. It's documented; giving pyscript's class reference a real cell would fix it.
  • task.executor() or an import inside a special method waits for another thread, so it usually raises (not when that thread happens to finish first). The docs say not to use them there; making the waiting built-ins raise at once inside a special method would make it consistent.

Docs

In Language Limitations, the special-methods bullet now lists the Python constructs that work, and the limitations. The __init__/__new__ bullet no longer says a dataclass __post_init__ isn't called, and its super() and metaclass __call__ notes are updated.

Testing

  • test_special_methods_match_python: 31 sources, each run in pyscript and in CPython and compared, once with INFO and once with DEBUG logging: comparisons, hashing and sorting, operators and conversions, formatting, containers and iteration, with and contextlib.ExitStack, calling instances, descriptors, __init_subclass__ and __class_getitem__, @classmethod special methods, special methods assigned in the class body, __getattr__, a metaclass __call__ singleton, @abstractmethod, a dataclass __post_init__, Enum, and eval() in a method.
  • test_special_method_errors: the can't-wait error, including a finally that waits and a lock held across the wait (it's released), with the interpreter's state intact afterwards; __enter__, __exit__ and an async def special method that wait; and a special method called from another thread.
  • One new STOP_ITERATION_UNCAUGHT_TESTS entry, for a StopIteration raised by __next__.
  • On master, 29 of the 31 sources fail (the other two check behavior master already gets right: an async def special method, and eval() in a method), and so do test_special_method_errors and the new STOP_ITERATION_UNCAUGHT_TESTS entry. Removing each of 18 parts of the change in turn made at least one of the new tests fail every time (twice by hanging the run, which is what those bugs do: unbounded recursion in debug logging, and a lock left held).
  • I also compared about 1,500 more cases between CPython, master and this branch, covering operators, containers, context managers, class machinery, waiting and threads.
  • Code with no special methods runs at the same speed as on master, within run-to-run noise (about 2%): builtin, module, compiled and pyscript function calls, method calls, class creation, and with blocks.
  • tests/test_unit_eval.py passes (36 tests), and the full suite gives the same results as master (on Windows, nine tests fail on both, from Windows paths and event-loop differences). ruff, codespell, pylint and mypy are clean. I ran these on Windows with local stand-ins for Home Assistant's Linux-only imports; CI passes on Linux.

Notes for review

  • Why I worked on this: I'd like to help narrow the gaps between pyscript and regular Python, for my own projects and for others. Special methods are a more advanced feature, and even with this change they have limits, but each gap that closes is one less pyscript-specific rule to learn, whether people write pyscript themselves or with AI assistance.
  • Support generator expressions, evaluated lazily (#564) #917 showed how this could be done; this applies its approach to special methods.
  • I'm not an expert on this codebase, so I'm open to feedback, more testing, or a better approach. I tried to reuse patterns already in the code, and to leave code that doesn't use special methods running exactly as before.
  • From your comments in Answer a sentence or webhook request right away in task.wait_until() #936 and Deprecated constant CONN_CLASS_LOCAL_PUSH #939, 3.0.0 is close. Whether this goes into it, or waits until after it for more review and soak time, is your call, depending on the timing and your assessment of the change.
  • The reference.rst wording was the hardest part to decide. Its readers are Python programmers of all levels, not people who know the interpreter, so I tried to say what they can expect to work and not work without going into implementation details. Feedback on any of the wording, or on what should or shouldn't be there, is welcome.

Work assisted by Claude Code

@jfriend00
jfriend00 marked this pull request as ready for review December 3, 2026 07:15

@craigbarratt craigbarratt left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks @jfriend00, this is thorough work. It addresses part of a long-standing problem: pyscript functions are async, but Python expects methods to be regular functions. It fits well with the other compatibility improvements in 3.0.0, so it will go in that release.

I compared it with master and CPython on more cases (callable instances, task.create(obj), decorated and inherited special methods, waiting __enter__/__exit__ and super().__enter__()), and they all match. The one behavior change I found, obj.__str__() called by name no longer allowing waits, is fine and documented. Approving.

@craigbarratt
craigbarratt merged commit fc3b603 into custom-components:master Dec 3, 2026
6 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants