I have to solve the follwing problem which doesn't allow me to change the add()
function, i.e. it needs to work for all 'untouched' functions that are decorated by the @password("my_pswd")
, meaning I cannot change the add() function. I am not familiar with passing such an argument to a function and transfer it to the decorator. As for how i tried solving this issue, the decorator (which is the only thing I may change) is included in the original question.
Decorator:
Write a parameterized decorator named "password" that takes a password as a parameter. The decorated function should take this password as a parameter and return its result. If the password is not provided, it should raise a ValueError exception. The decorator should work with any function regardless of its named and positional parameters.
Example:
@password("secret")
def add(a, b): #constant function, DO NOT MODIFY
return a+b
add("h", 1, 2) #ValueError
add(1, 2) #ValueError
add("secret", 1, 2) #3
def password(pswd):
#code here
I've tried using a named decorator like this :
def password(pswd):
def decorator(f):
def wrapper(*args, **kwargs):
if not f(*args) is pswd:
raise ValueError("Invalid password")
return f(*args, **kwargs)
return wrapper
return decorator
But, I get
line 28, in <module>
add("h", 1, 2)
File "//", line 16, in wrapper
if not f(*args) is pswd:
TypeError: add() takes 2 positional arguments but 3 were given
Any idea how to solve this? To be clear, I can't modify the add function, meaning I cannot give it a third positional argument.
The wrapper function should just check if the first argument is the password. And when the wrapper calls the original function it has to leave out the password argument. So the function signature should be
def wrapper(password_given, *args, **kwargs):
This allows it to pass only *args
to the original function, which leaves out the first argument.
Then it should use if pswd != pass:
to check the password -- you shouldn't use is
to compare strings.
def password(pswd):
def decorator(f):
def wrapper(password_given, *args, **kwargs):
if password_given != pswd:
raise ValueError("Invalid password")
return f(*args, **kwargs)
return wrapper
return decorator