GeneratorExit in Python: Causes and Fixes with Simple Examples
What is GeneratorExit in Python?
A GeneratorExit in Python occurs when a generator is closed or terminated, usually when the program stops iteration or calls the close() method on a generator.
In simple words, Python is saying:
“This generator has been closed and should stop execution.”
Unlike normal errors, GeneratorExit is not a bug — it is a signal to stop a generator gracefully.
What is a Generator in Python?
A generator is a special function that returns values one at a time using the yield keyword instead of returning all values at once.
Example:
def numbers():
yield 1
yield 2
yield 3
Generators are memory-efficient and commonly used for loops, large data processing, and streams.
When Does GeneratorExit Occur?
GeneratorExit occurs when:
-
A generator is closed manually
-
A generator finishes execution
-
A program stops generator iteration early
-
Python garbage collects a generator
-
generator.close()is called
Common GeneratorExit Error Message
Example 1: GeneratorExit When Closing a Generator
❌ Code
def my_generator():
try:
yield 1
yield 2
except GeneratorExit:
print("Generator closed!")
gen = my_generator()
print(next(gen))
gen.close()
✔ Output
✔ Python raised GeneratorExit when closing the generator.
Example 2: GeneratorExit Raised Automatically
❌ Code
def demo():
try:
yield "Hello"
finally:
print("Generator cleanup")
g = demo()
next(g)
g.close()
✔ Output shows cleanup when generator exits.
Example 3: Wrong Handling of GeneratorExit
❌ Incorrect Code
def bad_generator():
try:
yield 1
except GeneratorExit:
print("Trying to continue")
yield 2 # ❌ Not allowed
❌ Error
✔ You should not yield values after GeneratorExit.
Correct Way to Handle GeneratorExit
✔ Correct Code
def good_generator():
try:
yield 1
yield 2
except GeneratorExit:
print("Generator closed properly")
return
Why GeneratorExit is Important
✔ Allows safe generator shutdown
✔ Ensures cleanup of resources
✔ Prevents memory leaks
✔ Helps stop long-running generators
How to Avoid GeneratorExit Problems
-
Don’t yield values after generator is closed
-
Use
try–finallyfor cleanup -
Close generators when no longer needed
-
Avoid unnecessary generator loops
Difference Between GeneratorExit and StopIteration
| Error | Meaning |
|---|---|
| StopIteration | Generator finished normally |
| GeneratorExit | Generator was forced to close |
Summary
GeneratorExit in Python occurs when a generator is closed and should stop execution.
It is a normal control signal, not a coding mistake.
Understanding it helps you write safe and memory-efficient generators.
❓ Frequently Asked Questions (FAQ)
Q1: Is GeneratorExit a real error?
It is an exception used to stop generators safely.
Q2: Should I catch GeneratorExit?
Only if you need cleanup actions.
Q3: Can I ignore GeneratorExit?
No — generators should stop when it occurs.
📌 Final Tip
Never try to yield new values after GeneratorExit - always exit cleanly.
Comments
Post a Comment