Doctest traps

You met doctests in the functions chapter. They compare printed text, not values, and that causes most doctest failures.

  • Output must match repr exactly. 'hi' passes, "hi" fails. A trailing space fails.
  • Floats. 0.1 + 0.2 prints 0.30000000000000004. Round in the example: round(x, 2).
  • Unordered output. A set may print in a different order on another run or version. Wrap it in sorted(...).
  • Exceptions. Write Traceback (most recent call last):, then ..., then the last line, like ValueError: empty. doctest ignores the middle.
  • Long or changing output. Add # doctest: +ELLIPSIS and write ... for the part that varies, or # doctest: +SKIP to show an example without running it.

doctest.testmod() returns a result with the counts, which the program prints. Run it. Then remove the sorted from the first doctest and see if it still passes.