Development/Efficiency: test_functions.py

File test_functions.py, 1.9 KB (added by jdsiiro, 5 years ago)

Source code for testing function signatures.

Line 
1from math import sqrt
2from sys import stdout as out, version_info
3from timeit import timeit
4
5def tester(fcns, tests):
6    fmt = '%%-%ds %%s\n' % (
7        max(len(f+t) for t in tests for f in fcns), )
8    for fcn in fcns:
9        for test in tests:
10            try:
11                trials = [ timeit(fcn+test, setup, number=10000000)
12                           for i in range(3) ]
13                mean = sum(trials) / float(len(trials))
14                stdev = sqrt( sum(x**2 for x in trials)/float(len(trials))
15                              - mean**2 )
16                out.write(
17                    fmt % ( fcn+test, "%0.6f  +/- %0.3f" % (mean, stdev) ) )
18            except KeyboardInterrupt:
19                raise SystemExit
20            except:
21                out.write( fmt % (fcn+test, '(exception)') )
22            out.flush()
23        out.write('\n')
24
25
26setup="""
27def f_positional(a, b, c):
28    pass
29
30def f_varargs(*args):
31    pass
32
33def f_default(a=None, b=5, c=None):
34    pass
35
36def f_kwds(**kwds):
37    pass
38
39def f_vararg_kwds(*args, **kwds):
40    pass
41
42def f_all(a, b=5, *args, **kwds):
43    pass
44
45pos = (1,2,3)
46kwd = {'a':1,'b':2,'c':3}
47"""
48
49p_fcns = ["f_positional", "f_varargs", "f_default", "f_vararg_kwds", "f_all"]
50k_fcns = ["f_positional", "f_default", "f_kwds", "f_vararg_kwds", "f_all"]
51#setup = "from __main__ import " + ','.join(set(p_fcns+k_fcns))
52
53out.write('='*72+"\nTesting on Python %s\n" % (
54        '.'.join(str(x) for x in version_info[:3]),) )
55out.write(setup)
56
57out.write("\nPositional arguments\n\n")
58tester(p_fcns, ['()', '(1)', '(1,2)', '(1,2,3)', '(*(1,2,3))', '(*pos)'])
59
60out.write("\nKeyword arguments\n\n")
61tester(k_fcns, [ '()', '(a=1)', '(a=1,b=2)', '(a=1,b=2,c=3)',
62                 "(**{'a':1,'b':2,'c':3})", "(**kwd)" ])
63
64out.write("\nMixed arguments\n\n")
65tester(['f_vararg_kwds','f_all'],
66       [ '(1,2,c=3)', '(1,b=2,c=3)', '(1,b=2)', "(1,2,3,d=4)" ])