Skip to content

Mastering Python - Effortlessly Running Tests with python -m doctest


Python -m doctest

Writing a Python Module

  • Become a fully fledged Python package developer by writing your first package!
  • You’ll learn how to structure and write Python code that can be installed, used, and distributed just like famous packages such as NumPy and Pandas.

Utilizing Classes

  • Object Oriented Programming is a staple of Python development.
  • By leveraging classes and inheritance, your Python package will become a much more powerful tool for your users.


  • You’ve now written a fully functional Python package for text analysis!
  • To make maintaining your project as easy as possible, we’ll leverage best practices around concepts such as documentation and unit testing.


  • Identifying good comments
  • Identifying proper docstrings
  • Writing docstrings
  • Readability counts
  • Using good function names
  • Using good variable names
  • Refactoring for readability

Unit testing

  • Using doctest
  • Using pytest
  • Documentation & testing in practice
  • Documenting classes for Sphinx
  • Identifying tools

Final Thoughts

  • Hide Details
  • Exercise

Exercise Using doctest

  • We just learned about doctest, which, if you’re writing full docstrings with examples, is a simple way to minimally test your functions.
  • In this exercise, you’ll get some hands-on practice testing and debugging with doctest.
  • The following have all been pre-loaded in your environment: doctest, Counter, and text_analyzer.
  • Note that your docstring submission must match the solution exactly.
  • If you find yourself getting it wrong several times, it may be a good idea to refresh the sample code and start over.
  1. Complete the input code of the example in the docstring for sum_counters.
  2. Complete the docstring example by filling in the expected output.
  3. Run the testmod function from doctest to test your function’s example code.
def sum_counters(counters):
Sum the values in a dictionary of counters.
>>> c1 = Counter(a=1, b=2, c=3)
>>> c2 = Counter(a=2, b=3, c=4)
>>> sum_counters([c1, c2])
{'a': 3, 'b': 5, 'c': 7}
total = Counter()
for counter in counters:
total += counter
return total
import doctest
  • Take Hint (-30 XP)

By completing the exercise and running the testmod function, you can verify if your sum_counters function works as expected.