Nice way to cast a homogeneous tuple

John Nagle nagle at animats.com
Thu Jul 29 01:45:19 EDT 2010


On 7/28/2010 7:32 AM, Steven D'Aprano wrote:
> On Wed, 28 Jul 2010 09:35:52 -0400, wheres pythonmonks wrote:
>
>> Thanks ... I thought int was a type-cast (like in C++) so I assumed I
>> couldn't reference it.
>
> Python doesn't have type-casts in the sense of "tell the compiler to
> treat object of type A as type B instead". The closest Python has to that
> is that if you have an instance of class A, you can do this:
>
> a = A()  # make an instance of class A
> a.__class__ = B  # tell it that it's now class B
>
> and hope that it won't explode when you try to use it :/
>
> I make that seem like a dangerous thing to do, but it's not really. There
> actually are sensible use-cases for such a thing, you can't do it to
> built-ins (which would be dangerous!), and the worst that will happen
> with classes written in Python is they'll raise an exception when you try
> calling a method, rather than dump core.

    The main use for that sort of thing is in constructing objects
without their cooperation.  "copy" and "pickle" do that,
as they build up objects without running their initializers.

    Arguably, that would be better done with a built-in function for
creating arbitrary objects.  Something like:
	
	x = new_object("classname",
		(("attr1", val1), ("attr2", val2)))

to create a new object in one atomic operation.
Storing into "__class__" may not be portable across
Python implementations.  The implications for multiple
inheritance are difficult. It's really a hack for CPython.

				John Nagle



More information about the Python-list mailing list