On 16.03.2016 18:08, Random832 wrote:
Yeah, well, you can *almost* get there with:

try:
     thing = next(item for item in collection if good(item))
except StopIteration:
     thing = default

But the for/else thing seems like a more natural way to do it. Plus,
this is a toy example, if the body is more than one statement or doesn't
involve returning a value comprehensions aren't a good fit.

Sure, YMMV.

What I don't understand is why Python features "if break, then no else clause", but "if empty, then empty clause".

I found this excellent post: https://shahriar.svbtle.com/pythons-else-clause-in-loops

The described break-else replacement greatly resembles the answers of this thread:

condition_is_met = False
for x in data:
    if meets_condition(x):
        condition_is_met = True

if not condition_is_met:
    # raise error or do additional processing

Compared to the proposed empty clause replacement:

empty = True:
for item in items:
    empty = False
...

if empty:
...


In order to explain why this might be slightly more important to us than to other folks: we work in the field of Web development. As humans are no machines, they usually expect an empty list to be marked as such OR special actions when lists are not filled as expected.

Even Django ({% empty %}) and jinja ( {% else %}) features this type of construct. You might think it's enough when template engines work this way (the output layer). However, I quite regularly could find this useful within the logic part (the actions) of our applications.

Do you think this would be worth posting on python-ideas?

Best,
Sven

--
https://mail.python.org/mailman/listinfo/python-list

Reply via email to