forked from yidao620c/python3-cookbook
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdeco.py
More file actions
45 lines (35 loc) · 1.04 KB
/
deco.py
File metadata and controls
45 lines (35 loc) · 1.04 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# encoding: utf-8
"""
Topic: sample
Desc : 利用闭包演示带参的装饰器
"""
from time import time
from functools import wraps
__author__ = 'Xiong Neng'
def logged(when):
def log(f, *args, **kargs):
print('Called: function: %s, args: %r, kargs: %r' % (f, args, kargs))
def pre_decorator(func):
@wraps(func)
def func_wrapper(*args, **kargs):
log(func, *args, **kargs)
return func(*args, **kargs)
return func_wrapper
def post_decorator(func):
@wraps(func)
def func_wrapper(*args, **kwargs):
now = time()
try:
return func(*args, **kwargs)
finally:
log(func, *args, **kwargs)
print('time delta: %s' % (time() - now))
return func_wrapper
try:
return {'pre': pre_decorator, 'post': post_decorator}[when]
except KeyError as e:
raise ValueError(e, 'must be "pre" or "post"')
@logged('post')
def hello(name):
print('Hello', name)
hello('world')