|
Original |
Translation |
|
957
|
>>> from timeit import Timer >>> Timer('t=a; a=b; b=t', 'a=1; b=2').timeit() 0.57535828626024577 >>> Timer('a,b = b,a', 'a=1; b=2').timeit() 0.54962537085770791
|
|
|
958
|
In contrast to :mod:`timeit`'s fine level of granularity, the :mod:`profile` and :mod:`pstats` modules provide tools for identifying time critical sections in larger blocks of code.
|
|
|
959
|
|
|
|
960
|
One approach for developing high quality software is to write tests for each function as it is developed and to run those tests frequently during the development process.
|
|
|
961
|
|
962
|
def average(values): """Computes the arithmetic mean of a list of numbers. >>> print(average([20, 30, 70])) 40.0 """ return sum(values) / len(values) import doctest doctest.testmod() # automatically validate the embedded tests
|
|
|
963
|
The :mod:`unittest` module is not as effortless as the :mod:`doctest` module, but it allows a more comprehensive set of tests to be maintained in a separate file::
|
|
|
964
|
import unittest class TestStatisticalFunctions(unittest.TestCase): def test_average(self): self.assertEqual(average([20, 30, 70]), 40.0) self.assertEqual(round(average([1, 5, 7]), 1), 4.3) self.assertRaises(ZeroDivisionError, average, []) self.assertRaises(TypeError, average, 20, 30, 70) unittest.main() # Calling from the command line invokes all tests
|
|
|
965
|
|
|
|
966
|
Python has a "batteries included" philosophy. This is best seen through the sophisticated and robust capabilities of its larger packages. For example:
|
|