Repository navigation
Make special methods of pyscript classes work when Python calls them - #940
Merged
Merged
Conversation
jfriend00
marked this pull request as ready for review
December 3, 2026 07:15
craigbarratt
approved these changes
Dec 3, 2026
craigbarratt
left a comment
Member
There was a problem hiding this comment.
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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_compileor 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:The same goes for
obj[key],forloops,len(), operators, calling an instance, awithstatement in native code such ascontextlib.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:
__eq__never runs the call. pyscript first checksfunc == time.sleep(to replace blocking sleeps), the__eq__returns a coroutine, which counts as true, and so the call becomesasyncio.sleep()with the same arguments, after a warning that the code calls blockingtime.sleep().__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
Noneinto it. When a class body defines a special method (withdef, 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., fortask.sleep()) can't finish at once, so it's stopped and raises:__enter__and__exit__are the exception: when pyscript code calls them (awithstatement,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 anyasync defone, which Python uses withawait),__getattribute__,__setattr__and__delattr__(Python calls them on every attribute access, and pyscript's@propertysupport 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
withblock now also calls__exit__whenGeneratorExitstops 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:
__enter__and__exit__when pyscript code calls them. Everything else follows Python, where special methods are called synchronously, and today'swithstatements keep working.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.withincluded. Simplest, but it would break existingwithblocks whose__enter__or__exit__waits (e.g., a service call withblocking=Truein__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 withself, the formatting recursed, and the work could grow exponentially. Nested formatting now prints....call_func()checkedfunc == time.sleep, which runs a pyscript__eq__whenever an instance of a class that has one is called (the first example above); it usesis.eval(),exec(),locals()andset_global_ctx()compared symbol tables with==or!=, which can call a pyscript__eq__with interpreter internals; they useisandis not, which is what they mean.withblock now calls__exit__whenGeneratorExitstops it, so a special method stopped for waiting (or a generator expression element, from Support generator expressions, evaluated lazily (#564) #917) releases its locks.genexp_loop()that keeps the script frames of aStopIterationmoved intoscript_traceback(), which special methods use too, so an uncaughtStopIterationfrom__next__is reported at its own line.Known gaps
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 aftertype()returns, while Python fills__classcell__insidetype.__new__. It's documented; giving pyscript's class reference a real cell would fix it.task.executor()or animportinside 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 itssuper()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,withandcontextlib.ExitStack, calling instances, descriptors,__init_subclass__and__class_getitem__,@classmethodspecial methods, special methods assigned in the class body,__getattr__, a metaclass__call__singleton,@abstractmethod, a dataclass__post_init__,Enum, andeval()in a method.test_special_method_errors: the can't-wait error, including afinallythat waits and a lock held across the wait (it's released), with the interpreter's state intact afterwards;__enter__,__exit__and anasync defspecial method that wait; and a special method called from another thread.STOP_ITERATION_UNCAUGHT_TESTSentry, for aStopIterationraised by__next__.async defspecial method, andeval()in a method), and so dotest_special_method_errorsand the newSTOP_ITERATION_UNCAUGHT_TESTSentry. 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).withblocks.tests/test_unit_eval.pypasses (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
reference.rstwording 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