Skip to main content

10. Decorator Use Cases

Decorators are widely used in real-world Python projects.


Logging

def log(func):
def wrapper(*args, **kwargs):
print(f"Calling {func.__name__}")
return func(*args, **kwargs)
return wrapper

Authentication

In web frameworks like Flask:

@app.route("/admin")
@login_required
def admin_dashboard():
...

Memoization

from functools import lru_cache

@lru_cache(maxsize=None)
def fib(n):
if n < 2: return n
return fib(n-1) + fib(n-2)

Practice Challenge

Write a timer decorator that measures how long a function takes to run.


Wrap-Up

  • Decorators are powerful for logging, authentication, caching, and timing.