Suppose you have a lot of functions f1
, f2
, f3
, ... and you want a regular way to make the same change to all of them to do the same extra work.
That's what you're missing and it's why decorators are useful. That is to say, functions that take a function and return a modified version of it.
The decorator @
syntax is "just" for convenience. It lets you decorate the function as it is defined:
@decorated
def foo():
# several lines
instead of somewhere after the function definition:
def foo():
# several lines
foo = decorated(foo)
In fact of course the latter code is pretty horrible, since it means that by looking at the first definition of foo
in the source, you don't see the same foo
that users will call. So without the syntax, decorators wouldn't be so valuable because you'd pretty much always end up using different names for the decorated and undecorated functions.