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

Andrew Barnert abarnert at yahoo.com
Sun Mar 20 20:13:57 EDT 2016


On Mar 20, 2016, at 16:54, Andrew Barnert via Python-ideas <python-ideas at python.org> wrote:

> On Mar 20, 2016, at 16:39, Vito De Tullio <vito.detullio at gmail.com> wrote:
>> 
>> Robert Collins wrote:
>> 
>>>> Maybe I'm missing something, but shoulnd't be like
>>>> 
>>>>   if seq:
>>>>       for elem in seq:
>>>>           do_stuff(elem)
>>>>   else:
>>>>       do_empty_seq_stuff()
>>>> 
>>>> a trivial code handling an empty list?
>>> 
>>> seq = iter([])
>>> 
>>> will cause your example to not run do_empty_seq_stuff().
>> 
>> oh, ok. sorry, didn't think about the iterator object.
>> 
>> 
>> ...thinking about it, is there a reason why the boolean interpretation of an 
>> empty iterator is true?

Possibly a better way to put this than my other answer:

When you really do need to deal with any arbitrary iterable, it's more Pythonic to use the "if element is empty" post-check.

When you expect your input to be a collection* (as was clearly your intuition here), go ahead and make use of that, using exactly the "if seq:" code that you wrote.

If you need to deal with an iterable that might be an iterator rather than a collection, but if so it's guaranteed to be safely peekable... Well, I don't think that will ever actually come up, but if it does, you can do the peek-and-stuff-back thing instead of the "if element is empty". I think it would probably be simpler and more readable to do the post-test, and it would also avoid having to get across to your reader the idea that you can handle both collections and safely-peekable iterators but not non-safely-peekable iterators, but if you have some reason for that precondition that you wanted to express anyway, maybe using the peek-and-stuff code helps get it across?


* Or "reiterable" or "repeatable iterable" or "non-iterator iterable" or any of the other identical or closely parallel concepts. I don't want to restart the argument about which one is more useful here; they all make the right distinction in this case.



More information about the Python-ideas mailing list