5.2.3.2 How are Docstring Examples Recognized?

###
5.2.3.2 How are Docstring Examples Recognized?

In most cases a copy-and-paste of an interactive console session works fine, but doctest isn't trying to do an exact emulation of any specific Python shell. All hard tab characters are expanded to spaces, using 8-column tab stops. If you don't believe tabs should mean that, too bad: don't use hard tabs, or write your own `DocTestParser` class.

Changed in version 2.4: Expanding tabs to spaces is new; previous versions tried to preserve hard tabs, with confusing results.

    >>> # comments are ignored
    >>> x = 12
    >>> x
    12
    >>> if x == 13:
    ...     print "yes"
    ... else:
    ...     print "no"
    ...     print "NO"
    ...     print "NO!!!"
    ...
    no
    NO
    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. If expected output does contain a blank line, put `<BLANKLINE>` in your doctest example each place a blank line is expected. Changed in version 2.4: `<BLANKLINE>` was added; there was no way to use expected output containing empty lines in previous versions.

- 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 should use a raw docstring, which will preserve your backslashes exactly as you type them:

      >>> def f(x):
      ...     r'''Backslashes in a raw docstring: m\n'''
      >>> print f.__doc__
      Backslashes in a raw docstring: m\n

  Otherwise, the backslash will be interpreted as part of the string. For example, the "\" above would be interpreted as a newline character. Alternatively, you can double each backslash in the doctest version (and not use a raw string):

      >>> def f(x):
      ...     '''Backslashes in a raw docstring: m\\n'''
      >>> print f.__doc__
      Backslashes in a raw docstring: m\n

- The starting column doesn't matter:

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

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