|
| 1 | +# Example 1: Timer decorator |
| 2 | +import time |
| 3 | +def timer(func): # A decorator that measures how long a function takes to run. |
| 4 | + def wrapper(*args, **kwargs): |
| 5 | + start = time.time() |
| 6 | + result = func(*args, **kwargs) |
| 7 | + end = time.time() |
| 8 | + print(f"{func.__name__} ran in {end - start} seconds") |
| 9 | + return result |
| 10 | + return wrapper |
| 11 | + |
| 12 | +@timer |
| 13 | +def example_function(n): |
| 14 | + time.sleep(n) # Simulate a slow function |
| 15 | + |
| 16 | +example_function(2) |
| 17 | + |
| 18 | + |
| 19 | +# Example 2: Simple before/after decorator |
| 20 | +def outer(func): # A decorator that prints a message before and after the function runs. |
| 21 | + def wrapper(*args, **kwargs): |
| 22 | + print('Before') |
| 23 | + func(*args, **kwargs) # Pass all arguments to the original function |
| 24 | + print('After') |
| 25 | + return wrapper |
| 26 | + |
| 27 | +@outer # This applies the outer() decorator to hello() |
| 28 | +def hello(name): |
| 29 | + print(f"Your name is {name}") |
| 30 | + |
| 31 | +hello('Ali') # Behind the scenes: hello = outer(hello) |
| 32 | + |
| 33 | + |
| 34 | +# Example 3: Logging decorator |
| 35 | +def decorator(func): # A decorator that logs the function name and all arguments. |
| 36 | + def wrapper(*args, **kwargs): |
| 37 | + args_value = ', '.join(str(arg) for arg in args) |
| 38 | + kwargs_value = ', '.join(f"{k}={v}" for k, v in kwargs.items()) |
| 39 | + print(f"Calling: {func.__name__} with args [{args_value}] and kwargs [{kwargs_value}]") |
| 40 | + func(*args, **kwargs) |
| 41 | + return wrapper |
| 42 | + |
| 43 | +@decorator |
| 44 | +def greet(name, greeting='Welcome Sir'): |
| 45 | + print(f"{name}, {greeting}") |
| 46 | + |
| 47 | +greet('Ali', greeting='How are you?') |
| 48 | + |
0 commit comments