Generator
- A type of iterator
- generator function: function that uses
yield
statement - implement the iterator protocal, call
next
- raise StopIteration exhausted
Less code
Implement an iterator
1 2 3 4 5 6 7 8 9 10 11 12 13 |
class FactIter: def __init__(self, n): self.n = n self.i = 0 def __iter__(self): return self def __next__(self): if self.i >= self.n: raise StopIteration result = math.factrial(self.i) self.i += 1 return result |
Implement a generator
1 2 3 4 |
def factorials(n): for i in range(n): yield math.factorial(i) |
More efficient
Generator Comprehensions
1 2 |
(i**2 for i in range(5)) |
- local scope
- lazy evaluation
- is an iterator, can be exhausted
Delegating Generator
Use the syntax yield from
to yield items in a generator
1 2 3 4 |
for file in ('a.csv', 'b.csv', 'c.csv'): with open(file) as f: yield from f |