Python decorator pattern

Decorators

What is decorators?

It accepts the functions and add the decorator-like function into the original functions to achieve certain functions.

Examples:

Apply the function of measuring execution time on each function.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# -*- coding: utf-8 -*-
import time

# --exe_time
def exe_time(func):
def new_func(*args, **args2):
t0 = time.time()
print "@%s, {%s} start" % (time.strftime("%X", time.localtime()), func.__name__)
back = func(*args, **args2)
print "@%s, {%s} end" % (time.strftime("%X", time.localtime()), func.__name__)
print "@%.3fs taken for {%s}" % (time.time() - t0, func.__name__)
return back
return new_func
# --end of exe_time

@exe_time
def foo():
for i in xrange(10000000):
pass

if __name__ == "__main__":
foo()

See more details in the blog of liaoxuefeng.

Reference

  1. liaoxuefeng: Decorators https://www.liaoxuefeng.com/wiki/1016959663602400/1017451662295584
  2. Python: 使用装饰器“@”取得函数执行时间 https://oldj.net/blog/2010/05/22/decorator-get-execution-time