"for" with "else"?
Stephen Horne
$$$$$$$$$$$$$$$$$ at $$$$$$$$$$$$$$$$$$$$.co.uk
Wed Oct 1 22:32:04 EDT 2003
On Wed, 01 Oct 2003 03:31:10 GMT, "Andrew Dalke"
<adalke at mindspring.com> wrote:
>In my search, I didn't see any examples which were
>better done with exceptions -- and since (string) exceptions
>existed in the language for a long time (from the start
>I would imagine and definitely pre-1.3, which is
>about when I started), I find it hard to believe that
>your statement reflects what really happened.
You are quite right - I think I mentioned already in another post that
I'd completely forgotten the break-on-found idiom until I read Michael
Gearys post (I don't always read a thread fully before I reply to
stuff).
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'
The cleanest way to eliminate the 'break' and 'else' is probably as
follows...
try:
c = data.next ()
while c.isspace() or (c<' ' or ord(c) > 0x7f) : c = data.next ()
except StopIteration :
finfo.Type = 'TEXT'
Or possibly...
try :
ifilter (lambda c : c in string.printable, data).next ()
except StopIteration :
finfo.Type = 'TEXT'
But these approaches both have a major failing - they don't express
the intention well.
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.
--
Steve Horne
steve at ninereeds dot fsnet dot co dot uk
More information about the Python-list
mailing list