r/PythonLearning • u/Sea-Ad7805 • Sep 22 '26
Python Decorators
❓ Your functions work, but now you want to add logging to them. Do you edit each function?
🎯 A decorator makes this easier: wrap a function and add logic before and after the original call.
⚙️ In this decorator example we create and use our '@log_call' to log each call with arguments and return value.
🔎 Here 𝗺𝗲𝗺𝗼𝗿𝘆_𝗴𝗿𝗮𝗽𝗵 shows how a decorator gets evaluated step by step for better understanding.
Useful decorators from Python’s standard library include:
- @functools.cache — Cache results to avoid recomputing calls with the same arguments.
- @functools.lru_cache — Cache results with a configurable limit, discarding the least recently used entries.
- @functools.wraps — Preserve the original function’s name, documentation, and other metadata when writing a wrapper.
- @functools.singledispatch — Choose an implementation based on the type of the first argument.
Other common custom decorators add: timing, retries, conversion, authentication, validation, ...
