Checking the type

Ken Seehof kens at sightreader.com
Thu Mar 22 20:03:58 CET 2001


Here's a handy trick that lets you avoid importing the types module,
and saves you from learning all the type names (ListType, et. al.)
The compare is a tiny bit slower, but looks nicer (I think).

>>> a = [2,3,4]
>>> b = "3,4,5"
>>> def foo(x):
...  if type(x) == type([]):   # just use type() with a literal
...     print 'yes'
...  else:
...     print 'no'
...
>>> foo(a)
yes
>>> foo(b)
no


> Markus Reitz <Markus_Reitz at yahoo.com> wrote in message
> news:99a493$bhl$1 at sun.rhrk.uni-kl.de...
> > Hi,
> >
> > is there a possibilty to check if a variable refers to an object of type
> x?
> > Does a typeof-command exist in Python:
> >
> >   if a typeof list:
> >      #Commands only useable with list
> >
> > I read the Python Tutorial, but have not found a hint to this topic.
> >
> > Thanks
> >
> > Markus
> >
> >
>
> Sample code:
>
>      def Show (self, object):
>           """ <object> can be number, string, list, tuple, or
dictionary"""
>           from types import *
>           kind = type (object)
>           if kind == StringType:
>               self.Writeln (object)
>           elif (kind == ListType) or (kind == TupleType):
>                for item in object:
>                     self.Writeln (item)
>           elif kind == DictType:
>                sKeys = object.keys()
>                sKeys.sort()
>                for key in sKeys:
>                     self.Writeln ('%-16s   %s' % (key, `object[key]`))
>           else:
>               self.Writeln (`object`)
>
>           self.Activate()
>
> Mike






More information about the Python-list mailing list