[Tutor] question re type()

Aditya Lal aditya.n.lal at gmail.com
Wed Oct 31 07:13:33 CET 2007


On 10/29/07, Kent Johnson <kent37 at tds.net> wrote:
>
> Aditya Lal wrote:
> > or use types module
> >
> > import types
> >
> > if type(n) == types.IntType or type(n) == types.LongType :
> >     blah!
>
> A few notes:
> - If you look at types.py, you find
> IntType = int
> LongType = long
>
> and so on for all the built-in types, so there is no need or advantage
> to importing types vs
>    if type(n) == int
>
> - Common Python practice is to prefer the least restrictive type check
> possible. For Dick's specific case it doesn't matter, but I generally
> use isinstance() instead of checking for a specific type. The difference
> is that isinstance() is true for subtypes as well as the named type. You
> can also pass a tuple of types to isinstance() so you can say
>    if isinstance(n, (int, long))
>
> Kent
>
>
I completely agree that the check " type(n) == int " is very intuitive and
simple. Its just that there are many more types that the basic ones and
'types' module provide a "consistent" way for checking for types. As an
example - consider a function :
def execMyFun( f ) :
   if type(f) == types.GeneratorType :
      return f.next()
   elif type(f) == types.FunctionType :
      return f()
   else :
      raise Exception("Invalid type for f : " + type(f) )

Here types module came to the rescue which otherwise I would have written
using exception handling. *Well ! if you have a cleaner solution do let me
know.*


BTW, isinstance is cool :) as it checks for all subclasses as well - didn't
think of that.


--
Aditya
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20071031/36c299fc/attachment-0001.htm 


More information about the Tutor mailing list