[Python-ideas] Control Flow - Never Executed Loop Body
Sven R. Kunze
srkunze at mail.de
Tue Mar 22 14:02:26 EDT 2016
On 22.03.2016 18:57, Michel Desmoulin wrote:
>
> Le 22/03/2016 18:21, Sven R. Kunze a écrit :
>> On 22.03.2016 16:09, Stephen J. Turnbull wrote:
>>> Chris Barker writes:
>>> > All that being said:
>>> >
>>> > how about "elempty"?, to go with elif?
>>>
>>> -1 Not to my taste, to say the least.
>> Hmm, it seems there is no easy solution for this. What do you think
>> about an alternative that can handle more than empty and else?
>>
>> for item in collection:
>> # do for item
>> except NeverExecuted:
>> # do if collection is empty
>>
>> It basically merges "try" and "for" and make "for" emit EmptyCollection.
>> So, independent of the initial "never executed loop body" use-case, one
>> could also emulate the "else" clause by:
>>
>> for item in collection:
>> # do for item
>> except StopIteration:
>> # do after the loop
>>
> It's an interesting idea. Generalizing except for more block I mean.
>
> Imagine:
>
> if user:
> print(user.permissions[0])
> except IndexError:
> print('anonymous')
>
> with open('foo') as f:
> print(f.read())
> except IOError:
> print('meh')
>
> for item in collection:
> # do for item
> except NeverExecuted:
> # do if collection is empty
>
> Not only does it allow interesting new usages such as the for loop empty
> pattern, but it does save a level of indentation for many classic use
> cases where you would nest try/except.
That is indeed an important detail. I know from our internal guidelines
that it is recommended to reduce the indentation as much as possible.
So, this would come in handy.
Best,
Sven
More information about the Python-ideas
mailing list