Nice way to cast a homogeneous tuple

Carl Banks pavlovevidence at gmail.com
Thu Jul 29 11:29:01 EDT 2010


On Jul 28, 7:45 pm, Steven D'Aprano <steve-REMOVE-
T... at cybersource.com.au> wrote:
> On Wed, 28 Jul 2010 08:47:52 -0700, Carl Banks wrote:
> > On Jul 28, 7:32 am, Steven D'Aprano <st... at REMOVE-THIS-
> > cybersource.com.au> 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 :/
>
> > Type casts in C and non-pathlogical C++ don't modify the object they are
> > casting.
>
> > int (and str, float, etc.) is the closest thing to a type cast in
> > Python.
>
> Perhaps I have been misinformed, but my understanding of C type-casts is
> that (where possible), a cast like `int(var)`

(int)var


> merely tells the compiler
> to temporarily disregard the type of var and treat it as if it were an
> int. In other words, it's a compiler instruction rather than a conversion
> function.

Even if it did, it would still be temporary.  The type of the variable
remains unchanged.

But it doesn't disregard the original type: type casts try to preserve
semantic value.  (double)1 returns 1.0, which is not only a different
bit pattern but a different size.  That's exactly what float() does in
Python.


Carl Banks



More information about the Python-list mailing list