Python Tutorial

Python Flow Control

Python Functions

Python Data Types

Python Date and Time

Python Files

Python String

Python List

Python Dictionary

Python Variable

Python Input/Output

Python Exceptions

Python Advanced

Python GeneratorExit

GeneratorExit is a built-in exception in Python that is raised when a generator is closed before it is exhausted (i.e., before it has finished yielding all its items). Generators are special types of iterators that allow you to iterate over a potentially infinite sequence of items using the yield keyword.

When a generator is closed explicitly using the close() method or implicitly by the garbage collector when the generator is no longer needed, the GeneratorExit exception is raised inside the generator. You can handle this exception to perform cleanup operations before the generator is closed.

Here is an example of using a generator and handling the GeneratorExit exception:

def countdown(n):
    try:
        while n > 0:
            yield n
            n -= 1
    except GeneratorExit:
        print("Generator closed before it was exhausted.")
    finally:
        print("Cleaning up resources...")

# Create a generator object
gen = countdown(5)

# Iterate over the generator
for i in gen:
    print(i)
    if i == 3:
        gen.close()  # Close the generator before it is exhausted

In this example, we have a generator called countdown that counts down from a given number n. We create a generator object gen and start iterating over it using a for loop. When the value of i is 3, we close the generator before it is exhausted. This raises the GeneratorExit exception inside the generator, which we handle using a try-except block. The finally block is used to perform any necessary cleanup operations.

Output:

5
4
3
Generator closed before it was exhausted.
Cleaning up resources...

In most cases, you don't need to handle the GeneratorExit exception explicitly, since generators can be closed automatically by the garbage collector. However, it can be useful to handle this exception when you want to perform cleanup operations or provide custom behavior when the generator is closed.

  1. How to handle GeneratorExit in Python:

    • Description: Use try-except blocks to handle GeneratorExit and perform cleanup tasks if needed.
    • Code:
      def my_generator():
          try:
              while True:
                  yield 1
          except GeneratorExit:
              print("Generator is closing. Cleanup tasks can be performed here.")
      
      gen = my_generator()
      next(gen)
      gen.close()
      
  2. Python generator close() method:

    • Description: The close() method is used to close a generator, triggering a GeneratorExit exception inside the generator.
    • Code:
      def my_generator():
          try:
              while True:
                  yield 1
          except GeneratorExit:
              print("Generator is closing. Cleanup tasks can be performed here.")
      
      gen = my_generator()
      next(gen)
      gen.close()