Let’s grasp the concept of decorator in Python PEP 318 with short snippets.
def f1():
print("Called f1.")
def f2(f):
f()
f2(f1) # Called f1
f2
takes a function (object) as a parameter.
def f1(fun):
def wrap():
print("Start wrap")
fun()
print("End wrap")
return wrap
def f():
print("In function f")
f1(f)()
### python test.py
#Start wrap
#In function f
#End wrap
def f1(fun):
def wrap():
print("Start wrap")
fun()
print("End wrap")
return wrap
@f1
def f():
print("In function f")
f()
### python test.py
#Start wrap
#In function f
#End wrap
A decorator is like “pass decorated function into decorating function.”
def f1(fun):
def wrap(*args, **kwargs):
print("Start wrap")
fun(*args, **kwargs)
print("End wrap")
return wrap
@f1
def f(p1):
print(p1)
f("Hello,")
### python test.py
#Start wrap
#Hello,
#End wrap