added decorators with exercises for later
This commit is contained in:
1 parent
8f4f08b8a6
commit
6202f69e1c
3 files changed
+308
-9
No files matched your search
@@ -1,14 +1,16 @@
|
||||
## TODOs -
|
||||
### first
|
||||
|
||||
Decorators
|
||||
Error handling -- try/except/else/finally, chaining exceptions
|
||||
Abstract base classes -- force subclasses to implement specific methods using abc module
|
||||
- Decorators - done, revisit exercises in 2-3 days
|
||||
- Error handling - done (try/except/else/finally, custom exceptions, chaining)
|
||||
- Unpacking — *args, **kwargs, tuple/dict unpacking (already used)
|
||||
- Abstract base classes — force subclasses to implement methods using abc module
|
||||
|
||||
|
||||
### then (rolling)
|
||||
Context managers
|
||||
@dataclass
|
||||
Walrus operator
|
||||
Lambda & functional tools -- map, filter, functools, closures
|
||||
Collections module
|
||||
Unpacking -- *args, **kwargs, tuple/dict unpacking
|
||||
- Iterators & generators deep dive
|
||||
- Context managers
|
||||
- @dataclass
|
||||
- Lambda & functional tools — map, filter, functools, closures
|
||||
- Collections module — defaultdict, Counter, namedtuple, deque
|
||||
- Walrus operator
|
||||
@@ -0,0 +1,88 @@
|
||||
# Create three decorators:
|
||||
|
||||
# @log_call — prints the function name and arguments before it runs, and the result after
|
||||
# @validate_positive — checks that all number arguments are positive, raises ValueError if not
|
||||
# @retry(times=3) — retries a function up to 3 times if it raises an exception (this one is harder — a decorator that takes arguments)
|
||||
|
||||
def log_call(func):
|
||||
def wrapper(*args, **kwargs):
|
||||
print(f"function name: {func.__name__} and the (arguments are {args}, {kwargs})")
|
||||
return func(*args, **kwargs)
|
||||
return wrapper
|
||||
|
||||
@log_call
|
||||
def greet(name: str, n: int = 2):
|
||||
for _ in range(n):
|
||||
print(f"hello {name}")
|
||||
|
||||
# greet("aman")
|
||||
|
||||
def validate_positive(func):
|
||||
def wrapper(*args, **kwargs):
|
||||
for arg in args:
|
||||
if isinstance(arg, (int, float)):
|
||||
if arg > 0:
|
||||
return func(*args, **kwargs)
|
||||
else:
|
||||
raise ValueError("value must be positive")
|
||||
else:
|
||||
raise TypeError("the argument provided must be an integer")
|
||||
|
||||
return wrapper
|
||||
|
||||
@validate_positive
|
||||
def number(inp):
|
||||
print(inp)
|
||||
|
||||
# number(-1)
|
||||
|
||||
def retry(retries=3):
|
||||
def decorator(func): # layered? note! i also had issue that the retry decorator called the function incorrectly inside the except block and didn’t return result
|
||||
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 as - {e}")
|
||||
if i == retries:
|
||||
raise
|
||||
return wrapper
|
||||
return decorator
|
||||
|
||||
@retry(retries=3)
|
||||
def greet(name: str):
|
||||
if not isinstance(name, str):
|
||||
raise TypeError("must be a string")
|
||||
else:
|
||||
print(f"hello {name}")
|
||||
|
||||
#greet("aman")
|
||||
|
||||
# --- test
|
||||
|
||||
@log_call
|
||||
def add(a, b):
|
||||
return a + b
|
||||
|
||||
#print(add(3, 5))
|
||||
# Calling add(3, 5)
|
||||
# add returned: 8
|
||||
|
||||
@validate_positive
|
||||
def deposit(amount):
|
||||
return f"Deposited {amount}"
|
||||
|
||||
#print(deposit(100)) # "Deposited 100"
|
||||
#print(deposit(-50)) # raises ValueError: All arguments must be positive
|
||||
|
||||
@retry(retries=4)
|
||||
def risky():
|
||||
import random
|
||||
if random.random() < 0.7:
|
||||
raise ConnectionError("Failed!")
|
||||
return "Success!"
|
||||
|
||||
print(risky())
|
||||
# Attempt 1 failed: Failed!
|
||||
# Attempt 2 failed: Failed!
|
||||
# Success!
|
||||
@@ -0,0 +1,209 @@
|
||||
"""
|
||||
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()))
|
||||
"""
|
||||
Reference in new issue
Block a user