Python GeneratorExit – Tutorial with Examples

Python GeneratorExit - Tutorial with Examples

Python GeneratorExit is an exception that is raised in generators when they are closed. In this tutorial, we will explore how the GeneratorExit exception works and we will go through a couple of examples to see how it’s used in Python.

What is a Generator?

A Python generator is a function that behaves like an iterator. It allows you to generate a sequence of values at runtime using the yield keyword. The yield keyword pauses the function and saves its state. The function can be resumed later from where it stopped.

Generators are useful when you need to generate a large sequence of values, but you don’t want to store all the values in memory at once.

What is the GeneratorExit Exception?

The GeneratorExit exception is raised when a generator is closed. The exception is raised by the Python interpreter, and it’s raised specifically to inform the generator that it’s being closed.

If a generator raises the GeneratorExit exception, it means that the generator is done generating values, and it’s ready to be closed.

The GeneratorExit exception is a subclass of the BaseException class, which means that it’s not caught by default by the try…except statement.

Example 1: Using GeneratorExit Exception

Let’s look at an example that demonstrates the use of the GeneratorExit exception.

def Counter(n):
    try:
        i = 0
        while True:
            yield i
            i += 1
    except GeneratorExit:
        print("Countdown Stopped")

c = Counter(10)
for i in c:
    print(i)

c.close()

In the above example, we define a Counter function that uses a while loop to generate a sequence of numbers starting from 0 up to a particular value.

We then create an instance of the Counter function, and we use a for loop to iterate over it and print out each number that is generated.

Finally, we call the close() method on the generator object. This will raise the GeneratorExit exception, which will be caught by the try…except statement defined in the Counter function.

The output of this program will be:

0
1
2
3
4
5
6
7
8
9
Countdown Stopped

Example 2: Using the with statement

You can also use the with statement to handle the GeneratorExit exception. Here’s an example:

def Counter(n):
    i = 0
    try:
        while True:
            yield i
            i += 1
    finally:
        print('Done counting')

with Counter(10) as c:
    for i in c:
        print(i)

In the above example, we use the with statement to create a generator object from the Counter function. We then use a for loop to iterate over the generator object and print out each generated number.

Finally, the with statement will handle the GeneratorExit exception by calling the cleanup code in the finally block. In this case, the cleanup code is simply a print statement that indicates that the counting has completed.

The output of this program will be:

0
1
2
3
4
5
6
7
8
9
Done counting

Conclusion

The GeneratorExit exception is an important exception that is raised when a generator is closed. The exception allows generators to perform cleanup tasks before they are closed. We went through a couple of examples to demonstrate how the GeneratorExit exception is used in Python.

Leave a Reply

Your email address will not be published. Required fields are marked *