"as" keyword woes

Carl Banks pavlovevidence at gmail.com
Sun Dec 7 04:35:42 CET 2008


On Dec 6, 8:17 pm, Steven D'Aprano <st... at REMOVE-THIS-
cybersource.com.au> wrote:
> On Sun, 07 Dec 2008 11:27:56 +1000, Nick Coghlan wrote:
> > Warren DeLano wrote:
> >> In other words we have lost the ability to refer to "as" as the
> >> generalized OOP-compliant/syntax-independent method name for casting:
>
> > Other possible spellings:
>
> > # Use the normal Python idiom for avoiding keyword clashes # and append
> > a trailing underscore
> > new_object = old_object.as_(class_hint) float_obj = int_obj.as_("float")
> > float_obj = int_obj.as_(float_class)
>
> > # Use a different word (such as, oh, "cast" perhaps?) new_object =
> > old_object.cast(class_hint) float_obj = int_obj.cast("float")
> > float_obj = int_obj.cast(float_class)
>
> I don't like "cast", because a cast is an instruction to the compiler to
> treat data as some type other than what it was defined as.
It doesn't
> create a new piece of data. (At least in C-like languages.)

Actually, C-like languages do exactly that.  (float)i doesn't take the
bits of int i and treat them as if they were a float, it creates new
data in the appropriate data type that matches the value of i
semantically, which would have a very different bit pattern.

Pointer-to-int and pointer-to-pointer typecasts are really the only
ones that tend to preserve the bits of the data (which, since they are
the most common kinds of typecast, has misled some people to think
that typecasts in C are all about preserving bits).  However, in
general typecasts preserve the semantic value of the original data.

That's exactly what these methods would be doing, changing the type
while preserving the semantic value as much as possble, so cast is a
perfectly appropriate name for it.

(BTW, in C++, even pointer-to-pointer static casts don't always
preserve the bits.)


Carl Banks



More information about the Python-list mailing list