[issue35048] Can't reassign __class__ despite the assigned class having identical slots

Raymond Hettinger report at bugs.python.org
Sat Dec 7 13:56:57 EST 2019


Raymond Hettinger <raymond.hettinger at gmail.com> added the comment:

The relevant logic is in the compatible_for_assignment() function on line 3972 in Objects/typeobject.c.

After checking that the tp_free slots are the same, it proceeds as follows:

    /*
     It's tricky to tell if two arbitrary types are sufficiently compatible as
     to be interchangeable; e.g., even if they have the same tp_basicsize, they
     might have totally different struct fields. It's much easier to tell if a
     type and its supertype are compatible; e.g., if they have the same
     tp_basicsize, then that means they have identical fields. So to check
     whether two arbitrary types are compatible, we first find the highest
     supertype that each is compatible with, and then if those supertypes are
     compatible then the original types must also be compatible.
    */

So what is happening is that "class a" and "class b" aren't being directly compared to one another.  Instead, they are being compared to their parent "dict".   Since *dict* doesn't have __dict__ or __weakref__, "a" and "b" are deemed to have incompatible layouts.   See lines 3951 to 3954 in same_slots_added() in Objects/typeobject.c.

----------
nosy: +benjamin.peterson, pitrou

_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue35048>
_______________________________________


More information about the Python-bugs-list mailing list