Extend function behaviour with reusable Python decorators
Quick Answer
A decorator is a function that takes another function and returns a wrapper — annotate with `@decorator_name` to apply it. Always use `@functools.wraps(func)` to preserve the wrapped function's metadata.
1import functools
2import time
3
4# 1. Timing decorator
5def timer(func):
6 @functools.wraps(func)
7 def wrapper(*args, **kwargs):
8 start = time.perf_counter()
9 result = func(*args, **kwargs)
10 end = time.perf_counter()
11 print(f'{func.__name__} took {end - start:.4f}s')
12 return result
13 return wrapper
14
15# 2. Retry decorator
16def retry(times=3, exceptions=(Exception,)):
17 def decorator(func):
18 @functools.wraps(func)
19 def wrapper(*args, **kwargs):
20 for attempt in range(1, times + 1):
21 try:
22 return func(*args, **kwargs)
23 except exceptions as e:
24 if attempt == times:
25 raise
26 print(f'Attempt {attempt} failed: {e}. Retrying...')
27 return wrapper
28 return decorator
29
30# Usage
31@timer
32def slow_function():
33 time.sleep(0.5)
34 return 'done'
35
36@retry(times=3, exceptions=(ConnectionError,))
37def fetch_data(url: str):
38 # your HTTP request here
39 passA Python decorator is a higher-order function that wraps another function to extend its behaviour without modifying its source code. Decorators are used everywhere in Python — from Flask route registration to Django permissions. Understanding how to write your own decorators unlocks a powerful pattern for cross-cutting concerns like logging, timing, and retrying.
Yes. Decorators are applied bottom-up: `@a @b def f()` is equivalent to `f = a(b(f))`. The outermost decorator wraps the already-wrapped function.
This free python code snippet for decorators is production-ready and copy-paste friendly. Whether you are building a web app, API, or frontend interface, this intermediate-level example will help you implement decorators quickly and correctly.
All snippets in the Snippetly library follow python best practices and are tested for real-world use. You can adapt this code to work with React, Vue, Node.js, or any project that uses python.
Organise your team's code snippets with Snippetly. Share knowledge and boost productivity across your organisation.