So I’m still kind of new to Python decorators – I’ve used them before, but I’ve never made my own. I’m reading this tutorial (that particular paragraph) and I don’t seem to understand why do we need three levels of functions? Why can’t we do something like this:
def decorator(func, *args, **kwargs):
return func(*args,**kwargs)
Thanks 🙂
Well, what would happen if you called that decorator on a function?
This code would immediately call foo, which we don’t want. Decorators are called and their return value replaces the function. It’s the same as saying
So if we have a decorator that calls foo, we probably want to have a function that returns a function that calls foo — that function that it returns will replace foo.
Now, if we want to pass options to the decorator, we can’t exactly pass them ins ide-by-side with the function like in your example. There’s no syntax for it. So we define a function that returns a parameterized decorator. The decorator it returns will be a closure.
so we can do
And Python offers the convenience syntax where you inline the function call:
And all this is syntax sugar for the non-decorator syntax of