Re: [Tutor] isinstance() evil?

Magnus Lycka magnus at thinkware.se
Tue Dec 2 08:25:03 EST 2003


> I've read a couple aricle here and there that isinstance() is generally a 
> bad idea.

I wouldn't say that. It certainly has its uses.
 
> I have a question on that.
> 
> I'm writing a small method used for debugging programs using a particular 
> class I wrote.  I want it to accept either an instance of the class, or a 
> list of instances (or, for that matter, a list of list of instances, etc., 
> if that's really what you want to do).
> 
> I use isinstance() for this; it seems very straightforward to do this 
> recursively:
> 
>     Dump(thing):
> 
>         if isinstance(thing, list):
>             for element in thing:
>                 Dump(element)
>             return

I wouldn't use it in this case though. It seems to me that there is
no reason to restrict this particular behaviour to lists. Why not
allow other sequences, such as tuples, or maybe instances of some
class you made.

A simple option would be...

        try:
            for element in thing:
                Dump(element)
        except TypeError:
            # rest of dump...

This has a few problems though. First of all, you could get some
other type error that the one you get from looping over something
unloopable. But that is fixable:

        try:
            for element in thing:
                Dump(element)
        except TypeError, e:
            if str(e) != 'iteration over non-sequence':
                raise
            # rest of dump...

The second problem is that throwing exceptions is a bit costly
from a performance point of view. One might also have principal
objections about using the exception handling for situations that
aren't really errors or exceptioonal conditions.


-- 
Magnus Lycka, Thinkware AB
Alvans vag 99, SE-907 50 UMEA, SWEDEN
phone: int+46 70 582 80 65, fax: int+46 70 612 80 65
http://www.thinkware.se/  mailto:magnus at thinkware.se



More information about the Tutor mailing list