Python: Decorators with support for variable args and keyword arguments (kwargs)

This took a while to wrap my head around. Why the hell do people always nest their decorators like Osama Bin Laden's cave structure?

For example we have this function, decorated with the decorator "@varnish".

@varnish(max_age = 9000)
def blah(request, id):
return HttpResponse("Hi there")

It turns out that's an necessary evil because of the way arguments are passed.

def varnish(use_esi = False, max_age = 0):
def wrap(func):
def wrapper(*args, **kwargs):
response = func(*args, **kwargs)
esi(response, use_esi = use_esi, max_age = max_age)
return response

return wrapper

return wrap

The first method varnish() takes in the arguments for the decorator. This is simple enough.

The second method wrap() takes in the function being decorated and nothing else. This was the bit which was causing me grief as I was expecting more arguments.

The third method wrapper(), which I thought was unnecessary, receives the original arguments which should have been passed to the decorated function.

So by the third level of nesting you'll have yourself the actual body of the decorator. Annoying huh?

Now that you've figured it out, show em who's boss!


Copyright © Twig's Tech Tips
Theme by BloggerThemes & TopWPThemes Sponsored by iBlogtoBlog