Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to inquire an iterator in python without changing its pre-inquire state

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!

like image 907
Pato Avatar asked Oct 29 '22 22:10

Pato


1 Answers

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.

like image 146
Hans Then Avatar answered Nov 15 '22 05:11

Hans Then