Python variables are bound to types when used?
Fredrik Lundh
fredrik at pythonware.com
Sat Oct 22 13:13:58 EDT 2005
sjdevnull at yahoo.com wrote:
> > reset your brain:
> >
> > http://effbot.org/zone/python-objects.htm
>
> Neat link.
>
> Can you expand on this:
>
> > a type (returned by type(x))
> ...
> > You cannot change the type.
the page was written before the "type/class unification" in Python 2.2,
at a time where the word "type" had a stricter meaning (referring to C-
level types, not user-level classes).
in CPython 2.2 and later, you can in fact change the type under some
circumstances, as long as the internal structure (the "C-level type") is
identical. the types involved must (to quote the checkin messages):
- have the same basic size
- have the same item size
- have the same dict offset
- have the same weaklist offset
- have the same GC flag bit
- have a common base that is the same except for maybe the
dict and weaklist (which may have been added separately at
the same offsets in both types)
- both be heap types
this basically limits the feature to classes defined at the Python level
(just like before the unification); most attempts to use arbitrary types
will fail. e.g.
>>> x.__class__ = dict
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: __class__ assignment: only for heap types
>>> class c(list):
... pass
...
>>> x.__class__ = c
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: __class__ assignment: 'a' object layout differs from 'c'
I suppose it's time to add a footnote to the objects page...
</F>
More information about the Python-list
mailing list