83 10.11. Quality Control Python Tutorial, Release 3.9.5 10.11 Quality Control 10.12 Batteries Included 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. The doctest module provides a tool for scanning a module and validating tests embedded in a program’s docstrings. Test construction is as simple as cutting-and-pasting a typical call along with its results into the docstring. This improves the documentation by providing the user with an example and it allows the doctest module to make sure the code remains true to the documentation: Python has a “batteries included” philosophy. This is best seen through the sophisticated and robust capabilities of its larger packages. For example: • The$_{xmlrpc.client}$ and$_{xmlrpc.server}$ modules make implementing remote procedure calls into an almost trivial task. Despite the modules names, no direct knowledge or handling of XML is needed. • The$_{email}$package is a library for managing email messages, including MIME and other RFC 2822 -based message documents. Unlike$_{smtplib}$and$_{poplib}$which actually send and receive messages, the email package has a complete toolset for building or decoding complex message structures (including attachments) and for implementing internet encoding and header protocols. • The$_{json}$package provides robust support for parsing this popular data interchange format. The$_{csv}$mod- ule supports direct reading and writing of files in Comma-Separated Value format, commonly supported by databases and spreadsheets. XML processing is supported by the$_{xml.etree.ElementTree}$ ,$_{xml.dom}$ and$_{xml.sax}$ packages. Together, these modules and packages greatly simplify data interchange between Python applications and other tools. • The$_{sqlite3}$ module is a wrapper for the SQLite database library, providing a persistent database that can be updated and accessed using slightly nonstandard SQL syntax. 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 import unittest classTestStatisticalFunctions (unittest .TestCase): def test_average (self): self.assertEqual(average([ 20 ,30 ,70 ]),40.0 ) self.assertEqual( round(average([ 1,5,7]),1),4.3 ) with self.assertRaises(ZeroDivisionError ): average([]) with self.assertRaises(TypeError): average( 20 ,30 ,70 ) unittest.main() # Calling from the command line invokes all tests The$_{unittest}$module is not as effortless as the$_{doctest}$module, but it allows a more comprehensive set of tests to be maintained in a separate file: