Otherwise clause in for statement to run when a empty iterable is used

When working with generators, AFAIK, there's currently no easy way to handle the case of an empty generator (which can be useful if such case is an error). Converting the generator to a, say, list, is not a solution if the generator is intrinsically infinite. I propose to have an "otherwise" clause in the "for" statement that runs only if no items are to be processed; that is, to have the following code: # where get_items() may be an infinite generator for item in get_items(): SUITE1 otherwise: SUITE2 be semantically equivalent to: items_iter = iter(get_items()) try: first_item = next(items_iter) except StopIteration: SUITE2 else: for item in itertools.chain([first_item], items_iter): SUITE1

This should have been: When working with generators in a for statement, AFAIK, there's currently no easy way to handle the case of an empty generator (which can be useful if such case is an error).

I find that when I run into a similar scenario the reason why I need the iterable to be non-empty is because I'm trying to find something in it, and for this the `else` clause works pretty well: for item in get_items(): if check(item): do_thing(item) break else: raise ValueError() Early returns can also be useful: for item in get_items(): if check(item): return do_thing(item) raise ValueError()

On Tue, Sep 14, 2021 at 11:02 PM Valentin Berlier <berlier.v@gmail.com> wrote:
I find that when I run into a similar scenario the reason why I need the iterable to be non-empty is because I'm trying to find something in it, and for this the `else` clause works pretty well:
for item in get_items(): if check(item): do_thing(item) break else: raise ValueError()
Early returns can also be useful:
for item in get_items(): if check(item): return do_thing(item) raise ValueError()
Another useful method is a sentinel: item, no_items = object() for item in get_items(): frob(item) if item is no_items: raise ValueError() --- Ricky. "I've never met a Kentucky man who wasn't either thinking about going home or actually going home." - Happy Chandler

Your code has an unpacking error in the first line. I think you mean this, right? no_items = object() item = no_items for item in get_items(): frob(item) if item is no_items: raise ValueError()

On Sun, Sep 19, 2021, 6:42 PM Andre Delfino <adelfino@gmail.com> wrote:
Your code has an unpacking error in the first line. I think you mean this, right?
no_items = object() item = no_items
for item in get_items(): frob(item)
if item is no_items: raise ValueError()
Sorry yes. Actually I intended to write this but it's the same thing. no_items = item = object()
participants (3)
-
Andre Delfino
-
Ricky Teachey
-
Valentin Berlier