Decorators
A decorator is a function that takes another function and extends its behavior without explicitly modifying it. Decorators are applied using the `@` syntax. They are used for logging, timing, access control, and more.
Simple Decorator
Define a wrapper function that adds behavior before/after the original.
def timer(func):
import time
def wrapper(*args, **kwargs):
start = time.time()
result = func(*args, **kwargs)
end = time.time()
print(f"{func.__name__} took {end - start:.4f}s")
return result
return wrapper
@timer
def slow_function():
time.sleep(1)
return "Done"
slow_function()
Decorators with Arguments
To pass arguments to the decorator, wrap another layer.
def repeat(times):
def decorator(func):
def wrapper(*args, **kwargs):
result = None
for _ in range(times):
result = func(*args, **kwargs)
return result
return wrapper
return decorator
@repeat(3)
def greet(name):
print(f"Hello {name}!")
greet("Alice")
Two Minute Drill
- Decorators are functions that wrap other functions.
- They use the `@` syntax and can modify behavior.
- Inner wrapper function receives `*args, **kwargs`.
- Use `functools.wraps` to preserve metadata.
- Common uses: logging, timing, authentication.
Need more clarification?
Drop us an email at career@quipoinfotech.com
