Use Decorator in Python

Page content

Let’s grasp the concept of decorator in Python PEP 318 with short snippets.

Step 1: Function as a parameter

def f1():
    print("Called f1.")

def f2(f):
    f()

f2(f1) # Called f1

f2 takes a function (object) as a parameter.

Step 2: Wapping function

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

Step 3: Use decorator

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.”

Step 4: Decorator with parameters

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

Reference

https://www.youtube.com/watch?v=r7Dtus7N4pI