-
Notifications
You must be signed in to change notification settings - Fork 49
/
decorator_tutorial.py
112 lines (78 loc) · 1.74 KB
/
decorator_tutorial.py
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
import time
from functools import wraps
# tutorial decorator with argument
def decorator(func):
@wraps(func)
def wrapped(*args, **kwargs):
func(*args, **kwargs)
return wrapped
def bold(func):
@wraps(func)
def wrapper():
print("<b> level one")
func()
print("</b>")
return wrapper
def italic(func):
@wraps(func)
def wrapper():
print("<i> level two")
func()
print("</i>")
return wrapper
@bold
@italic
def sandwich(data="my sandwich"):
print(data)
@italic
@bold
def sandwich_worse(data="my sandwich worse"):
print(data)
def elapsed_time(func):
@wraps(func)
def wrapper(*args, **kwargs):
start_time = time.time()
res = func(*args, **kwargs)
end_time = time.time() - start_time
print(func.__name__, end_time)
return res
return wrapper
@elapsed_time
def elapsed_time_tutorial():
time.sleep(2)
# function log
def func_log(func):
@wraps(func)
def wrapped():
print('call', func.__name__)
func()
print('end', func.__name__)
return wrapped
@func_log
def hello_log():
print('hello')
# top function exception
def sub_command(func):
@wraps(func)
def wrapped(*args, **kwargs):
try:
func(*args, **kwargs)
except IndexError:
print('help_string')
except Exception as e:
print('please contact us:', e)
return wrapped
@sub_command
def git_status():
print('git_status')
if __name__ == '__main__':
# tutorial_1
sandwich()
# The order is important
# sandwich_worse()
# tutorial_2
# elapsed_time_tutorial()
# tutorial_3
# hello_log()
# tutorial_4
# git_status()