Nice way to cast a homogeneous tuple

Carl Banks pavlovevidence at gmail.com
Sat Aug 7 16:02:56 EDT 2010


On Aug 7, 6:54 am, Albert van der Horst <alb... at spenarnc.xs4all.nl>
wrote:
> In article <1pm7i7-473.... at satorlaser.homedns.org>,
> Ulrich Eckhardt  <eckha... at satorlaser.com> wrote:
>
>
>
> >Steven D'Aprano wrote:
> >> Perhaps I have been misinformed, but my understanding of C type-casts is
> >> that (where possible), a cast like `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.
>
> >You are misinformed. The result of a cast in C or C++ behaves as if a
> >temporary was created:
>
> >  int x = 0;
> >  unsigned(x)--; // invalid, compiler error
>
> >Now, where this distinction gets blurred is when you are casting pointers:
>
> >  (*(unsigned*)&x)--;
>
> >or, in C++, references:
>
> >  reinterpret_cast<unsigned&>(x)--;
>
> >Technically, these are still invalid though, only that they give you
> >undefined behaviour at runtime instead of a compiler error, but those are
> >already very fine details of the according standards.
>
> There is just one conclusion that should remain from this.
> If you're ever going to program in in c or c++, casts are to be
> avoided like the plague.

You sound as if you don't usually program in C or C++, which suggests
to me that you shouldn't be offering advice on how to program in these
languages.  I program in C all the time, and I can tell you you can't
get very far in C or C++ without sometimes resorting to type-casts.  (C
++ offers more help for class types, but there's not a lot you can do
to avoid casts for converting between built-in types.)

The CPython interpreter uses type casts all over the place, BTW.

> (And recently they have been thought over in
> C++ to be split in different names with the reinterpret_cast the most
> dangerous, but at least it is a big read flag.)

If by "recently" you mean "10 years ago", and by "thought over" you
mean "standardized and implemented".

> I see an analogy with goto's in my experience. Once you understand
> how bad they are, you discover there is always a better solution.

What better solution do you propose for this that doesn't use type-
casting?

int a, b;
double ratio;

ratio = (double)a/b;


> It is unfortunate that cast's in Python share the same name, but
> it is kind of unavoidable because it is about the proper CS name to use.

Not really.  Very few people call int(), float(), and company "type
casts".  They aren't type casts at all, they are constructors that
sometimes have the same semantics as type casts in C.


Carl Banks



More information about the Python-list mailing list