Files

88 lines
2.4 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# 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!