I've 2 questions. I've created a decorator which checks whether the dictionary has a key or not? Here it is.
def check_has_key(func):
def inner(x,y): # inner function needs parameters
dictionary = {"add" : "true", "subtract" : "true"}
if dictionary.has_key("add") :
return func(x,y)
return "Add not allowed"
return inner # return the inner function (don't call it)
@check_has_key
def add(x,y):
return x+y
print add(1,2)
1) Can I pass the key as an argument to the wrapper and then check whether it exists or not? For eg :- like I just pass the key as @check_has_ket("subtact")
.
2) Can I use a decorator inside the function? as in if I need to check whether the dictionary has the key or not, deep down the function?
EDIT
I got the answer for the 1st question.
def abc(a):
def check_has_key(func):
def inner(x,y): # inner function needs parameters
dictionary = {"add" : "true", "subtract" : "true"}
if dictionary.has_key(a) :
return func(x,y)
return "Add not allowed"
return inner # return the inner function (don't call it)
return check_has_key
@abc("subtract")
def add(x,y):
return x+y
print add(1,2)
But my doubt still remains can I use the decorator deep down the function? Meaning if I need to check whether a key exist in the dictionary or not deep down the function , can I use the decorator for this purpose or will I have to use the if condition only?