PDA

View Full Version : if-then with types...


Scrapz
11-21-2002, 10:37 AM
I'm writing a python module, and am doing really well, except for the elaborate error handling that I'm trying to incorporate. I'm trying to see if a certain value is of type 'int' - and if not, print something... simple really...


if type(quality) != "int" or type(quality) != "float":
print "Invalid quality - should be of type 'int' or 'float' not %s" % type(quality)


...now that statement proves false even if I stick a 'int' value to it. I've also changed the first line to:


if type(quality) != "<type 'int'>" or type(quality) != "<type 'float'>":


...but it still fails. Any clues on how to get around this?

TTFN,
Scrapz :p

Strike
11-21-2002, 10:43 AM
There's a couple of ways:

The most easy-to-read way, IMO:

>>> if type(1) is int: print "Yup"
...
Yup


The "more OO" way:

>>> if "abc".__class__ is str: print "yup"
...
yup


And the way I used to have to do things before the basic datatypes became classes:

>>> if type(5.043) == type(0.0): print "yup"
...
yup
>>> if type([1, 2]) == type([]): print "yup"
...
yup

Scrapz
11-21-2002, 10:49 AM
Thanks, that works, but only after I realized I should have used AND not OR in that statement, otherwise it would always fail :rolleyes:

inkedmn
11-21-2002, 11:39 AM
i discovered the "types" module awhile back, it works very similarly to what Strike had:

>>> import types
>>> if type("brett") is types.StringType:
... print "String"
...
String


anyway, you can read about it here: http://www.python.org/doc/current/lib/module-types.html

:)

Strike
11-21-2002, 12:35 PM
Ah yeah, that was the only other way of doing it before types became classes, I believe ... I just preferred using an empty datatype and running type() on that, even though it's a bit less obvious. I think the very first example I have above is simpler and just as clear.

jemfinch
11-21-2002, 02:39 PM
The most backwards compatible way is to do this:


if type(aVariable) == type(1): # Check to see if it's an int type


The best way since 2.2 is this:


if type(aVariable) == int:


Since, in 2.2+, the type name (int, str, etc.) is the type (check out type(int) -- it's of type type :))

Jeremy