Fun with numbers - dammit, but I want a cast!

Alex Martelli aleax at aleax.it
Mon Aug 11 16:38:24 CEST 2003


Graham Nicholls wrote:
   ...
>> xscale = xframe / float(img_x)
> 
> Thats what I wanted to do, but was sure I'd read that python didn't have
> casts, and that _looks_ like a cast to me!

Well, Python surely has the ability to create new objects, and the most
typical way to do that is to call a type, possibly passing it, as the
call's arguments, the value[s] that direct the new object's creation.


So, for example, if you have a string S and want to create a list L
whose items are the string's characters, you typically code:

L = list(S)


Similarly, if you have a number N and want to create a float F whose
value is the floating-point equivalent of N's value, you code:

F = float(N)


Whether these are "casts" is, I guess, a pretty moot issue.  Me, I'd
call them "type calls" (or "explicit constructor calls" if I were in a C++
mood:-), reserving the terminology "cast" for the C/Java notation:

    (sometype)somevalue

or the C++ notations of forms such as:

    static_cast<sometype>(somevalue)

But, of course (in C++), explicitly calling a costructor of (e.g.) float,
with an integer argument; or statically casting an int to float; or even
using the old C-ish "prepended type in parenthesis" notation; have much
the same effect in most contexts.  As long as you're quite clear that
what you're actually doing is "create a new value of a specified type
by calling the type with suitable argument[s]", rather than (the typical
idea of "cast") "reinterpreting an existing value AS IF it was of some 
other type rather than of the type it actually is", it may not be a
problem if you like to call the operation "a cast".


Alex





More information about the Python-list mailing list