Python & FastAPI•Part 2: Python Core Language, Internals & Runtime (6 - 25)
Generators and the `yield` keyword:
In Simple Words:
A generator produces values on demand one at a time using yield instead of returning an entire collection at once, achieving $O(1)$ memory consumption.
python
def read_large_file(file_path):
with open(file_path, 'r') as f:
for line in f:
yield line.strip() # Memory-efficient lazy evaluation
# Reads gigabytes of logs without running out of RAM:
for log_entry in read_large_file("huge_log.txt"):
if "ERROR" in log_entry:
print(log_entry)