which is better: isinstance() or type()?

Donnal Walter donnal at donnal.net
Fri Aug 2 00:05:59 CEST 2002


Benjamin Han <bhan at andrew.cmu.edu> wrote in message news:<Pine.LNX.4.44.0208011324350.3775-100000 at capriccio.harmony.org>...
> class Foo (list):
>   pass
> 
> f=Foo()
> 
> print isinstance(f,Foo)
> print type(f) is Foo
> 
> 
> so which one is better? I understand that for arbitrary class that doesn't 
> inherit from one of the pre-defined types will get <type 'instance'> after 
> calling type().

Not long ago I asked much the same question. Here is Neal's answer:

Neal Norwitz <neal at metaslash.com> wrote in message news:<pan.2002.07.26.20.58.13.66355.9703 at metaslash.com>...
> On Fri, 26 Jul 2002 16:39:26 -0400, Donnal Walter wrote:
> 
> > I read in Guido's keynote address (slide 15 of 23) that we are now
> > supposed to be using built-in type names instead of the types module.
> > What is the preferred alternative syntax in Python 2.2 for the following
> > snippet?
> > 
> >         ...
> >         if type(content) is types.ListType:
> >             print 'content is a list'
> >         else:
> >             print 'content is not a list'
> 
> Check out PEP 8, Programming Recommendations (near the end).
> 
> 	http://www.python.org/peps/pep-0008.html
> 
> Guido prefers to use isinstance(content, list).
> 
> Neal



More information about the Python-list mailing list