Python: Iterator returns None

Here is my code:

class Prizes(object): def __init__(self, purchases, n, d): self.p = purchases self.n = n self.d = d self.x = 1 def __iter__(self): return self def __next__(self): print(self.x) if self.x % self.n == 0 and self.p[self.x - 1] % self.d == 0: self.x = self.x + 1 return self.x - 1 elif self.x > len(self.p): raise StopIteration self.x = self.x + 1 def superPrize(purchases, n, d): return list(Prizes(purchases, n, d)) 

Usage example:

 superPrize([12, 43, 13, 465, 1, 13], 2, 3) 

The output should be:

 [4] 

But the actual conclusion:

 [None, None, None, 4, None, None]. 

Why is this happening?

+5
source share
2 answers

Your problem is your implementation of __next__ . When Python calls __next__ , it will always wait for the return value . However, in your case, it looks like you do not always have a return value for each call. Thus, Python uses the function's default return value, None :

You need to somehow maintain programmatic control inside __next__ until you get the actual return value. This can be done using while -loop:

 def __next__(self): while True: if self.x % self.n == 0 and self.p[self.x - 1] % self.d == 0: self.x = self.x + 1 return self.x - 1 elif self.x > len(self.p): raise StopIteration self.x = self.x + 1 
+2
source

Wrap it with while so that your method does not return a value until you find it:

 def __next__(self): while True: if self.x % self.n == 0 and self.p[self.x - 1] % self.d == 0: self.x = self.x + 1 return self.x - 1 elif self.x > len(self.p): raise StopIteration self.x = self.x + 1 

Things working with iterators call __next__ , expecting it to return a value, but the method returns the value only if otherwise, it reaches the end of the method and returns None .

+1
source

Source: https://habr.com/ru/post/1271283/


All Articles