python_cheatsheet.py

🐍 Python Deep Dive

Internals, concurrency, advanced patterns

# Internals

GIL

Mutex preventing concurrent bytecode execution. CPU-bound → use multiprocessing. I/O-bound → threading/asyncio OK.

Memory

Reference counting + generational GC (gen0, gen1, gen2). sys.getrefcount(). gc.collect() for cycles.

Object Model

Everything is an object. id(), type(), isinstance(). Mutable: list, dict, set. Immutable: int, str, tuple, frozenset.

# Concurrency Models

ModuleWhenPatternNote
asyncio I/O-bound, many connections async/await, event loop FastAPI, aiohttp
threading I/O-bound, simple parallelism Thread, Lock, Semaphore GIL limits CPU
multiprocessing CPU-bound computation Process, Pool, Queue Separate memory
concurrent.futures Simple thread/process pool ThreadPoolExecutor / ProcessPoolExecutor High-level API

# Code Patterns

Decorator with args
              def retry(attempts=3):
    def decorator(func):
        @functools.wraps(func)
        def wrapper(*args, **kwargs):
            for i in range(attempts):
                try: return func(*args, **kwargs)
                except Exception:
                    if i == attempts - 1: raise
        return wrapper
    return decorator
            
Context Manager
              @contextmanager
def timer(label):
    start = time.perf_counter()
    yield
    elapsed = time.perf_counter() - start
    print(f"{label}: {elapsed:.3f}s")
            
Generator Pipeline
              def read_lines(path):
    with open(path) as f:
        yield from f

def filter_errors(lines):
    yield from (l for l in lines if "ERROR" in l)

# Lazy: processes line by line
errors = filter_errors(read_lines("app.log"))
            
Async Pattern
              async def fetch_all(urls):
    async with aiohttp.ClientSession() as s:
        tasks = [s.get(u) for u in urls]
        results = await asyncio.gather(*tasks)
        return [await r.json() for r in results]
            

# Essential Dunder Methods

__init__ Constructor
__repr__ Dev-friendly string
__str__ User-friendly string
__eq__ / __hash__ Equality + hashing
__len__ len() support
__getitem__ obj[key] access
__iter__ / __next__ Iteration protocol
__enter__ / __exit__ Context manager
__call__ Make instance callable
__slots__ Memory optimization

# Modern Type Hints

x: int = 5 Basic annotation
list[str] Generic (3.9+)
str | None Union (3.10+)
TypeVar('T') Generic type variable
Protocol Structural subtyping
@dataclass Auto __init__, __repr__, __eq__