-
Notifications
You must be signed in to change notification settings - Fork 27
/
decorator_experiments.py
121 lines (80 loc) · 2.35 KB
/
decorator_experiments.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
import functools
import random
def once_only(f):
"""A function decorater that ensures the decorated function is only called
once during the lifetime of the VM."""
static_data = dict(been_called=False, result=None)
@functools.wraps(f)
def wrapper(*args, **kwargs):
if not static_data["been_called"]:
static_data["result"] = f(*args, **kwargs)
static_data["been_called"] = True
return static_data["result"]
return wrapper
class DependencyNotFoundError(NameError):
pass
def depends(dependency_list):
"""A function decorator that ensures that the depended-upon functions are
called (in order) before the decorated function is called. Dependencies
will be called without any arguments."""
def decorator(f):
@functools.wraps(f)
def wrapper(*args, **kwargs):
for dependency in dependency_list:
if callable(dependency):
dependency()
else:
if dependency in globals():
globals()[dependency]()
else:
raise DependencyNotFoundError(
"Dependency not found: %s" % dependency
)
return f(*args, **kwargs)
return wrapper
return decorator
def krisskross(fn):
"""
Well make you jump, jump (out of a window)
50% chance of reversing the order of args and kwargs keys
"""
def wrapped(*args, **kwargs):
if random.choice([True, False]):
return fn(*args[::-1], **{k[::-1]: v for k, v in kwargs.items()})
return fn(*args, **kwargs)
return wrapped
@once_only
def should_only_run_once():
print("Function has been run!")
should_only_run_once()
should_only_run_once()
def a1():
print("a1")
def b1():
print("b1")
@depends([a1, b1])
def c1():
print("c1")
print("--------")
c1()
@depends([a1])
def b2():
print("b2")
@depends([b2])
def c2():
print("c2")
print("--------")
c2()
@depends(["a1", "b1"])
def c3():
print("c3")
print("--------")
c3()
@krisskross
def guess_the_order(*args, **kwargs):
print(args)
print(kwargs)
guess_the_order(1, 2, 3, hello="world")
guess_the_order(1, 2, 3, hello="world")
guess_the_order(1, 2, 3, hello="world")
guess_the_order(1, 2, 3, hello="world")