determine variable type

Magnus Lycka lycka at carmen.se
Fri Aug 19 11:28:19 EDT 2005


MCollins at seminolecountyfl.gov wrote:
> trying to determine a variable type, specifically that a variable is an 
> integer.
> 
> i tried using type(var) but that only seemed to produce a response in the 
> command line.

You mean that if you do "type(var)" at the Python prompt, it gives
you a reply, but if you have a line with just that in a script, it
doesn't?

That has nothing to do with type checks. All Python expressions in
Python work like that. In interactive use, unused results are echoed
to the screen, but in scripts, they are not. How would you expect
the echoed value to be useful in your program?

In a script, you need to take care of the output of an expression
to get any use from it. A standalone expression on a line of its
own is legal Python code, but the result is thrown away... E.g.

var = 6
type(var) # Works, but meaningless, noone will know what happened
print type(var) # Like the interactive use (more or less)
var_type = type(var) # Now you have a variable containing the result
                      # of the expression. You can use that later
if type(var) == int: # You can use the result in another construct...
     print "%i is an integer!" % var

But don't worry so much about type checking. That's typically not
so important in Python as is is in most other languages, in fact, if
you try to handle types too strictly in Python, you are throwing away
a lot of the benefits of Python's dynamic features.

Perhaps your code is useful with other types than integers, such as
the new decimal type or some upcoming money type. That typecheck might
just make it impossible to use your code in some completely meaningful
way. If you just did nothing, your code would probably throw an
exception if 'var' had a type that didn't make sense, and handling
that exception is probably not more difficult than to handle whatever
action you planned to take if var wasn't an int...

Python is much stricter in its type handling than e.g. C++, so don't
worry so much. Trying to add a string to an int etc, will raise a
sensible exception. It won't lead to any program crash or give any
bizarre result to your calculations.

If you're sanitizing user input, that's a good thing of course, but
then the safe thing would be to read strings (e.g. via raw_input) and
then inspect the string before you evaluate it or cast it to something
else. Actually, int() does this pretty well, so you could just do:

.while 1: # Loop until broken out of...
.    response = raw_input('Number please: ')
.    try:
.        var = int(response)
.        break
.    except ValueError:
.        print response, 'isn't a number!'






More information about the Python-list mailing list