Is there a consensus on how to check a polymorphic instance?

Dan Perl danperl at rogers.com
Tue Nov 23 05:19:44 CET 2004


As you say yourself, many people in this group will probably recommend 
solution #3.  I would agree with them.

You should keep in mind that Alex's recipe (solution #2) was published in 
2001 (before version 2.2 which introduced big changes in terms of OO) so I'm 
not sure he would recommend that solution anymore.  I'll leave it to him to 
give his final judgement.

I haven't read Mertz's book and I don't know in what context he recommends 
solution #1.  Personally I see it useful in situations where you want to 
check whether the class has a method like next() for example, so you want to 
see whether the object is iterable.  But if you implement a base class with 
an attribute x1 it may be risky to just check objects for having that 
attribute.  The object may have an attribute with that name but its role may 
be completely different than what you expect (e.g., your class may use x1 
for a list, but your object is an instance of a class that uses x1 for a 
string).  Same thing with methods.

Go with isinstance().  That's what it's for.

Dan

"Mike Meng" <meng.yan at gmail.com> wrote in message 
news:1101180636.399043.199740 at z14g2000cwz.googlegroups.com...
> hi all,
> I'm a newbie Python programmer with a C++ brain inside. I have a
> lightweight framework in which I design a base class and expect user to
> extend. In other part of the framework, I heavily use the instance of
> this base class (or its children class). How can I ensure the instance
> IS-A base  class instance, since Python is a fully dynamic typing
> language?
>
> I searched and found several different ways to do this:
>
> 1. In `Text Processing in Python', David Mertz suggests using `hasattr'
> to check abilities instead of type checking.
>
> 2. In ActiveState's Python Cookbook site, Alex Martelli suggested a
> safe and accurate `look before you leap' technique on
> http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52291
>
> 3. In this group, some others suggest using isinstance() builtin
> function to check instance.
>
> Now my questions:
> 1. Is my design speaks native Pythonish? Such design is native in C++
> and Java OO style, but I'm not sure about this in Python.
>
> 2. As I state in title, is there a consensus on how to check a
> polymorphic instance? I find all the three ways above is a little bit
> tedious compared with C++ and Java, in which compile-time type checking
> ensures the interface protocol, any better ideas in Python?
> Any comments will be appreciated.
> 





More information about the Python-list mailing list