[Python-Dev] Assignment to __class__

Guido van Rossum guido@python.org
Thu, 09 Jan 2003 10:31:29 -0500


> I'm testing large chunks of our code base with Python 2.3a1 and have run
> into another minor snag.  Five months ago Guido committed a patch to prevent
> assigning __class__ for non-heap-types, which was backported to 2.2-maint
> two weeks ago in response to SF #658106.  This is a great idea for
> preventing nonsensical assignments to None.__class__, or 2.__class__, but it
> is too heavy handed in preventing assignments to [1,2,3].__class__,
> (1,2,3).__class__ or {1:2,3:4}.__class__.
> 
> My specific use-case involves dictionary and list objects.  I define a
> classes that inherits from list or dict and add specialized algebraic,
> vector and tensor functions over the range and domain of the data in the
> list or dictionary.  I _could_ just copy the data into my new objects, but it
> is wasteful since these structures can be very large and deeply nested.
> 
> I suspect that it is possible to come up with better criteria for allowing
> safe assignment to __class__ that will still allow the useful technique I
> describe above.

You can only set __class__ when the old and new class instance have
the same instance layout at the C level.  Changing this is impossible
given the way objects are implemented in C.  This means you can never
change a list into a dict or vice versa, because the C structs are
different.

Or do I misunderstand you?  Can you give an example of something you
think should be allowed but currently isn't?

--Guido van Rossum (home page: http://www.python.org/~guido/)