What happens when a generator is garbage-collected, and what is GeneratorExit?
PICTURE THIS: HOW TO EXPLAIN IT
Simple meaning
When a generator is closed, Python raises GeneratorExit at the paused yield so finally blocks can run.
WHY — Generators instead of guessing?
Why interviewers care about Generators:
who only read docs from people who shipped.
and tied to Python work.
Name the idea, why it exists, then one short example.
End with when you use it and one common pitfall.
STEPS — What happens step by step?
Before you speak the answer, walk the interviewer through these steps:
- 1When a generator is
closed, Python raises GeneratorExit at the paused yield so finally blocks can run.
- 2Catching GeneratorExit and yielding
again is a RuntimeError
- 3How it works
you should re-raise or return.
- 4This matters for generators
that hold DB cursors or files.
- 5Common mistake
What juniors usually get wrong.
- 6Close
When you pick this over the alternative.
EXAMPLE — See it in action
Here's a short line you can speak, broken into clear beats:
Note: Adapt this scaffold to your own project — keep it under 60–90 seconds.
Key takeaway
When a generator is closed, Python raises GeneratorExit at the paused yield so finally blocks can run. Catching GeneratorExit and yielding again is a RuntimeError