Python Reference ยท Statements and Keywords
The yield statement
Reference for Python yield: build generator functions, pause and resume with send(), delegate with yield from, and avoid the one-pass and return pitfalls.
The yield keyword turns a function into a generator function. Calling it does not run the body. It returns a generator object, and the body runs piece by piece: each time you ask for the next value, execution continues until it reaches a yield, hands that value out, and freezes with all local variables intact.
Generators produce values lazily, one at a time, so they can describe huge or even infinite sequences while using almost no memory. They are also the simplest way to write your own iterator.
def countdown(n): while n > 0: yield n n -= 1
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Syntax
yield expression yield variable = yield expression yield from iterable
| Form | Description |
|---|---|
yield value |
Pauses the generator and gives value to the caller. |
yield |
Same, but the value produced is None. |
x = yield value |
Also receives a value: whatever the caller passes to send() becomes the result of the yield expression (None for a plain next()). |
yield from iterable |
Hands over every item of the iterable, one by one, and evaluates to the sub-generator's return value. |
Return value: calling a generator function returns a generator object. The generator's own return value ends it and puts the value in StopIteration.value.
Raises: StopIteration from next() once the generator is finished. Calling send() with a non-None value on a generator that has not started raises TypeError. A generator that is already running raises ValueError if re-entered.
Usage notes
- Lazy by design. Nothing in the body runs until the first
next()(or the first loop iteration). Argument errors inside the body therefore appear late, not at the call. - One pass only. A generator is its own iterator and cannot be rewound. Once exhausted, looping again produces nothing. Call the generator function again for a fresh one.
returnends the generator. Reaching the end of the body or runningreturnraisesStopIterationfor the consumer. Aforloop swallows it silently.- Methods on generators.
send(value)resumes with a value,throw(exc)raises an exception at the pausedyield, andclose()raisesGeneratorExitthere sofinallyblocks can clean up. yield fromreplaces afor ...: yieldloop and also forwardssend()andthrow()to the inner generator.- Generator expressions.
(n * n for n in data)is a compact one-expression generator. It uses less memory than a list comprehension but can only be consumed once. - Not a coroutine keyword. In an
async deffunction,yieldcreates an asynchronous generator; plain coroutines useawaitinstead. - A
yieldanywhere makes it a generator, even in a branch that never runs. Forgetting that is a common reason a function "returns nothing useful". - Memory. Prefer a generator when you only iterate once. Use a list when you need indexing,
len()or several passes.
Related
iter(),next(),return,asyncandawait- Iterators and generators,
for - Lessons: Generators, Iterators