How to request an iterator in python without changing its preliminary request state

I built an iterable object A that contains a list of other objects B. I want to be able to automatically skip a specific object B in the list if it is marked as bad when 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 a conditional expression that is commented out in the pseudo-code above without missing an iteration request (the else clause does not work)

Thanks!

+5
source share
2 answers

You can use the generator function:

  def __iter__(self): for item in self.Blist: if not item.is_bad(): yield item 

The generator function is marked with the yield keyword. The generator function returns a generator object, which is an iterator. It pauses execution in the yield , and then resumes processing when the calling procedure calls next on the intern.

+1
source

What about:

 def __iter__(self): nextB = iter(self.Blist) for b_obj in nextB: if b_obj.is_bad(): yield b_obj 

A simplified example:

 class B: def __init__(self, cond): self.cond = cond def is_bad(self): return self.cond class A: def __init__(self): self.Blist = [B(True), B(False), B(True)] def __iter__(self): nextB = iter(self.Blist) for b_obj in nextB: if b_obj.is_bad(): yield b_obj a = A() for x in a: print(x.is_bad()) >> True True 
+1
source

All Articles