PyPython

Python: Advanced – code examples

Contents

Generator

Advanced#yield#generator#iterator
Use case: Process large amounts of data piece by piece without holding everything in memory.
def zaehle_bis(n):
    i = 1
    while i <= n:
        yield i
        i += 1

for x in zaehle_bis(3):
    print(x)
print(sum(zaehle_bis(100)))

yield pauses the function and delivers the next value.

Decorator for timing

Advanced#decorator#wraps
Use case: Add runtime measurement, logging or caching uniformly to many functions.
import time, functools

def zeitmessung(fn):
    @functools.wraps(fn)
    def wrapper(*a, **kw):
        t = time.perf_counter()
        res = fn(*a, **kw)
        print(f"{fn.__name__} took {time.perf_counter() - t:.4f}s")
        return res
    return wrapper

@zeitmessung
def rechne():
    return sum(range(1_000_000))

rechne()

functools.wraps preserves the name and docstring of the original function.

Custom context manager

Advanced#with#contextmanager
Use case: Reliably open and close resources (timers, connections, locks).
from contextlib import contextmanager

@contextmanager
def abschnitt(titel):
    print(f"-- Start: {titel}")
    try:
        yield
    finally:
        print(f"-- End: {titel}")

with abschnitt("Calculation"):
    print(2 + 2)

Everything before yield is setup, everything after is cleanup – even on exceptions.

Running tasks in parallel with ThreadPool

Advanced#thread#parallel#concurrent
Use case: Handle many slow I/O tasks (downloads, API calls) at the same time.
from concurrent.futures import ThreadPoolExecutor
import time

def aufgabe(n):
    time.sleep(0.5)
    return n * n

with ThreadPoolExecutor(max_workers=4) as pool:
    ergebnisse = list(pool.map(aufgabe, range(8)))
print(ergebnisse)

Eight tasks of 0.5 s each finish in about 1 s with four threads.