PyPython
AdvancedLesson 11 of 12

Generators, Iterators & Decorators – Python

Memory-efficient data streams and functions that extend functions.

A generator produces values on demand with yield – ideal for large or infinite sequences.

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

from itertools import islice
print(list(islice(fibonacci(), 10)))   # [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]

quadratsumme = sum(x*x for x in range(1_000_000))  # generator expression
print(quadratsumme)

A decorator "wraps" a function, e.g. for timing, logging or caching:

import time, functools

def zeitmessung(fn):
    @functools.wraps(fn)
    def wrapper(*args, **kwargs):
        start = time.perf_counter()
        ergebnis = fn(*args, **kwargs)
        print(f"{fn.__name__}: {time.perf_counter() - start:.4f}s")
        return ergebnis
    return wrapper

@zeitmessung
def langsam():
    return sum(range(2_000_000))

langsam()