I thought I understood decorators but not anymore. Do decorators only work when the function is created?
I wanted to create a series of functions that all have a required argument called ‘ticket_params’ that is a dictionary. and then decorate them with something like @param_checker(['req_param_1', 'req_param_2']) and then if ‘req_param_1’ and ‘req_param_2’ aren’t in the dictionary, raise a custom Exception subclass. Am I thinking of this all wrong?
It would be something like this in the calling code:
@param_checker(['req_param_1', 'req_param_2'])
def my_decorated_function(params):
# do stuff
params = {'req_param_1': 'Some Value'}
my_decorated_function(params)
# exception would be raised here from decorator.
A decorator is applied immediately after the
defstatement; the equivalence is:is exactly the same thing as:
So the job of
param_checkeris to return a function that takes as its argument the function to be decorated and returns yet another function which does what you require. OK so far?Edit: so, here’s one implementation…: