Concepts 🚀 Project 🧮 Labs
📚 Learn / Python / Generators (yield)

Generators (yield)

Functions that produce a stream of values lazily. Memory-efficient for big data.

Code example

def fib():
    a, b = 0, 1
    while True:
        yield a
        a, b = b, a + b

gen = fib()
print([next(gen) for _ in range(10)])  # [0,1,1,2,3,5,8,13,21,34]

How it works

A generator function uses `yield` instead of `return`. Each `yield` pauses the function and emits a value; calling `next()` resumes it. Generators are lazy — they only compute the next value when asked. This is how Python streams huge files line-by-line without loading them all into memory. FastAPI supports streaming responses via `StreamingResponse` which takes an async generator.

🔍 Where this is used in OpenBenchML Used implicitly in dict comprehensions, range(), and file iteration throughout the codebase.