[Tutor] Type Checking:
Danny Yoo
dyoo@hkn.eecs.berkeley.edu
Sat, 3 Mar 2001 20:24:28 -0800 (PST)
On Sat, 3 Mar 2001, Tim Johnson wrote:
> Consider the following code:
> # code begins
> >>> str = 'hello'
> >>> type(str)
> <type 'string'>
> >>> if type(str) == 'string':
> ... print "it's a string"
> ... else:
> ... print "I don't know how to type"
(Side note: try to avoid using 'str' as a variable name: it's already the
name of the built-in str() function that converts anything to a string.
This warning is meant to avoid potential weirdness later on; you'll
probably want to keep that str() function for a rainy day. *grin*)
Other people have already pointed out that
type(mystr) == types.StringType
is the traditional way of doing the type comparison. The reason that
type(mystr) == 'string':
doesn't quite work is because types are things --- objects --- that need
to be compared with either other. This might not make much sense yet;
let's make an analogy with what we already know. In Python:
1 == '1'
is false, even though they 'look' the same, and the reason is because
numbers are different from strings. Likewise:
type(mystr) == "<type 'string'>"
doesn't work either; types are things that are different from both strings
and numbers. That's why Python has a premade collection of these type
objects in the 'types' module, to make the comparison easier and to avoid
this issue. However, in a pinch, this will work:
type(mystr) == type('this is a string')
because we grab the type of mystr, and grab the type of a string, and
compare the two. This works because we're comparing between alike things.
It's the apples and oranges argument, taken in a very literal setting.
(Does anyone find it humorous that there's even a types.TypeType object in
there?)
Good luck to you.