Dynamically changing an object's class - still to be allowed?

Tim Peters tim.one at comcast.net
Thu Apr 25 18:50:40 EDT 2002


[Hamish Lawson]
> I came across a debate that ran on the list while Python 2.2 was being
> developed that suggested (if I understood correctly) that Guido was
> planning to limit the ability to dynamically change an object's class by
> assigning to its __class__ attribute. It was indicated that these
> limitations might be implemented for Python 2.2, but they don't appear
> to have been; might they yet?

Well, not in 2.2 <wink>.  Some 2.2 prereleases disallowed changing __class__
at all, but Guido backed down from this after enough people showed arguably
valid use cases, and 2.2 tries to allow it *when it can*.  That's the plan
for 2.3 & onward too.

Use of some features of new-style classes can make it impossible, though.
All instances of old-style classes had exactly the same memory layout, but
instances of new-style class *may* have radically different memory layouts.
As an obvious example, "int" is a new-style class, and you're never going to
be able to change the __class__ of your own new-style class's instances to
"int":

>>> class C(object):
...    pass
...
>>> c = C()
>>> c.__class__ = int
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
TypeError: __class__ assignment: 'int' object layout differs from 'C'
>>>

Not that it's not complaining because 'int' is a builtin class, it's
complaining because the instance memory layouts don't jibe.

I wouldn't blame you if you thought this was a bug in 2.3 CVS <wink>:

>>> (3).__class__ = bool
>>> 3
True
>>>






More information about the Python-list mailing list