-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDecoratorApplicationLogger.py
More file actions
executable file
·121 lines (91 loc) · 2.01 KB
/
DecoratorApplicationLogger.py
File metadata and controls
executable file
·121 lines (91 loc) · 2.01 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
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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Apr 28 15:46:48 2021
@author: maherme
"""
#%%
def logged(fn):
from functools import wraps
from datetime import datetime, timezone
@wraps(fn)
def inner(*args, **kwargs):
run_dt = datetime.now(timezone.utc)
result = fn(*args, **kwargs)
print('{0}: called {1}'.format(run_dt, fn.__name__))
return result
return inner
@logged
def func_1():
pass
@logged
def func_2():
pass
func_1()
func_2()
#%%
# We can use the decorator from DecoratorApplicationTiming.py:
def timed(fn):
from functools import wraps
from time import perf_counter
@wraps(fn)
def inner(*args, **kwargs):
start = perf_counter()
result = fn(*args, **kwargs)
end = perf_counter()
print('{0} ran for {1:.6f}s'.format(fn.__name__, end-start))
return result
return inner
# We can decorate a function with two decorators:
@logged
@timed
def fact(n):
from operator import mul
from functools import reduce
return reduce(mul, range(1, n+1))
fact(3)
#%%
# We can specify two decorators in this other way:
def fact(n):
from operator import mul
from functools import reduce
return reduce(mul, range(1, n+1))
fact = logged(timed(fact))
fact(6)
#%%
# Let's do an example for understanding what decorator runs first:
def dec_1(fn):
def inner():
print('Running dec_1')
return fn()
return inner
def dec_2(fn):
def inner():
print('Running dec_2')
return fn()
return inner
@dec_1
@dec_2
def my_func():
print('Running my_func')
my_func()
#%%
# Notice my_func is called first now:
def dec_1(fn):
def inner():
result = fn()
print('Running dec_1')
return result
return inner
def dec_2(fn):
def inner():
result = fn()
print('Running dec_2')
return result
return inner
@dec_1
@dec_2
def my_func():
print('Running my_func')
my_func()
#%%