Development/Efficiency: test_property.py

File test_property.py, 1.6 KB (added by jdsiiro, 5 years ago)

Source code for testing properties

Line 
1#!/usr/bin/env python
2from math import sqrt
3from sys import stdout as out, version_info
4from timeit import timeit
5
6out.write('='*72+"\nTesting on Python %s\n" % (
7        '.'.join(str(x) for x in version_info[:3]),) )
8
9setup = "from __main__ import %s as CLS; obj=CLS()"
10
11class class_attribute(object):
12    def __init__(self):
13        self.a = 0
14
15class class_property(object):
16    def __init__(self):
17        self._a = 0
18
19    @property
20    def a(self):
21        return self._a
22
23    @a.setter
24    def a(self, value):
25        self._a = value
26
27class class_method(object):
28    def __init__(self):
29        self._a = 0
30
31    def a(self):
32        pass
33
34    def get_a(self):
35        return self._a
36
37    def set_a(self, value):
38        self._a = value
39   
40
41tests = [
42    ("class_attribute","x = obj.a; x = None"),
43    ("class_method","x = obj.get_a(); x = None"),
44    ("class_property","x = obj.a; x = None"),
45    ("class_attribute","obj.a = 5; obj.a = None"),
46    ("class_method","obj.set_a(5); obj.set_a(None)"),
47    ("class_property","obj.a = 5; obj.a = None"),
48    ]
49
50testFmt = "%%-%ds" % (max(len("%s"%(t,)) for t in tests) + 2, )
51for test in tests:
52    try:
53        trials = [ timeit(test[1], setup % (test[0]), number=10000000)
54                   for i in range(3) ]
55        mean = sum(trials) / float(len(trials))
56        stdev = sqrt( sum(x**2 for x in trials)/float(len(trials))
57                      - mean**2 )
58        out.write(
59            testFmt % (test,) + " %0.6f  +/- %0.3f\n" % (mean, stdev) )
60    except KeyboardInterrupt:
61        raise SystemExit
62    except:
63        out.write( testFmt % (test,) + "(exception)\n" )
64    out.flush()
65
66