I'm trying to understand Python function decorators, but so far I don't see any case where a function decorator can do something I couldn't do using first class functions.
As an example, the logger decorator
is often given as a simple example of a useful function decorator:
def logger(f):
def new_f():
print("Calling %s" % f.__name__)
return f()
return new_f
This decorator is then classically used together with a function we want to log, as so:
@logger
def fun1():
[do something]
However, for the same result we could just define func1 and wrap it with logger:
def fun2():
[do something]
def logged_fun2():
return logger(fun2)()
Calling logged_fun2
is analogue to calling fun1
. In addition, when we wrap fun2
with logger
we can still call the original fun2
without logging if we wish to.
Are there things I can do with decorators that I can't do using first class functions? Or is it better to look at decorators as a form of syntactic sugar for wrapping functions?
Decorator syntax:
@deco
def f(...):
...
is defined as exactly equivalent to the following syntax:
def f(...):
...
f = deco(f)
So no, there's nothing decorators can do that first-class functions can't. Decorators are first-class functions.