Calling a generator function runs no body code at all; it returns a generator object. The body executes only when you call next on it, running until the first yield, which suspends the frame with its local variables intact. Each subsequent next resumes exactly where it stopped. When the body returns, the generator raises StopIteration, which a for loop catches for you.
Why interviewers ask this
This probes whether you understand suspended execution, which is the mental model behind iterators, context managers written with contextlib, and async coroutines. An interviewer can tell within two sentences whether you have only used generators or whether you know the frame is preserved between yields. It also sets up follow ups about the iterator protocol and about send and throw.
How to structure your answer
- Say the call returns an object and runs nothing.
- Describe the suspend and resume cycle around yield.
- Explain how the loop sees the end.
- Connect it to the iterator protocol.
Example answer
Calling it does almost nothing. Python sees the yield keyword at compile time, marks the function as a generator, and the call just hands back a generator object with a frozen frame. Nothing in the body has run yet, which trips people up when they expect their validation at the top to fire immediately. The first next runs until it hits a yield, passes that value out, and freezes the frame with every local still alive. Call next again and execution picks up on the line after the yield. When the function falls off the end or hits a bare return, Python raises StopIteration, and a for loop treats that as the signal to stop. Under the hood a generator satisfies the iterator protocol because it has both dunder iter and dunder next, so it works anywhere an iterable is expected. I lean on this for streaming pipelines. On one project we had four transformation stages chained as generators, and no stage ever held more than a single record.
Walking into this interview soon? GhostPilot listens to your live call, spots the question the moment it is asked, and puts a structured answer on your screen in real time. Try it on your next mock, or grab a $29 Session Pass, no subscription, for the real thing.
See how it worksFollow-up questions to expect
- What does yield from give you?
- How do send and throw work on a generator?
- How is an async generator different?
Related python developer questions
Your interviewer will ask their own version of this. Paste your actual job description into the free Question Predictor and get the 20 questions that role is most likely to ask, with what each one is really probing.
Predict my questions