-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdecorators.py
54 lines (42 loc) · 1.28 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
import time
from functools import wraps
def retry(func, max_retries=1):
@wraps(func)
def wrapper(*args, **kwargs):
exception = None
for i in range(max_retries):
try:
return func(*args, **kwargs)
except Exception as ex:
exception = ex
wait = 1 + int(i)
print('Retry in %s seconds - %s/%s' %
(wait, i + 1, max_retries))
time.sleep(wait)
raise exception
return wrapper
def try_except(func):
def decorator(*args, **kwargs):
try:
return func(*args, **kwargs)
except Exception as e:
raise e
return decorator
def elapsed(decimal_place=6):
def __print_elapsed(func):
def decorator(*args, **kwargs):
start_time = time.time()
result = func(*args, **kwargs)
end_time = time.time()
time_format = 'elapsed time: %%.%df secs' % decimal_place
print(time_format % (end_time - start_time), 'in %s()' %
func.__name__)
return result
return decorator
return __print_elapsed
@elapsed(decimal_place=3)
def __sample():
total = 0
for i in range(0, 100000):
total += i
return total