Generators have been an important part of Python ever since they were introduced with PEP 255.
Generator functions allow you to declare a function that behaves like an iterator.
They allow programmers to make an iterator in a fast, easy, and clean way.
What's an iterator, you may ask?
An iterator is an object that can be iterated (looped) upon. It is used to abstract a container of data to make it behave like an iterable object. You probably already use a few iterable objects every day: strings, lists, and dictionaries to name a few.
An iterator is defined by a class that implements the Iterator Protocol. This protocol looks for two methods within the class: __iter__and __next__.
Whoa, step back. Why would you even want to make iterators?
Saving memory space
Iterators don't compute the value of each item when instantiated. They only compute it when you ask for it. This is known as lazy evaluation.
Lazy evaluation is useful when you have a very large data set to compute. It allows you to start using the data immediately, while the whole data set is being computed.
Let's say we want to get all the prime numbers that are smaller than a maximum number.
We first define the function that checks if a number is prime:
def check_prime(number): for divisor in range(2, int(number ** 0.5) + 1): if number % divisor == 0: return False return True
Then, we define the iterator class that will include the __iter__and __next__methods:
class Primes: def __init__(self, max): self.max = max self.number = 1
Primes are instantiated with a maximum value. If the next prime is greater or equal than the max, the iterator will raise a StopIteration exception, which ends the iterator.
When we request the next element in the iterator, it will increment the number by 1 and check if it's a prime number. If it's not, it will call __next__again until the number is prime. Once it is, the iterator returns the number.
By using an iterator, we're not creating a list of prime numbers in our memory. Instead, we're generating the next prime number every time we request for it.
Let's try it out:
primes = Primes(100000000000)
for x in primes: print(x)
<__main__.Primes object at 0x1021834a8> 2 3 5 7 11 ...
Every iteration of the Primes object calls __next__to generate the next prime number.
Iterators can only be iterated over once. If you try to iterate over primes again, no value will be returned. It will behave like an empty list.
Now that we know what iterators are and how to make one, we'll move on to generators.
Recall that generator functions allow us to create iterators in a more simple fashion.
Generators introduce the yield statement to Python. It works a bit like return because it returns a value.
The difference is that it saves the state of the function. The next time the function is called, execution continues from where it left off, with the same variable values it had before yielding.
If we transform our Primes iterator into a generator, it'll look like this:
def Primes(max): number = 1 while number < max: number += 1 if check_prime(number): yield number