Reputation: 140
In the below method, if a certain condition is met, I'm using yield
to return a generator. Within that same method, I'd like to check if the yield
has already been triggered (thus the generator populated).
I've read that next(generator)
is the common way to check if a generator is empty. But I don't see how I could apply that in this situation where the check has to happened within the method itself.
Here's the snippet :
def my_method(my_list: list) -> List[Iterable]:
for el in my_list:
if el == "foo":
yield el
if <yield_has_been_triggered> and el == "bar":
break
My current non-elegant solution is :
def my_method(my_list: list) -> List[Iterable]:
check = False
for el in my_list:
if el == "foo":
check = True
yield el
if check and el == "bar":
break
Is there a solution to get this <yield_has_been_triggered> information ?
Upvotes: 1
Views: 143
Reputation: 3385
I think you'd probably look at doing that where you actually called the generator tbh:
called = False
for item in my_method(<list>);
if called and item == "bar":
break
called = True
...
But otherwise, pretty much how you've done it I think.
In [3]: def myfunc():
...: _called = False
...: for i in range(10):
...: if _called and i == 5:
...: break
...: _called = True
...: yield i
...:
In [4]: for i in myfunc():
...: print(i)
...:
0
1
2
3
4
Upvotes: 1