IdentifiantMot de passe
Mot de passe oublié ?Je m'inscris ! (gratuit) Warnings Warnings

doctest is serious about requiring exact matches in expected output. If even a single character doesn't match, the test fails. This will probably surprise you a few times, as you learn exactly what Python does and doesn't guarantee about output. For example, when printing a dict, Python doesn't guarantee that the key-value pairs will be printed in any particular order, so a test like

>>> foo()
{"Hermione": "hippogryph", "Harry": "broomstick"}

is vulnerable! One workaround is to do

>>> foo() == {"Hermione": "hippogryph", "Harry": "broomstick"}

instead. Another is to do

>>> d = foo().items()
>>> d.sort()
>>> d
[('Harry', 'broomstick'), ('Hermione', 'hippogryph')]

There are others, but you get the idea.

Another bad idea is to print things that embed an object address, like

>>> id(1.0) # certain to fail some of the time
>>> class C: pass
>>> C()   # the default repr() for instances embeds an address
<__main__.C instance at 0x00AC18F0>

The ELLIPSIS directive gives a nice approach for the last example:

>>> C() #doctest: +ELLIPSIS
<__main__.C instance at 0x...>

Floating-point numbers are also subject to small output variations across platforms, because Python defers to the platform C library for float formatting, and C libraries vary widely in quality here.

>>> 1./7  # risky
>>> print 1./7 # safer
>>> print round(1./7, 6) # much safer

Numbers of the form I/2.**J are safe across all platforms, and I often contrive doctest examples to produce numbers of that form:

>>> 3./4  # utterly safe

Simple fractions are also easier for people to understand, and that makes for better documentation.

See About this document... for information on suggesting changes.