Multi-isinstance idiom (Re: Deprecate tabs for indenting (was Re: Indenting with tabs vs spaces))

Brian McErlean b_mcerlean at yahoo.com
Fri Dec 7 11:26:58 EST 2001


"Mike C. Fletcher" <mcfletch at rogers.com> wrote in message news:<mailman.1007621769.21056.python-list at python.org>...
> That doesn't seem to keep the semantics, it only works if the tested 
> class is an actual sub-class of your combination class, not if it's a 
> child of just one of the parents (that is, it's an "and" test with an 
> extra class added as well).  If you want an or test,  how about:
> 
> try:
>     raise f
> except (future.Step, yada, yada):
>     blah
> except:
>     stuffWhenNotSubClass
> 
> Problem is that it's nothing like intuitive, an explicit function like:
> 
> def ismultiinstance( test, classes ):
>     for classObject in classes:
>         if isinstance( test, classObject):
>             return 1
>     return 0
> 
> Would be much easier to read, though not very computationally efficient 
> (extra function call, loop overhead) compared to letting the C exception 
> machinery handle the project.
> 

Since an empty list is false, how about:

classes = [future.Step, future.Status, future.Announce, 
           possibility.Observe, future.Incarnate, future.Start]

if filter(lambda c,test=test: isinstance(test,c), classes):
    # body

It should be reasonably fast, since the actual looping is in C, though its 
probably ugly enough that you should still put it in its own ismultiinstance 
function.
Alternatively the list comprehension equivalent:

if [c for c in classes if isinstance(test,c)]:
     # do something.


Brian McErlean.



More information about the Python-list mailing list