Decorator
Decorators are a powerful Python feature that allows modifying or enhancing functions and classes without changing their source code. They are widely used for logging, caching, access control, and more. The guide walks through Function Decorators, Preserving Metadata, Decorators with Arguments, Class Decorators, Common Patterns. A decorator is a callable that accepts a function and returns a replacement. The `@decorator` syntax is syntactic sugar for `func = decorator(func)`. The wrapper function typically uses `*args, **kwargs` to pass through all arguments. Use `functools.wraps(func)` on the wrapper to copy `__name__`, `__doc__`, `__module__`, and other metadata from the original function. Without it, introspection tools like `help()` show the wrapper's metadata instead of the original function's. A decorator that takes arguments needs three levels: the outer function receives the decorator argument, the middle function receives the decorated function, and the innermost wrapper handles the call. This pattern enables configurable decorators like `@retry(times=3)`. The guide is organized into 5 sections that build on each other, each pairing a prose explanation with runnable code.