-
Notifications
You must be signed in to change notification settings - Fork 35
/
Copy pathIV More on Decorators.py
417 lines (312 loc) · 9.41 KB
/
IV More on 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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
"""
this chapter gives you a bunch of real-world examples of when and how you would write decorators in your own code. You will also learn advanced
decorator concepts like how to preserve the metadata of your decorated functions and how to write decorators that take arguments.
"""
"""Real-world examples
======================"""
# +++
import time
def timer(func):
""" A decorator that prints how long func took to run."""
# Define wrapper func to return
def wrapper(*args, **kwargs):
# When wrapper is called start timer
t_start = time.time()
# Call decorated func and store result
result = func(*args, **kwargs)
# Get total time it took to run
t_total = time.time() - t_start
print('{} took {}s'.format(func.__name__, t_total))
return result
return wrapper
# Using timer()
@timer
def sleep_n_seconds(n):
time.sleep(n)
sleep_n_seconds(5)
# sleep_n_seconds took 5.005s
# +++
"""=========="""
## Print the return type
def print_return_type(func):
"""Prints out the type of the variable that gets returned from every call of any function it is decorating."""
# Define wrapper(), the decorated function
def wrapper(*args, **kwargs):
# Call the function being decorated
result = func(*args, **kwargs)
print('{}() returned type {}'.format(
func.__name__, type(result)
))
return result
# Return the decorated function
return wrapper
@print_return_type
def foo(value):
return value
print(foo(42))
print(foo([1, 2, 3]))
print(foo({'a': 42}))
"""foo() returned type <class 'int'>
42
foo() returned type <class 'list'>
[1, 2, 3]
foo() returned type <class 'dict'>
{'a': 42}"""
#----
## Counter
def counter(func):
"""decorator that adds a counter to each function that you decorate."""
def wrapper(*args, **kwargs):
wrapper.count += 1
# actual function itself
return func(*args, **kwargs)
#reset counter
wrapper.count = 0
# Return the new decorated function
return wrapper
# Decorate foo() with the counter() decorator
@counter
def foo():
print('calling foo()')
foo()
foo()
print('foo() was called {} times.'.format(foo.count))
# calling foo()
# calling foo()
# foo() was called 2 times.
"""Decorators and metadata
===========================
>>>>>>>> from functools import wraps ==== add the metadata from wrapper to the decorated version of print_sum().
>>>>>>>> @wraps ==== Decorate wrapper() so that it keeps func()'s metadata"""
## Preserving docstrings when decorating functions
def add_hello(func):
def wrapper(*args, **kwargs):
print('Hello')
return func(*args, **kwargs)
return wrapper
# Decorate print_sum() with the add_hello() decorator
@add_hello
def print_sum(a, b):
"""Adds two numbers and prints the sum"""
print(a + b)
print_sum(10, 20)
print_sum_docstring = print_sum.__doc__
print(print_sum_docstring)
# Hello
# 30
# None
## Preserving docstrings when decorating functions 2
# you're printing wrapper docstring , not add hello docstring"""
def add_hello(func):
# Add a docstring to wrapper
def wrapper(*args, **kwargs):
"""Print 'hello' and then call the decorated function."""
print('Hello')
return func(*args, **kwargs)
return wrapper
@add_hello
def print_sum(a, b):
"""Adds two numbers and prints the sum"""
print(a + b)
print_sum(10, 20)
print_sum_docstring = print_sum.__doc__
print(print_sum_docstring)
# Hello
# 30
# Print 'hello' and then call the decorated function.
## Preserving docstrings when decorating functions 3
# Import the function you need to fix the problem
# will allow you to add the metadata from print_sum() to the decorated version of print_sum().
from functools import wraps
def add_hello(func):
def wrapper(*args, **kwargs):
"""Print 'hello' and then call the decorated function."""
print('Hello')
return func(*args, **kwargs)
return wrapper
@add_hello
def print_sum(a, b):
"""Adds two numbers and prints the sum"""
print(a + b)
print_sum(10, 20)
print_sum_docstring = print_sum.__doc__
print(print_sum_docstring)
## Preserving docstrings when decorating functions 4
from functools import wraps
def add_hello(func):
# Decorate wrapper() so that it keeps func()'s metadata
@wraps(func)
def wrapper(*args, **kwargs):
"""Print 'hello' and then call the decorated function."""
print('Hello')
return func(*args, **kwargs)
return wrapper
@add_hello
def print_sum(a, b):
"""Adds two numbers and prints the sum"""
print(a + b)
print_sum(10, 20)
print_sum_docstring = print_sum.__doc__
print(print_sum_docstring)
# Hello
# 30
# Adds two numbers and prints the sum
#----
## Measuring decorator overhead
@check_everything
def duplicate(my_list):
"""Return a new list that repeats the input twice"""
return my_list + my_list
t_start = time.time()
duplicated_list = duplicate(list(range(50)))
t_end = time.time()
decorated_time = t_end - t_start
t_start = time.time()
# Call the original function instead of the decorated one
duplicated_list = duplicate.__wrapped__(list(range(50)))
t_end = time.time()
undecorated_time = t_end - t_start
print('Decorated time: {:.5f}s'.format(decorated_time))
print('Undecorated time: {:.5f}s'.format(undecorated_time))
# Finished checking inputs
# Finished checking outputs
# Decorated time: 1.74689s
# Undecorated time: 0.00026s
#----
"""Decorators that take arguments
=================================
>>>>>>>>> ==== for using a decorator that prints n times eg."""
# ++
def run_n_times(n):
"""define and Return decorator
Returns: function 3 times"""
def decorator(func):
# wrapper that takes a range and applys function in wich you used decorator
def wrapper(*args, **kwargs):
for i in range(n):
func(*args, **kwargs)
return wrapper
return decorator
@run_n_times(3)
def print_sum(a,b):
print(a+b)
print_sum(3,5)
# 8
# 8
# 8
# ++
#----
## Run_n_times()
# Make print_sum() run 10 times with the run_n_times() decorator
@run_n_times(10)
def print_sum(a, b):
print(a + b)
print_sum(15, 20)
# 35....10times
## Run_n_times() 2
# Use run_n_times() to create the run_five_times() decorator
run_five_times = run_n_times(5)
@run_five_times
def print_sum(a, b):
print(a + b)
print_sum(4, 100)
# 104....5times
## Run_n_times() 3
# modify the built-in print()
# Modify the print() function to always run 20 times
print = run_n_times(20)(print)
print('What is happening?!?!')
# What is happening?!?! .... 20times
#----
## HTML Generator
def html(open_tag, close_tag):
def decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
msg = func(*args, **kwargs)
return '{}{}{}'.format(open_tag, msg, close_tag)
# Return the decorated function
return wrapper
# Return the decorator
return decorator
## HTML Generator 2
# Make hello() return bolded text
@html('<b>', '</b>')
def hello(name):
return 'Hello {}!'.format(name)
print(hello('Alice'))
# <script.py> output:
# <b>Hello Alice!</b>
## HTML Generator 3
# Make goodbye() return italicized text
@html('<i>', '</i>')
def goodbye(name):
return 'Goodbye {}.'.format(name)
print(goodbye('Alice'))
# <i>Goodbye Alice.</i>
## HTML Generator 4
# Wrap the result of hello_goodbye() in <div> and </div>
@html('<div>','</div>')
def hello_goodbye(name):
return '\n{}\n{}\n'.format(hello(name), goodbye(name))
print(hello_goodbye('Alice'))
# <div>
# <b>Hello Alice!</b>
# <i>Goodbye Alice.</i>
# </div>
"""Timeout(): a real world example
================================="""
## Tag your functions
def tag(*tags):
# Define a new decorator, named "decorator", to return
def decorator(func):
# Ensure the decorated function keeps its metadata
@wraps(func)
def wrapper(*args, **kwargs):
# Call the function being decorated and return the result
return func(*args, *kwargs)
wrapper.tags = tags
return wrapper
# Return the new decorator
return decorator
@tag('test', 'this is a tag')
def foo():
pass
print(foo.tags)
# ('test', 'this is a tag')
#----
## Check the return type
def returns_dict(func):
# Complete the returns_dict() decorator
def wrapper(*args, **kwargs):
result = func(*args, **kwargs)
assert(type(result) == dict)
return result
return wrapper
@returns_dict
def foo(value):
return value
try:
print(foo([1,2,3]))
except AssertionError:
print('foo() did not return a dict!')
# foo() did not return a dict!
## Check the return type 2
def returns(return_type):
# Complete the returns() decorator
def decorator(func):
def wrapper(*args, **kwargs):
result = func(*args, **kwargs)
assert type(result) == return_type
return result
return wrapper
return decorator
@returns(dict)
def foo(value):
return value
try:
print(foo([1,2,3]))
except AssertionError:
print('foo() did not return a dict!')
# <script.py> output:
# foo() did not return a dict!