The Python yield keyword
What’s the Python yield keyword for? See
notes / FastAPI with Chroma
for a real world use case.
W3Schools yield tutorial
The yield keyword turns a function into a function generator. The function generator returns
an iterator.
The code in the function is not executed when it is first called, but is divided into steps, one step for each yield. Each step is executed when iterated upon. The function’s return values will be a list of values, one value for each yield.1
In [1]: def my_func():
...: yield "This"
...: yield "is"
...: yield "a"
...: yield "test"
...:
In [2]: x = my_func()
In [4]: for i in x:
...: print(i)
...:
This
is
a
test
Python 3 documentation — yield expressions
yield expressions are used to define a generator function or an asynchronous generator function.
They can only be used in the body of a function definition.
Yield expressions in async functions
Using a yield expression in an async def function’s body causes that coroutine function to be an
asynchronous generator function. Python docs:
https://docs.python.org/3/reference/expressions.html#asynchronous-generator-functions
.
References
Python 3.14.2 Documentation. “6. Expressions — Yield expressions.” Last updated: January 10, 2026. https://docs.python.org/3/reference/expressions.html#yield-expressions .
-
W3Schools, “Python yield keyword,” https://www.w3schools.com/python/ref_keyword_yield.asp . ↩︎