Glossary

Yield

The yield keyword is what turns an ordinary function into a generator function. When Python encounters yield in a function body, it compiles the function as a generator. Calling the function returns a generator object without executing any of the body. Each call to next() on the generator runs the body until it hits a yield expression, at which point the yielded value is returned to the caller and the generator's state (local variables, instruction pointer) is frozen until the next next() call.

yield can also receive values via the .send(value) method, making generators bidirectional. In this mode, the yield expression evaluates to the sent value inside the generator. This feature was the foundation of early Python coroutine implementations, though modern async/await syntax has largely replaced it for concurrent programming.

yield from (Python 3.3+, PEP 380) delegates iteration to a sub-generator or any iterable, forwarding next() calls and send() values through transparently. This eliminates the need for manual for item in sub: yield item loops and enables clean recursive generators. yield from also properly propagates the sub-generator's return value and exceptions.

Related terms: Generator, Iterator, Coroutine

Discussed in:

This site is currently in Beta. Please email Chris Paton (cpaton@gmail.com) with any suggestions, questions or comments.