Using the doctest module
All of the example code in this book that is executed at the interactive interpreter (like the String formatting example code in this appendix) was created using Python's doctest
module. The doctest
module allows the writing of executable test code within the docstrings of modules, classes, functions, and methods. It is a great way to not just test your code, but provide executable documentation. For example, we could create a file C:\mayapybook\pylib\doctestexample.py
with the following:
def adder(a, b): """ Return a added to b. >>> adder(1, 2) 3 >>> adder('a', 'b') 'ab' >>> adder(1, 'b') Traceback (most recent call last): TypeError: unsupported operand type(s) for +: 'int' and 'str' """ return a + b
Now if you run this file through the doctest
module, it will run all the prompt-like lines and ensure...