Using Python Decorators
Posted by joseph on 11 Jul 2021 in Python
A python decorator allows you to remove repeated code by passing function into another function which extends it.
An Example
Here is an example of a decorator:def printer(func):
def inner(*s):
print(*s)
return func(*s)
return inner
@printer
def add(a, b):
return a + b
if __name__ == "__main__":
print(add(1, 2))
Here is what it would look like without it:
def printer(func):
def inner(*s):
print(*s)
return func(*s)
return inner
def add(a, b):
return a + b
add = printer(add)
if __name__ == "__main__":
print(add(1, 2))
Practical applications
Measuring the time a function takes to run is one of many uses for a decorator, here is how it's done:import time
def measure_time(func):
def wrapper(*arg):
t = time.time()
res = func(*arg)
print("Function took " + str(time.time()-t) + " seconds to run")
return res
return wrapper
@measure_time
def myFunction(n):
time.sleep(n)
if __name__ == "__main__":
myFunction(2)
Another use is in exposing a function to something, here is an example from flask:
from flask import Flask
app = Flask(__name__, instance_relative_config=True)
# a simple page that says hello
@app.route('/hello')
def hello():
return 'Hello, World!'
Decorator Factories
A decorator factory is a function that takes arguments and returns an augmented decorator with it, here is an example:def printfunc(s):
def wrapper(func):
def inner(*arg):
o = func(*arg)
print(s, o)
return o
return inner
return wrapper
@printfunc("add:")
def add(a, b):
return a + b
if __name__ == "__main__":
add(1, 2)