[Python-ideas] Documenting Python warts

Chris Angelico rosuav at gmail.com
Wed Jan 2 11:01:57 CET 2013


On Wed, Jan 2, 2013 at 8:49 PM, Steven D'Aprano <steve at pearwood.info> wrote:
> On 02/01/13 20:37, Chris Angelico wrote:
>> Calling it "else" makes perfect sense if you're searching for something.
>>
>> for x in lst:
>>    if x.is_what_we_want(): break
>> else:
>>    x=thing()
>>    lst.append(x)
>
>
> Not really. The "else" doesn't match the "if", it matches the "for". That's
> the problem really. Besides, your example is insufficiently general. You
> can't
> assume that the "else" immediately follows the "if", let alone the correct
> if.
>
>
>
> for x in lst:
>     if x.is_what_we_want():
>         break
>     do_something()
>     and_another_thing()
>     if today is Tuesday:
>         print("we must be in Belgium")
> else:
>     x = thing()
>     lst.append(x)
>
>
> So at best it makes *imperfect* sense, sometimes.

Thinking functionally, the for loop is searching for an element in the
list. It'll either find something (and break) or not find anything
(and raise StopIteration). If it finds something, do stuff and break,
else do other stuff. The "else" of the logic corresponds to the
"else:" clause.

Not saying it's always right, but it does at least make some sense in
that particular application, which is a reasonably common one. I've
coded exactly that logic in C++, using a goto to do a "break and skip
the else clause" (with a comment to the effect that I'd rather be
writing Python...).

ChrisA



More information about the Python-ideas mailing list