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
@@ -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!
|
||||
Reference in new issue
Block a user