[Python-ideas] Control Flow - Never Executed Loop Body

Michel Desmoulin desmoulinmichel at gmail.com
Tue Mar 22 13:57:43 EDT 2016



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.
	

> Thinking this further, it might enable much more use-cases and stays
> extensible without the need to invent all kinds of special keywords.
> 
> 
> So, this "for" might roughly be equivalent to (using the "old for"):
> 
> class NeverExecuted(StopIteration):
>     pass
> 
> i = iter(collection)
> try:
>     e = next(i)
> except StopIteration:
>     if [NeverExecuted/StopIteration is catched]:
>         raise NeverExecuted
> else:
>     # do for item e
>     for e in i:
>         # do for item e
>     else:
>         if [StopIteration is catched]:
>             raise StopIteration
> 
> 
> I hope that's not too convoluted.
> 
> Best,
> Sven
> _______________________________________________
> Python-ideas mailing list
> Python-ideas at python.org
> https://mail.python.org/mailman/listinfo/python-ideas
> Code of Conduct: http://python.org/psf/codeofconduct/


More information about the Python-ideas mailing list