[Python-ideas] Documenting Python warts

Steven D'Aprano steve at pearwood.info
Wed Jan 2 10:49:32 CET 2013


On 02/01/13 20:37, Chris Angelico wrote:
> On Wed, Jan 2, 2013 at 8:27 PM, Steven D'Aprano<steve at pearwood.info>  wrote:
>> There would be a lot less confusion if they weren't called "else". Even
>> now, I have to explicitly remind myself that the else block doesn't
>> run if the for loop is empty, but *after* the for block.
>>
>> # Python 4000 proposal:
>> for x in seq:
>>      ...
>> then:
>>      # this is skipped by a break
>> else:
>>      # this runs only if seq is empty
>
> 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.


-- 
Steven



More information about the Python-ideas mailing list