forked from fluentpython/example-code
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhasattr.py
More file actions
44 lines (33 loc) · 869 Bytes
/
hasattr.py
File metadata and controls
44 lines (33 loc) · 869 Bytes
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
import timeit
test_hasattr = """
if hasattr(gizmo, 'gadget'):
feature = gizmo.gadget
else:
feature = None
"""
test_getattr = """
feature = getattr(gizmo, 'gadget', None)
"""
test_tryget = """
try:
feature = getattr(gizmo, 'gadget')
except AttributeError:
feature = None
"""
class Gizmo:
def __init__(self):
self.gadget = True
gizmo = Gizmo()
test_keys = 'hasattr', 'getattr', 'tryget'
def test():
for test_key in test_keys:
test_name = 'test_' + test_key
test = globals()[test_name]
setup = 'from __main__ import gizmo'
t_present = min(timeit.repeat(test, setup=setup))
del gizmo.gadget
t_absent = min(timeit.repeat(test, setup=setup))
gizmo.gadget = True
print('{:7} {:.3f} {:.3f}'.format(test_key, t_present, t_absent))
if __name__ == '__main__':
test()