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.
Python code
15 linesdef 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
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
- Use `contextlib.closing()` to automatically close a generator within a `with` block.
- 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
More from Comprehensions & generators
- Batch Rows in Chunks with a Generator in Python easy
- Build a Generator Pipeline in Python: Filter Then Map medium
- Build a lazy generator to read file lines in Python easy
- Chunk an Iterable into Batches with a Generator in Python easy
- Convert Data in Python with Comprehensions and Generators easy
- Count Data in Python with Comprehensions and Generators easy
Keep learning
Related tutorials and quizzes for this topic.