Decorator is a function that wraps another function to extend its functionality without changing the code.
Simple decorator:
1def timer(func):2 import time3 def wrapper(*args, **kwargs):4 start = time.time()5 result = func(*args, **kwargs)6 end = time.time()7 print(f"{func.__name__} took {end - start:.2f}s")8 return result9 return wrapper1011@timer12def slow_function():13 time.sleep(1)14 return "Done"1516slow_function() # "slow_function took 1.00s"
Decorator with arguments:
1def repeat(n):2 def decorator(func):3 def wrapper(*args, **kwargs):4 for _ in range(n):5 result = func(*args, **kwargs)6 return result7 return wrapper8 return decorator910@repeat(3)11def say_hello():12 print("Hello!")
Popular decorators:
@staticmethod, @classmethod.@property — getter/setter.@lru_cache — caching.@login_required (Django).