-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhasattr_protocol.py
55 lines (48 loc) · 1.13 KB
/
hasattr_protocol.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
import time
import timeit
setups = {
"property": """
class MyClass:
@property
def __protocol__(self):
time.sleep(0.00001)
return True
obj = MyClass()""",
"method": """
class MyClass:
def __protocol__(self):
time.sleep(0.00001)
return True
obj = MyClass()""",
"none": """
class MyClass:
pass
obj = MyClass()""",
}
tests = {
"eafp": """
try:
obj.__protocol__
except AttributeError:
pass
""",
"lbyl": """hasattr(obj, "__protocol__")""",
"gentle-lbyl": (
""""__protocol__" in obj.__dir__() or hasattr(obj, "__protocol__")"""
),
}
results = {}
for setup_name, setup_stmt in setups.items():
for test_name, test_stmt in tests.items():
test_name = f"{setup_name}, {test_name}"
times = timeit.repeat(
setup=setup_stmt,
stmt=test_stmt,
repeat=10,
number=1000,
globals={"time": time},
)
avg_time = sum(times) / len(times)
results[test_name] = avg_time
for test_name, result in sorted(results.items(), key=lambda x: x[1]):
print(f"{test_name:>18}: {result:03g}")