[TIP] doctest and floats

Ben Finney bignose+hates-spam at benfinney.id.au
Mon Mar 10 18:18:01 PDT 2008

"Tim Head" <betatim at gmail.com> writes:

> On 10/03/2008, Ben Finney <bignose+hates-spam at benfinney.id.au> wrote:
> > Instead, do [in your doctests] what people *should* be doing
> > [with your code]
> Yes, obviously that is the right way to do it, the problem with this
> it requires four lines to test the return value of a function. Which
> considering we are in doctest world means someone reading the docs
> needs to wade through four lines (and comprehend that all they do is
> check (near) equality) which IMHO reduces the benefit of doctests to
> near zero ;]]

Not at all. The great benefit of such a doctest is that it *shows the
reader how to do it right*. All of the necessary steps to use your
code should be in the doctest.

Remember that doctests serve two very important purposes: automated
tests *and* direct examples to the reader showing how your code should
be used.

> To make matters even worse, what I really was after was a nifty way to
> compare an array of floats ...

Then your complaints about extra lines of code are reduced even further.

    >>> epsilon = 1e-12
    >>> want = [1.0, 0.8, 0.6, 0.4, 0.2, 0.1]
    >>> got = foo()
    >>> len(want) == len([False for (w, g) in zip(want, got)
    ...     if (w - g) < epsilon])

Is 'want_array == got_array', or simply showing an array of floats for
doctest to compare for equality, simpler than this? Of course it is,
but it's *wrong*. Your doctests should not even imply that an equality
test is correct, otherwise they fail to provide a good example to the

> I was hoping there would be a way to (ab)use the ellipsis flag to
> say "I dont care about the digits after this one", obviously not a
> smart thing to do for real tests, but humans would understand it.

However, a human would *not* then be able to use the doctest as an
example for their own code. They still need to be doing an epsilon
comparison (if they want to test near-equality), so your doctests
should show them that method.

 \            "Beware of and eschew pompous prolixity."  -- Charles A. |
  `\                                                         Beardsley |
_o__)                                                                  |
Ben Finney

More information about the testing-in-python mailing list