[Tutor] Getting the type of a variable

wesley chun wescpy at gmail.com
Fri Oct 27 20:32:53 CEST 2006


> > I want to check the type of a variable so that I know which format to use
> > for printing eg
> >
> Alternatively, you could just cast it as a string.

what joshua is saying is that for just displaying something, that it's
just as easy to convert it to a string, or, if you're using print, to
not do anything at all (since objects which are part of print
statements are automagically sent to str()), e.g.,

print "a is a number with a value of", a # no need to convert a

as many others have pointed out, using type() works too, but "type(x)
is type(0)" works slightly faster than "type(x) == type(0)" ... can
any non-tutors guess why?

also, isinstance() works great if you want to do multi-compares.  for
example, here's a snippet out of chapter 4 in my book:

def displayNumType(num):
    print num, 'is',
    if isinstance(num, (int, long, float, complex)):
        print 'a number of type:', type(num).__name__
    else:
        print 'not a number at all!!'

displayNumType(-69)
displayNumType(9999999999999999999999L)
displayNumType(98.6)
displayNumType(-5.2+1.9j)
displayNumType('xxx')

when you run it, you get:

-69 is a number of type: int
9999999999999999999999 is a number of type: long
98.6 is a number of type: float
(-5.2+1.9j) is a number of type: complex
xxx is not a number at all!!

the good news is that isinstance() means only one function call, and
it's pretty fast. if there's any downside of isinstance(), and it's
pretty minor -- well, perhaps it's a feature -- is that it is *not* a
direct type/class comparison, meaning that subclasses will match too:

>>> isinstance(1, object)
True
>>> isinstance('xxx', object)
True

anyway, hope this helps!
-- wesley
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
"Core Python Programming", Prentice Hall, (c)2007,2001
    http://corepython.com

wesley.j.chun :: wescpy-at-gmail.com
python training and technical consulting
cyberweb.consulting : silicon valley, ca
http://cyberwebconsulting.com


More information about the Tutor mailing list