Definição
Produzem itens sob demanda, sem carregar tudo na memória. Ideais para ficheiros e APIs paginadas.
Exemplos
1. Ler um ficheiro grande linha a linha
def read_lines(path):
with open(path) as f:
for line in f:
yield line.rstrip("\n")2. API paginada
def fetch_all(url):
page = 1
while True:
data = requests.get(url, params={"page": page}, timeout=30).json()
if not data["items"]:
return
yield from data["items"]
page += 13. Expressão geradora
total = sum(r["amount"] for r in read_rows(path))