Unlocking the Power of Generators: Mastering the close() Method in Python

Exploring the Versatility of Generators and How to Gracefully Close Them

Max N
3 min readApr 11, 2024

Generators in Python are powerful tools that allow you to create iterables without the need to store the entire sequence in memory. They’re particularly useful when working with large datasets or infinite sequences. In this article, we’ll dive into the close() method, which provides a way to gracefully terminate a generator’s execution.

Generators are created using the yield keyword, instead of the return statement used in regular functions. When a generator function is called, it returns a generator object, which can be iterated over to retrieve the yielded values one at a time.

Here’s a simple example of a generator function that generates the first n Fibonacci numbers:

def fibonacci(n):
a, b = 0, 1
for i in range(n):
yield a
a, b = b, a + b

You can use this generator like this:

fib_gen = fibonacci(10)
for num in fib_gen:
print(num)

This will output the first 10 Fibonacci numbers:

0
1
1
2
3
5
8
13
21
34

--

--

Max N

A writer that writes about JavaScript and Python to beginners. If you find my articles helpful, feel free to follow.