tp_base, tp_basesize, and __slots__ instance __class__ reassignment
Jp Calderone
exarkun at intarweb.us
Sat Jul 5 13:21:40 EDT 2003
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:
>>> class Foo(object):
... __slots__ = 'a', 'b'
...
>>> class Bar(object):
... __slots__ = 'a', 'b'
...
>>> f = Foo()
>>> f.__class__ = Bar
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
--
Where a calculator on the ENIAC is equipped with 18,000 vacuum tubes and
weighs 30 tons, computers in the future may have only 1,000 vacuum tubes and
weigh only 1.5 tons. -- Popular Mechanics, March 1949
More information about the Python-list
mailing list