Advanced Python: Decorators, Generators, and Metaclasses
To build frameworks like FastAPI or Django, you must master the dynamic nature of Python.
Decorators: Cross-Cutting Concerns
Decorators allow you to wrap functions with logic (logging, timing, auth) without modifying their source code.
python codeimport functools import time def timer(func): @functools.wraps(func) def wrapper(*args, **kwargs): start = time.perf_counter() result = func(*args, **kwargs) end = time.perf_counter() print(f"Finished {func.__name__} in {end-start:.4f}s") return result return wrapper @timer def heavy_computation(): time.sleep(1)
Generators: Memory-Efficient Iteration
Generators use "lazy evaluation". They yield items one by one instead of loading a whole list into memory. Essential for processing large logs or datasets.
python codedef read_large_file(file_path): with open(file_path) as f: for line in f: yield line.strip() # Only one line is in memory at a time for line in read_large_file('huge_log.txt'): process(line)
Metaclasses: The Class Factory
Metaclasses are "classes that create classes". They are used to enforce constraints on sub-classes or auto-register components.
python codeclass Singleton(type): _instances = {} def __call__(cls, *args, **kwargs): if cls not in cls._instances: cls._instances[cls] = super().__call__(*args, **kwargs) return cls._instances[cls] class DatabaseConnection(metaclass=Singleton): pass
Dunder Methods
Control how your objects behave with operators like +, [], or () using methods like __add__, __getitem__, and __call__.