On Tue, Jul 21, 2020 at 05:48:35PM -0700, Christopher Barker wrote:

> for something in some_iterable:
>     some_stuff_with_maybe_a_break
> else:  # if not break:
>     something_more
> 
> and no changes needed to Python!
> 
> I may actually start doing that myself ...

I always do that, not because I need it now, but because the next person 
who reads my code in six months might need it.

That person might even be me.


> As for the "loop didn't run at all" case: Does anyone find a need for that?
> Personally, I've found that everytime I do some kind of check for an empty
> iterable before a loop, it was totally unnecessary.

If we had it, I would use it. It is generally possible to work around 
the lack, e.g. with an explicit test of a sequence (but that doesn't 
work with iterators), but I find that sometimes it isn't *obvious* that 
the empty loop case is handled correctly:

    for x in iterable:
        do stuff
    continue processing

If iterable is empty, is the code still correct? Sometimes that's 
obvious, but when it *isn't* obvious I wish there was a way to run this:

    for x in iterable:
        do stuff
    if loop was empty:
        whatever is needed to make it obviously correct
        such as an assert, or early return

I'd rather have an extra couple of lines of code and obviously correct 
code than save a few lines and have to think hard about whether the code 
is correct :-)

More rarely I do need to treat the empty case specially. If the iterator 
is a sequence I can test the length up front, but this doesn't work with 
iterables.

It's not *hard* to work around this, it's just inelegant.


-- 
Steven
_______________________________________________
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-le...@python.org
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at 
https://mail.python.org/archives/list/python-ideas@python.org/message/RHIY4356PWI5ESEZ7AA2MXW3MBATPCVI/
Code of Conduct: http://python.org/psf/codeofconduct/

Reply via email to