isinstance() considered harmful

kosh at aesaeion.com kosh at aesaeion.com
Thu Jan 24 02:51:46 EST 2002


On 23 Jan 2002, Kragen Sitaker wrote:

> To determine whether an object supports an interface
> ----------------------------------------------------
>
> Using isinstance() to determine whether an object
> supports a particular interface is always a bad
> idea.  You are, in essence, including inheritance
> from a particular class in the interface; if
> anyone wants to implement that interface, they
> must derive their class from the class you
> specify, which means they'll inherit its bugs,
> they'll probably have to understand its
> invariants, and, in Python, they'll have to be
> careful not to collide with names it defines.
> (This is especially bad if one of those names is
> __getattr__ or __setattr__, but that's another
> problem.)
>

However I do see it as useful to make base classes that esentially do
nothing but instead encapsulate some kind of behavior so that you can use
isinstance to test if an object implements that kind of behavior.
Otherwise how would you test if an object was able to work in a listish type
way. You don't want to check every method needs to indexing, len etc when
you work with the object all the time however if you put all those methods in
a base class with just pass for an implementation then you can test for an
insinstance of that class and find out very quickly if it is some kind of
list capable object.

I use this in zope a fair bit since I can easily check if an object is
catalogaware, persistent etc. Since each of those items actually
encomapasses a fair number of methods I don't really see any fast way to
check for all of these existance during the time I have to draw the
webpage and hand it to a user.

> It's not just overly conservative; it's also
> overly liberal.  Someone can override methods in
> the interface with broken methods --- in Python,
> they can even override them with non-callable
> objects.  An object's derivation from a particular
> class doesn't guarantee that it implements all the
> protocol that class does.  (Still, breaking
> protocols your base classes implement is almost
> always a bad idea.)
>

Overall I have final say over all code that we use so someone breaking how
things work in an inherited class doesn't happen.





More information about the Python-list mailing list