Skip to the solution
MediumDSA14 min read

How does yield from delegation work?

707 views

The problem

Question presented to candidate: "Python has yield from. Isn't that just a shorter way of writing for x in sub: yield x? Explain what it really does, and when the difference matters."

What a strong answer should cover:

  • yield from <iterable> makes the current generator a pass-through for a sub-iterator: every value the sub-iterator produces goes straight to the outer caller, and the outer generator stays paused at that line until the sub-iterator is exhausted.
  • It is more than the for loop: send() values, throw() exceptions and close() are forwarded to the subgenerator, which the loop version cannot do (the loop only ever calls next()).
  • The value of the yield from expression is the subgenerator's return value, carried by StopIteration.value โ€” so result = yield from sub() lets helper generators return results.
  • Typical uses: flattening recursive structures, splitting a large generator into smaller helper generators, and (historically) the generator-based coroutines that came before async/await. It was added by PEP 380 in Python 3.3.
  • CPython details: GET_YIELD_FROM_ITER + a SEND loop in the bytecode, and gi_yieldfrom pointing at the current delegate; yield from is a SyntaxError inside async def.

Code / implementation expected: Optional โ€” a small delegating generator that captures a subgenerator's return value, or a recursive flatten.

  • generators
  • yield-from

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

14 min read ยท 12 sections

Run the code

Edit the code and run it here. Each console line with an expected value becomes a test.

PythonValues out, return value back, and recursive flatten
Pythonsend, throw and close are forwarded to the subgenerator
PythonThe yield from keyword versus a hand-written PEP 380 expansion

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 75 of 139 in Python

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

All Python questions
Up nextMedium

What is a deadlock in Python?

Continue