You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
[mypyc] Use defined __new__ method in tp_new and constructor (#19739)
Fixes#16012
mypyc ignored custom implementations of `__new__` because, even though a
C function representing the method was generated, it was called neither
in the type constructor nor in the method assigned to the `tp_new`
pointer.
Now if there's a `__new__` method defined for a type, the corresponding
function is called in place of the setup function which is responsible
for allocating memory for new objects and initializing their attributes
to default values.
The setup function is still called when creating instances of the type
as calls resolving to `object.__new__()` are transformed to call the
setup function. This way, `__new__` can return instances of other types
and instances of the type of the class where `__new__` is defined are
setup correctly.
There are a couple of limitations:
- Programs with `super().__new__()` calls in `__new__` methods of
non-native classes are rejected because it's more difficult to resolve
the setup function for non-native classes but this could probably be
supported in the future.
- Similarly, programs are rejected when a class inherits from a
non-compiled class. In this case calling the `tp_new` method of the
parent type results in an error because cpython expects the sub type to
use a wrapper for `tp_new` which compiled classes don't. Allowing this
would require compiled types to be initialized more closely to the way
cpython does it which might need a lot of work.
- Lastly, when `__new__` is annotated with `@classmethod`, calling it
without the type parameter works in compiled code but raises an error in
interpreted. I'm not sure of the reason and it's difficult to make it a
compiler error because it's outside of what mypyc sees.
---------
Co-authored-by: Brian Schubert <[email protected]>
Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
0 commit comments