-
Notifications
You must be signed in to change notification settings - Fork 0
/
decorators.py
100 lines (77 loc) · 2.17 KB
/
decorators.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
# decorators allows to temporary extend and modify the behavior of a callable (function, method, class)
# often are generic functionality wrapped around a function (e.g. timing, logging, access control, etc)
# decorator: container function
# wrapped: input function to decorate
# wrapper: closure decorating the input
import time
# timing decorator
def time_wrapper(wrapped):
def wrapper(*args, **kwargs):
start = time.time()
result = wrapped(*args, **kwargs)
end = time.time()
print(wrapped.__name__ + " took " + str((end-start)*1000) + " mil sec")
return result
return wrapper
@time_wrapper
def calc_square(numbers): # wrapped
result = []
for number in numbers:
result.append(number*number)
return 'Squared!'
@time_wrapper
def calc_cube(numbers): # wrapped
result = []
for number in numbers:
result.append(number*number*number)
return 'Cubed!'
array = range(1, 100000)
calc_square(array)
calc_cube(array)
# logging decorator
def star_decorator(wrapped):
def wrapper(*args, **kwargs):
print('*'*10 + 'START' + '*'*10)
wrapped(*args, **kwargs)
print('*'*10 + 'END' + '*'*10)
return wrapper
@star_decorator
def calc_square(n):
print(n * n)
calc_square(3)
def trace(wrapped):
def wrapper(*args, **kwargs):
print(f'TRACE: calling {wrapped.__name__}() with {args}, {kwargs}')
original_result = wrapped(*args, **kwargs)
print(f'TRACE: {wrapped.__name__}() returned {original_result!r}')
return original_result
return wrapper
@trace
def write(name, text):
return f'{name}: {text}'
write('Foo', 'Hello World')
# editor
def uppercase(wrapped):
def wrapper():
original_result = wrapped()
modified_result = original_result.upper()
return modified_result
return wrapper
@uppercase
def greet():
return 'Hello!'
greet()
# multiple decoration and order
def strong(f):
def wrapper():
return '<strong>' + f() + '</strong>'
return wrapper
def emphasis(f):
def wrapper():
return '<em>' + f() + '</em>'
return wrapper
@strong
@emphasis
def html_greet():
return 'Hello!'
html_greet()