I built an iterable object A that holds a list of other objects B. I want to be able to automatically skip a particular object B on the list if it is flagged bad when the object A is used in a for loop.
class A():
def __init__(self):
self.Blist = [B(1), B(2), B(3)] #where B(2).is_bad() is True, while the other .is_bad() are False
def __iter__(self):
nextB = iter(self.Blist)
#if nextB.next().is_bad():
# return after skip
#else:
# return nextB
However, I cannot figure out how to write the conditional that is commented in pseudo code above, without skipping the iteration inquired (the else clause fails)
Thanks!
You can use a generator function:
def __iter__(self):
for item in self.Blist:
if not item.is_bad():
yield item
A generator function is marked by the keyword yield
. A generator function returns a generator object, which is an iterator. It will suspend execution at the yield
statement and then resume processing when the calling routine calls next
on the interator.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With