The generator method .close()
is used to terminate a generator early. Once the .close()
method is called the generator is finished just like the end of a for loop
. Any further iteration attempts will raise a StopIteration
exception.
def generator(): i = 0 while True: yield i i += 1 my_generator = generator() next(my_generator) next(my_generator) my_generator.close() next(my_generator) # raises StopGenerator exception
In the above example, my_generator()
holds an an infinite generator object. After a couple next(my_generator)
calls, my_generator.close()
is called. When we attempt to call next(my_generator)
again, a StopIteration
exception is raised.
The .close()
method works by raising a GeneratorExit
exception inside the generator function. The exception is generally ignored but can be handled using try
and except
.
def generator(): i = 0 while True: try: yield i except GeneratorExit: print("Early exit, BYE!") break i += 1 my_generator = generator() for item in my_generator: print(item) if item == 1: my_generator.close()
0 1 Early exit, BYE!
Putting the yield
expression in a try
block we can handle the GeneratorExit
exception. In this case, we simply print out a message. Because we interrupted the automatic behavior of the .close()
method, we must also use a break
to exit the loop or else a RuntimeError
will occur.
To practice this further, we can attempt to use the .close()
method on our student generator.
Instructions
We have a collection of 5,000 students. We only want to retrieve information on the first 100 students. Use the close()
method to terminate the generator after 100 students.