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

Mike C. Fletcher mcfletch at rogers.com
Fri Dec 7 15:12:17 EST 2001


The lambda form would be slow (extra function call overhead for each 
call, and it _always_ does every check, so never short-circuits once it 
knows the answer is true).  Same basic problem with the list 
comprehension, modulo the overhead of the function call (i.e. no 
short-circuiting).

AFAIK, list comprehensions are basically just syntactic sugar around 
regular loops, so they aren't likely any faster than a for loop.  If 
that's changed, it would be good to know.

Enjoy,
Mike

Brian McErlean wrote:

> "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.
> 


-- 
_______________________________________
   Mike C. Fletcher
   http://members.rogers.com/mcfletch/






More information about the Python-list mailing list