Decorators

Modifying function behavior

Interview Relevant: Very important for interviews

Decorators

Functions that modify other functions.

Code Examples

Function decorators.

python
1from functools import wraps
2
3# Basic decorator
4def timer(func):
5    @wraps(func)  # Preserve metadata
6    def wrapper(*args, **kwargs):
7        import time
8        start = time.time()
9        result = func(*args, **kwargs)
10        print(f"Took {time.time() - start:.2f}s")
11        return result
12    return wrapper
13
14@timer
15def slow_function():
16    import time
17    time.sleep(1)
18
19# Decorator with arguments
20def repeat(n):
21    def decorator(func):
22        @wraps(func)
23        def wrapper(*args, **kwargs):
24            for _ in range(n):
25                result = func(*args, **kwargs)
26            return result
27        return wrapper
28    return decorator
29
30@repeat(3)
31def say_hello():
32    print("Hello!")
33
34# Multiple decorators (bottom-up)
35@decorator1
36@decorator2
37def func():
38    pass
39# Same as: decorator1(decorator2(func))

AI Tutor

Ask about the topic

Sign in Required

Please sign in to use the AI tutor

Sign In