"for" with "else"?

David Eppstein eppstein at ics.uci.edu
Wed Oct 1 23:10:03 EDT 2003


In article <ruumnv0dul3eb4rrfj9vrn1qluhc964vls at 4ax.com>,
 Stephen Horne <$$$$$$$$$$$$$$$$$@$$$$$$$$$$$$$$$$$$$$.co.uk> wrote:

> I still think that exception-based approaches are far from painful for
> this kind of stuff. However, with your example from binhex.py...
> 
>   for c in data:
>       if not c.isspace() and (c<' ' or ord(c) > 0x7f):
>           break
>   else:
>       finfo.Type = 'TEXT'
... 
> Actually, there is a very clean and expressive approach that I'd use
> if I had access to my own library stuff...
> 
>   if mylib.exists (lambda c : c in string.printable, data) :
>     finfo.Type = 'TEXT'
> 
> with, in 'mylib'...
> 
>   def exists (pred, seq) :
>     for i in seq :
>       if pred(i) : return True
>     return False
> 
> ...which is, of course, cheating as that return is just as
> unstructured as a break - but I don't mind cheating too much when it
> is localised in a trivial library function.

Haven't you inverted the logic here?
You want a universal quantifier, not an existential one.

-- 
David Eppstein                      http://www.ics.uci.edu/~eppstein/
Univ. of California, Irvine, School of Information & Computer Science




More information about the Python-list mailing list