How to Close a Generator and Handle GeneratorExit in Python

This Python code demonstrates how to explicitly close a generator using the close() method and handle the GeneratorExit exception through a finally block to run cleanup logic.

Easy Python 3.9+ Aug 9, 2026 Comprehensions & generators 12 views 0 copies

Python code

15 lines
Python 3.9+
def countdown(n):
    try:
        while n > 0:
            yield n
            n -= 1
    finally:
        print(f"Generator closed after countdown completed")


if __name__ == "__main__":
    gen = countdown(5)
    print(next(gen))
    print(next(gen))
    gen.close()
    print("Generator closed explicitly")

Output

stdout
5
4
Generator closed after countdown completed
Generator closed explicitly

How it works

When you call close() on a generator, Python raises the GeneratorExit exception inside the generator at its current yield point. If the generator has a finally block, it will execute, allowing you to perform cleanup actions like releasing resources or logging. After the finally block completes, the generator is terminated and further attempts to iterate it raise StopIteration. In this example, the finally block prints a message, then the program continues with the next statement after close(). This pattern ensures that resources are properly released even when a generator is abandoned before completion.

Common mistakes

  • Calling `close()` on an already-closed generator raises `StopIteration` if iterated again; avoid using it after closing.
  • Forgetting that `GeneratorExit` is not caught by normal `except Exception` handlers; use `finally` or catch `GeneratorExit` explicitly if needed.
  • Assuming `close()` is asynchronous; it is synchronous — use `aclose()` for async generators.

Variations

  1. Use `contextlib.closing()` to automatically close a generator within a `with` block.
  2. Handle cleanup by wrapping generator logic in a `try/finally` without relying on explicit `close()` calls.

Real-world use cases

  • Releasing database connections or file handles when a data-generation loop is interrupted early.
  • Flushing and closing log streams that a generator writes to, ensuring no partial writes are lost.
  • Cancelling background tasks or timers when a producer generator is no longer needed in a streaming pipeline.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Comprehensions & generators

Related tutorials and quizzes for this topic.