209 lines
5.8 KiB
Python
209 lines
5.8 KiB
Python
"""
|
|
Python Decorators Practice
|
|
============================
|
|
Concepts covered:
|
|
1. Basic decorators — wrapping functions with extra behavior
|
|
2. Decorators with *args, **kwargs — flexible argument passing
|
|
3. Decorators with parameters — triple-nested pattern
|
|
4. Practical use cases: logging, validation, retry logic
|
|
"""
|
|
|
|
|
|
# =============================================================================
|
|
# 1. BASIC DECORATOR — @log_call
|
|
# Prints function name, arguments, and return value
|
|
# =============================================================================
|
|
|
|
def log_call(func):
|
|
"""Logs function calls with arguments and return values."""
|
|
def wrapper(*args, **kwargs):
|
|
print(f"Calling {func.__name__}(args={args}, kwargs={kwargs})")
|
|
result = func(*args, **kwargs)
|
|
print(f"{func.__name__} returned: {result}")
|
|
return result
|
|
return wrapper
|
|
|
|
|
|
# =============================================================================
|
|
# 2. VALIDATION DECORATOR — @validate_positive
|
|
# Ensures all numeric arguments are positive
|
|
# =============================================================================
|
|
|
|
def validate_positive(func):
|
|
"""Raises ValueError if any numeric argument is negative."""
|
|
def wrapper(*args, **kwargs):
|
|
for arg in args:
|
|
if isinstance(arg, (int, float)) and arg < 0:
|
|
raise ValueError(f"All arguments must be positive, got {arg}")
|
|
return func(*args, **kwargs)
|
|
return wrapper
|
|
|
|
|
|
# =============================================================================
|
|
# 3. PARAMETERIZED DECORATOR — @retry(retries=n)
|
|
# Retries a function up to n times if it raises an exception
|
|
# Note: decorator with arguments = three nested layers
|
|
# - retry(retries=3) → returns decorator
|
|
# - decorator(func) → returns wrapper
|
|
# - wrapper(*args) → does the work
|
|
# =============================================================================
|
|
|
|
def retry(retries=3):
|
|
"""Retries a function up to `retries` times on failure."""
|
|
def decorator(func):
|
|
def wrapper(*args, **kwargs):
|
|
for i in range(retries + 1):
|
|
try:
|
|
return func(*args, **kwargs)
|
|
except Exception as e:
|
|
print(f" Attempt {i + 1} failed: {e}")
|
|
if i == retries:
|
|
raise
|
|
return wrapper
|
|
return decorator
|
|
|
|
|
|
# =============================================================================
|
|
# 4. TESTS
|
|
# =============================================================================
|
|
|
|
if __name__ == "__main__":
|
|
|
|
# --- @log_call ---
|
|
print("=== @log_call ===")
|
|
|
|
@log_call
|
|
def add(a, b):
|
|
return a + b
|
|
|
|
add(3, 5)
|
|
|
|
print()
|
|
|
|
@log_call
|
|
def greet(name, n=2):
|
|
for _ in range(n):
|
|
print(f" hello {name}")
|
|
|
|
greet("Alice", n=3)
|
|
|
|
# --- @validate_positive ---
|
|
print("\n=== @validate_positive ===")
|
|
|
|
@validate_positive
|
|
def deposit(amount):
|
|
return f"Deposited {amount}"
|
|
|
|
print(deposit(100))
|
|
|
|
try:
|
|
deposit(-50)
|
|
except ValueError as e:
|
|
print(f"Caught: {e}")
|
|
|
|
# --- @retry ---
|
|
print("\n=== @retry ===")
|
|
|
|
@retry(retries=4)
|
|
def risky():
|
|
import random
|
|
if random.random() < 0.7:
|
|
raise ConnectionError("Server unavailable!")
|
|
return "Success!"
|
|
|
|
try:
|
|
result = risky()
|
|
print(f"Result: {result}")
|
|
except ConnectionError:
|
|
print("All retries exhausted")
|
|
|
|
|
|
# =============================================================================
|
|
# 5. FUTURE EXERCISE — Come back in 2-3 days and try these!
|
|
# Do NOT peek at your code above. Try from scratch.
|
|
# =============================================================================
|
|
|
|
"""
|
|
EXERCISE 1: @timer
|
|
------------------
|
|
Create a decorator that measures how long a function takes to run.
|
|
Hint: use time.time() before and after.
|
|
|
|
@timer
|
|
def slow_add(a, b):
|
|
import time
|
|
time.sleep(1)
|
|
return a + b
|
|
|
|
slow_add(3, 5)
|
|
# slow_add took 1.00 seconds
|
|
# 8
|
|
|
|
|
|
EXERCISE 2: @require_type(expected_type)
|
|
-----------------------------------------
|
|
Create a parameterized decorator that checks the RETURN value
|
|
is the expected type. Raise TypeError if not.
|
|
|
|
@require_type(int)
|
|
def add(a, b):
|
|
return a + b
|
|
|
|
add(3, 5) # 8 — works fine
|
|
|
|
@require_type(str)
|
|
def add(a, b):
|
|
return a + b
|
|
|
|
add(3, 5) # raises TypeError: Expected str, got int
|
|
|
|
|
|
EXERCISE 3: @count_calls
|
|
-------------------------
|
|
Create a decorator that tracks how many times a function
|
|
has been called. Store the count as an attribute on the wrapper.
|
|
|
|
@count_calls
|
|
def greet(name):
|
|
print(f"hello {name}")
|
|
|
|
greet("Alice")
|
|
greet("Bob")
|
|
greet("Charlie")
|
|
print(greet.call_count) # 3
|
|
|
|
|
|
EXERCISE 4: Combine decorators
|
|
-------------------------------
|
|
Stack multiple decorators on one function. What order do they run?
|
|
|
|
@log_call
|
|
@validate_positive
|
|
@timer
|
|
def deposit(amount):
|
|
return f"Deposited {amount}"
|
|
|
|
deposit(100)
|
|
# What prints first? log_call, validate_positive, or timer?
|
|
# Try it and figure out the order!
|
|
|
|
|
|
EXERCISE 5: @cache_result
|
|
--------------------------
|
|
Create a decorator that caches (remembers) return values.
|
|
If the function is called with the same arguments again,
|
|
return the cached result instead of running the function.
|
|
|
|
@cache_result
|
|
def slow_multiply(a, b):
|
|
import time
|
|
time.sleep(2)
|
|
return a * b
|
|
|
|
slow_multiply(3, 4) # takes 2 seconds, returns 12
|
|
slow_multiply(3, 4) # instant! returns 12 from cache
|
|
slow_multiply(5, 6) # takes 2 seconds, returns 30 (new args)
|
|
|
|
Hint: use a dictionary inside the decorator to store results.
|
|
The key can be (args, tuple(kwargs.items()))
|
|
""" |