-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path_decorators.py
More file actions
138 lines (110 loc) · 2.39 KB
/
_decorators.py
File metadata and controls
138 lines (110 loc) · 2.39 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
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
# coding=utf-8
'''
def transact(method):
def transacted_call(slf, *args, **kwargs):
try:
transaction = self.start_transaction()
r = method(slf, *args, **kwargs)
transaction.commit()
return r
except:
transaction.rollback()
raise
return transacted_call
class C:
@transact
def update(self, what):
return
'''
#
# def decorator
#
'''
def decorator(input_function):
def wrapper():
print('_________________')
input_function()
print('_________________')
return wrapper
@decorator
@decorator
def a_stand_alone_function():
print('simpliest function')
#a_stand_alone_function = decorator(a_stand_alone_function)
a_stand_alone_function()
'''
#
# a decorator passing arbitrary arguments
#
'''
def deco(function_to_decorate):
def wrapper(*args, **kwargs):
print(args)
print(kwargs)
function_to_decorate(*args, **kwargs)
return wrapper
class Mary(object):
def __init__(self):
self.age = 32
@deco
def sayYourAge(self, lie=-3):
print("I'm {} years.".format(self.age + lie))
m = Mary()
m.sayYourAge()
'''
#
# benchmark
#
'''
import datetime
def benchmark(func):
def wrapper(*args, **kwargs):
start = datetime.datetime.now()
func(*args, **kwargs)
finish = datetime.datetime.now()
total_seconds = (finish - start).total_seconds()
print(total_seconds)
return wrapper
@benchmark
def s():
out = 6 ** 80
return out
s()
'''
#
# counter
#
def counter(func):
def wrapper(*args, **kwargs):
wrapper.count += 1
print(func.__name__, wrapper.count)
wrapper.count = 0
return wrapper
@counter
def health():
print('-')
health()
health()
health()
health()
#
# decorator with args
#
'''
def decorator_with_args(decorator_to_enhance):
def decorator_maker(*args, **kwargs):
def dec_wrapper(func):
return decorator_to_enhance(func, *args, **kwargs)
return dec_wrapper
return decorator_maker
@decorator_with_args
def decorated_decorator(func, *args, **kwargs):
def wrapper(fun_arg1, fun_arg2):
print('I have', args, kwargs)
return func(fun_arg1, fun_arg2)
return wrapper
@decorated_decorator
def decorated_function(fun_arg1, fun_arg2):
print(fun_arg1, fun_arg2)
decorated_function('dg', 'hyy')
'''