<aside> 👨🏼‍💻 This page introduce the most important features of Python generators.

</aside>

Support my work buying me a coffee ☕

Martí Grau is R&D and IA engineer

Description

Advantages

1) Easy to implement

Generators can be implemented in a clear and concise way as compared to their iterator class counterpart.

# Using Iterator Class
class PowTwo:
    def __init__(self, max=0):
        self.n = 0
        self.max = max

    def __iter__(self):
        return self

    def __next__(self):
        if self.n > self.max:
            raise StopIteration

        result = 2 ** self.n
        self.n += 1
        return result

# Using generator function
def PowTwoGen(max=0):
    n = 0
    while n < max:
        yield 2 ** n
        n += 1

2) Memory Efficient

Generator implementation of such sequences is memory friendly and is preferred since it only produces one item at a time.

3) Represent Infinite Stream

Infinite streams cannot be stored in memory, and since generators produce only one item at a time, they can represent an infinite stream of data.

def all_even():
    n = 0
    while True:
        yield n
        n += 2

4) Pipelining Generators

Multiple generators can be used to pipeline a series of operations.

# 1 generator that produces the numbers in the Fibonacci series
# 2 generator for squaring numbers.
def fibonacci_numbers(nums):
    x, y = 0, 1
    for _ in range(nums):
        x, y = y, x+y
        yield x

def square(nums):
    for num in nums:
        yield num**2

print(sum(square(fibonacci_numbers(10))))