Website hosting service by

 Back to Index

5.2.6 How are Docstring Examples Recognized?

In most cases a copy-and-paste of an interactive console session works fine--just make sure the leading whitespace is rigidly consistent (you can mix tabs and spaces if you're too lazy to do it right, but doctest is not in the business of guessing what you think a tab means).

>>> # comments are ignored
>>> x = 12
>>> x
>>> if x == 13:
...     print "yes"
... else:
...     print "no"
...     print "NO"
...     print "NO!!!"

Any expected output must immediately follow the final '>>> ' or '... ' line containing the code, and the expected output (if any) extends to the next '>>> ' or all-whitespace line.

The fine print:


  • Expected output cannot contain an all-whitespace line, since such a line is taken to signal the end of expected output.


  • Output to stdout is captured, but not output to stderr (exception tracebacks are captured via a different means).


  • If you continue a line via backslashing in an interactive session, or for any other reason use a backslash, you need to double the backslash in the docstring version. This is simply because you're in a string, and so the backslash must be escaped for it to survive intact. Like:


    >>> if "yes" == \\
    ...     "y" +   \\
    ...     "es":
    ...     print 'yes'


  • The starting column doesn't matter:


      >>> assert "Easy!"
            >>> import math
                >>> math.floor(1.9)

    and as many leading whitespace characters are stripped from the expected output as appeared in the initial '>>> ' line that triggered it.




2002-2004 Webhosting Service


Disclaimer: This documentation is provided only for the benefits of our hosting customers.
For authoritative source of the documentation, please refer to


Domain registration : Buy domain name or register domain name from $5.95/year only


Cheap domain registration : Register domain name or buy domain name, including free domain hosting services offers cheap domain registration, domain name transfer and domain search services