Repository navigation
Description
You cannot set A.__new__ back to object.__new__ once it is set to something else.
class A:
def __init__(self, arg):
pass
A.__new__ = object.__new__
A(123) # it passes
A.__new__ = 123 # you can pass anything here
A.__new__ = object.__new__
A(123) # it cannot pass
# TypeError: object.__new__() takes exactly one argument (the type to instantiate)The cause of this is analyzed here: #105888 (comment)
Edited for clarity.
Original Post
Summary
If the __new__ method of a class was replaced by a dummy method and later replaced by it original __new__, the method has a divergent behavior as before. Before and and after the swap, both methods point to the same physical address, so according to my debugging capabilities from within Python code, both methods are identical, but show a different behavior.
As I understood the answer to my StackOverflow question, CPython implements a "forgiving" feature, if only one of the __new__ or __init__ methods was modified by a user e.g. expecting additional arguments. So the other method ignores them, because __call__ of the meta-class passes args and kwargs to __new__ as well as __init__.
So far so good, but why does __new__ behave differently in my case if the methods are still identical according the function pointer locations? I my opinion, some internal checks in CPython are not correct and the exception is raised inadvertently.
Background
I'm implementing several features like abstract methods, abstract classes, must-override methods, singletone behavior, slotted classes (automatic inference of slots) and mixin classes (deferred slots) using a user-defined meta-class called ExtendedType. The following code can be found as a whole at pyTooling/pyTooling on the development branch.
Depending on the internal algorithms of ExtendedType, it might decide a class A is abstract. If so, the __new__ method is replaced by a dummy method raising an exception (AbstractClassError). Later, when a class B(A) inherits from A, the meta-class might come to the decision, B isn't abstract anymore, thus we want to allow the object creation again and allow calling for the original __new__ method. Therefore, the original method is preserved as a field in the class (__orig_new__).
Replacing __new__ was choosen, because it has no performance impact compared to overriding __call__ in the meta-class, as this is called on every object creation, also on non-abstract classes.
(Performance loss is 1:2.47 on CPython 3.10.11 and 1:2.86 on CPython 3.11.3 measured by pytest-benchmark)
To simplify the internal algorithms for the abstractness decision, the meta-class implements a boolean named-parameter abstract.
Bug Report
class AbstractClassError(Exception):
pass
class M(type):
# staticmethod
def __new__(cls, className, baseClasses, members, abstract):
newClass = type.__new__(cls, className, baseClasses, members)
if abstract:
def newnew(cls, *_, **__):
raise AbstractClassError(f"Class is abstract")
# keep original __new__ and exchange it with a dummy method throwing an error
newClass.__new_orig__ = newClass.__new__
newClass.__new__ = newnew
else:
# 1. replacing __new__ with original (preserved) method doesn't work
newClass.__new__ = newClass.__new_orig__
return newClass
class A(metaclass=M, abstract=True):
pass
class B(A, abstract=False):
def __init__(self, arg):
self.arg = arg
b = B(5)This causes an error message:
TypeError: object.__new__() takes exactly one argument (the type to instantiate)
Investigate if swapping methods worked correctly:
print("object.__new__ ", object.__new__)
print("A.__new_orig__ ", A.__new_orig__)
print("A.__new__ ", A.__new__)
print("B.__new__ ", B.__new__)Results:
object.__new__ <built-in method __new__ of type object at 0x00007FFE30EDD0C0>
A.__new_orig__ <built-in method __new__ of type object at 0x00007FFE30EDD0C0>
A.__new__ <function M.__new__.<locals>.newnew at 0x000001CF11AE5A80>
B.__new__ <built-in method __new__ of type object at 0x00007FFE30EDD0C0>
So, the preserved method in __new_orig__ is identical to object.__new__ and is again the same after swapping back the __new__ method in class B.
Behavior of Ordinary Classes
Here is a comparison with two ordinary classes X and Y(X):
class X:
pass
class Y(X):
def __init__(self, arg):
self.arg = arg
y = Y(3)Of cause this will work, but are the new methods different?
object.__new__ <built-in method __new__ of type object at 0x00007FFE3B61D0C0>
A.__new_orig__ <built-in method __new__ of type object at 0x00007FFE3B61D0C0>
A.__new__ <function M.__new__.<locals>.newnew at 0x000001CD1FB459E0>
B.__new__ <built-in method __new__ of type object at 0x00007FFE3B61D0C0>
X.__new__ <built-in method __new__ of type object at 0x00007FFE3B61D0C0>
Y.__new__ <built-in method __new__ of type object at 0x00007FFE3B61D0C0>
Also X and Y use the same __new__ method as B or object.
Comparing results:
print("Y.__new__ ", Y.__new__)
y = Y(3)
print("y.arg ", y.arg)
print("B.__new__ ", B.__new__)
b = B(5)
print("b.arg ", y.arg)
Results:Outputs:
Y.__new__ <built-in method __new__ of type object at 0x00007FFE3B61D0C0>
y.arg 3
B.__new__ <built-in method __new__ of type object at 0x00007FFE3B61D0C0>
Traceback (most recent call last):
File "C:\Temp\newIstKomisch.py", line 67, in <module>
b = B(5)
^^^^
TypeError: object.__new__() takes exactly one argument (the type to instantiate)
Further Reading:
Your environment
- CPython versions tested on: 3.11.3
- Operating system and architecture: Windows 11 64-bit, x86-64
/cc @skoehler
Activity
Paebbels commentedon Jun 17, 2023
Implementing that
__call__method in the meta-class fixes the bug in CPython with a huge performance impact.But it shows according to the view from with the Python code, both
__new__methods are identical.sunmy2019 commentedon Jun 19, 2023
Update: Ignore this post since it is partially incorrect.
The behavior of
object.__new__is depending on C level argumenttype->tp_new.Once it is set during class creation, there is no easy way from Python side to change its value. The subsequent stores of
__new__will only affectB.__dict__, nottp_new.cpython/Objects/typeobject.c
Lines 5412 to 5446 in 4426279
I agree it is a bug.
I don't think it would be an easy change since this behavior has been long-standing for at least 10 years.
And I don't think it is worth a change since it seems like a corner case.
But I also don't object to a change if there is enough reason for it, and the performance is not dropping (too much)
sunmy2019 commentedon Jun 19, 2023
To circumvent it, avoid setting
__new__or__init__after class creation.Paebbels commentedon Jun 19, 2023
I'll try and check what I can do. Maybe I can handover the modified or swapped methods to
type.__new__(...).I'll also investigate another workaround by adding a wrapper for
__new__if the method is swapped back, which removes unwanted parameters from a call to the originalobject.__new__. Maybe the performance impact is not so drastic.Paebbels commentedon Jun 19, 2023
For your example:
Where can I find the C code for the assignment, which adds an entry to
cls.__dict__and replacestp_newwith a redirection?When
__new__is a (function) slot, why is it converted to a__dict__entry? If a user defines__slots__then accesses are not converted to__dict__entries, right? Or is there a difference for attribute slots vs. function slots?Another problem:
How should this behavior be portable to e.g. PyPy? CPython is a reference implementation but also a language specification. So PyPy would need to implement the same bug.
An assignment like the one above shouldn't break the code.
It's not a question of corner cases and niches, but about mathematical correctness of a programming language, right?!
I also would like to understand (still need to search it) how
@abstractin ABCMeta works. It might have a similar problem if it works like my approach.Paebbels commentedon Jun 19, 2023
Just a curious side question:
I wrote my meta-class
ExtendedTypeadding several features to Python (3.7..11), some are enhancing the speed in Python 3.10 by 25% or still 5-10% in Python 3.11.Core features:
__slots__.(To my knowledge: ABCMeta is incompatible with user defined meta-classes in multiple inheritance scenarios. Moreover features provided by multiple meta-classes like abstract and singleton, can't be composed if not provided by a single meta-class)
I have unit tests (pytest) to check the behavior and performance of my code.
I would be open in donating that to CPython so
typecould be enhanced with low performance impact. Especially if implemented by CPython in C instead of Python code.I'm not sure whom to contact by issues or email and speak to.
Paebbels commentedon Jun 19, 2023
@sunmy2019 I fixed your example 😃:
The original exampled posted in the morning missed an
__init__method inA.Assigning something different then
object.__new__:Error message:
It can be fixed like that:
So the assignment operator has a hidden magic feature if the assign method to
tp_newisobject.__new__then it accepts the new method, otherwise it does wired stuff.sunmy2019 commentedon Jun 20, 2023
My example is wrong so I deleted it.
sunmy2019 commentedon Jun 20, 2023
Update: Ignore this post since it is partially incorrect.
I want to clarify this.
slot
tp_newis assigned during class creation. So if the class is created with a customized__new__, then it can never useobject.__new__again. (otherwise, you will meet the bug above)You can find the assignment here.
cpython/Objects/typeobject.c
Lines 6245 to 6284 in 3bb0994
It adds an entry? Yes.
replaces
tp_newwith a redirection? No. No need for that.__dict__has higher precedence overtp_new.You can also verify that
'__new__' is not in B.__dict__during creation, andtp_newis the same withA's.After you do
B.__new__ = ..., you can verify'__new__' is in B.__dict__Paebbels commentedon Jun 20, 2023
I got your point about
newClass.__new__ = ...creating the dictionary item the first time. Now attribute lookup order kicks in. But why doesnot fail?
It's an assignment and
__new__is not yet in the__dict__. Following your reasoning, it was then not added to__dict__otherwise it would fail. Then would in turn mean, the assignment was not executed, right?Also following you explanations,
tp_newis not changed, but an entry is added to__dict__. Iftp_newwasn't touched, why does this check fail? According to your reasoning, an earlier item in the lookup order was added, sotp_newisn't reached anymore. That can't be true.skoehler commentedon Jun 20, 2023
I don't follow. Let's consider the following code again:
If what you say was true, then the assignment of 5 wouldn't matter. The class has already been created at that point by
type.__new__(). So how does the assignment of5change the outcome?\Also, when commenting out the assignment of
5, how come the assignment ofoldnewdoesn't trigger the same effect?Alternatively, if the creation of the class happens later, i.e., after the completion of
M.__new__(), how does the assignment of5affect the outcome since it is later overwritten byoldnew?We established that example fails if and only if the assignment of
5is not commented out. Nothing you said so far seems explain that. May I ask you to clarify further?The evidence we presented strongly suggest that assignments to
__new__have some side-effect that happens at the time of assignment!sunmy2019 commentedon Jun 21, 2023
It is touched on here.
cpython/Objects/typeobject.c
Lines 4420 to 4435 in 3bb0994
sunmy2019 commentedon Jun 21, 2023
@Paebbels @skoehler You both are correct. I am missing something. I dig a bit deeper.
For this code:
The following things happened.
type.__new__create a class, and set its C slottp_newtoobject_new.cpython/Objects/typeobject.c
Lines 6245 to 6284 in 3bb0994
newClass.__new__ = oldnewdoes affect the C slot. (I was wrong about it)You can see it here. The
update_slotis supposed to updatetp_newto the correct value (aslot_tp_newto indicate looking through the class's__dict__)cpython/Objects/typeobject.c
Lines 4927 to 4938 in 4d140e5
But it does not. It special cases
object.__new__here. In this case, itstp_newis left unchanged.cpython/Objects/typeobject.c
Lines 9814 to 9835 in 4d140e5
tp_new. For a class withtp_new = object_new, it calls the C functionobject_new. For a class withtp_new = slot_tp_new, it goes through class's__dict__.So in this example.
sunmy2019 commentedon Jun 21, 2023
Super weird bug. Looks like we should fix the
update_slotlogic.Paebbels commentedon Jun 21, 2023
I couldn't follow all the steps yet. I might need to read the C code a few more times to puzzle all parts together. But we know for sure, something is odd in that behavior.
Btw. what's the sentence about the beer? Am I and @skoehler qualified for it?
sunmy2019 commentedon Jun 22, 2023
Unfortunately, the 23-yr old slot updating code was introduced in Python 2.3 721f62e. There are codes relying on this behavior. So at least this part is not changeable.
The argument check code is added 12 yrs ago. 96384b9
@Paebbels Will you allow me to edit your post? I want to state the reason and the problem more clearly.
You should ask @gvanrossum. But I guess it was correct when that line was written. Somewhere else broke the things.
Paebbels commentedon Jun 22, 2023
@sunmy2019, yes you can modify the post.
[-]Abnormal behavior of __new__ if method was replaced and swapped back to original __new__[/-][+]Cannot set `A.__new__` back to `object.__new__` once it is set to something else.[/+]sunmy2019 commentedon Jun 23, 2023
I personally think it is the current design does not allow setting
A.__new__inobject.__new__in any case.I prefer to make it clear in the doc: do not assign
A.__new__ = object.__new__.Paebbels commentedon Jun 23, 2023
Ok, now we have understood it.
But is it the intension of Python not allowing it to be set?
What group of developers is deciding on such a question?
I don't think so.
sunmy2019 commentedon Jun 23, 2023
I think core developers can decide if there are no controversies. Otherwise we require a PEP.
It's just my guess. It may never be never supported. https://godbolt.org/z/eE81aGPMo
Fix instantiating a class that fulfills an expectation its base-class…