tp_base, tp_basesize, and __slots__ instance __class__ reassignment

J

Jp Calderone

In trying to update some code built on top of reload(), I've hit a point
of confusion in how it is determined whether or not __class__ is allowed to
be rebound.

Consider, for example:
... __slots__ = 'a', 'b'
... ... __slots__ = 'a', 'b'
... Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: __class__ assignment: 'Bar' object layout differs from 'Foo'

The cause of this particular error does not actually seem to be that the
object layouts of Bar and Foo are incompatible, but rather that the object
layouts of _object_ and Foo are incompatible.

I've tracked down the point of rejection to same_slots_added
(Objects/typeobject.c:2347 or thereabouts):

static int
same_slots_added(PyTypeObject *a, PyTypeObject *b)
{
PyTypeObject *base = a->tp_base;
int size;

if (base != b->tp_base)
return 0;
if (equiv_structs(a, base) && equiv_structs(b, base))
return 1;
size = base->tp_basicsize;
if (a->tp_dictoffset == size && b->tp_dictoffset == size)
size += sizeof(PyObject *);
if (a->tp_weaklistoffset == size && b->tp_weaklistoffset == size)
size += sizeof(PyObject *);
return size == a->tp_basicsize && size == b->tp_basicsize;
}

I do not understand why the final line is comparing size against each of a
and b's tp_basicsize, rather than perfoming some comparison between a and b
directly.

Can anyone enlighten me?

Jp
 
?

=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=

Jp said:
Can anyone enlighten me?

The test doesn't recognize the addition of arbitrary same slots.
Instead, it only looks for the __dict__ slot and the weakrefs slot.
If any additional slots have been added to either subclass, the
classes are considered different.

To test whether just these two slots have been added in lock-step,
you check
1. the dictoffset is the same for both classes, and it follows
immediately the base slots, or neither class has a dictoffset.
2. the weakrefs offset is the same for both classes, and it follows
immediately the dictoffset (or the base slots if there was no
dictoffset).
3. there are no additional slots

Now, this *could* be generalized to treating to classes the same if
they have the same user-defined slots. If you want to do that, looking
at the size is not sufficient - you also have to verify that the slot
names and offsets are the same, lock-step-wise.

HTH,
Martin
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,537
Members
45,024
Latest member
ARDU_PROgrammER

Latest Threads

Top