Mixing docstrings and doctests makes Python a nifty language
One of my favorite little features of Python is how you can embed comments in modules, classes, and functions, and have these comments available when using the code. It makes it easy to look up info on code when needed without having to jump to the browser. This has encouraged me to write useful comments. The following block shows a simple shopping cart library with several pieces of documentation built into it.
We can open a Python session, pull in the code, poke it, prod it, and see how it works.
I love this! This is how I discovered a lot of how Python worked.
But Python doesn't stop there! It comes "batteries included" with the doctest module, which let's us embed runnable code blocks. I have been working on Chapter 3 - Creating testable documentation with doctest, and loved digging around, creating different recipes using doctests.
If you will look closely at the screenshot above, I typed "print recipe21.__doc__" and "print recipe21.ShoppingCart.__doc__". The Python statements between those two were actually embedded in the docstring!
There is an old debate about how comments are typically out of date and leads to code smells. If you want, you read one such back and forth. Bottom line: Python gives us the power to help blur the line of this debate further by making our documentation testable. Regardless of your opinion on comments, what is the #1 way we best learn how to use a library? With code examples!
But Python's niftyness is only just beginning. We keep talking about viewing doc strings and running doc strings. Wouldn't it be great to write a tiny script, in less than 40 lines, that could print out all the doc strings AND run our doctests?
If we run this, we can see a printout of doc strings as well Python has lots of bits of cool stuff and then makes it super easy to write them together.
We can see the docstrings printed out. We also turned up the verbosity on doctest, and see all the information printed out. Python's deft nature let's us express this report quickly and succinctly. Awesome!

