48

I'm trying to keep my source code under the 80 character guideline width that PEP8 recommends, but can't figure out how to wrap my doctest which has results longer than 80 characters.

A noddy example:

def long_string():
    """
    Returns a string which is wider than the recommended PEP8 linewidth

    >>> print long_string()
    0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789

    """
    return '0123456789' * 10

I've tried a couple of combinations, including using # doctest: +NORMALIZE_WHITESPACE and trying to simply wrap the line with a newline.

pelson
  • 21,252
  • 4
  • 92
  • 99

2 Answers2

47

Just figured out:

def long_string():
    """
    Returns a string which is wider than the recommended PEP8 linewidth

    >>> print long_string()
    01234567890123456789012345678901234567890123456789012345678901234567890\
12345678901234567890123456789

    """
    return '0123456789' * 10

Hope that helps somebody else out.

pelson
  • 21,252
  • 4
  • 92
  • 99
  • 6
    Generally, I avoid such issues in doctests by changing my expectations. `res = long_string(); print res[:60]` followed by the first 60 chars, etc. – Martijn Pieters Nov 15 '12 at 10:32
  • 1
    Yeah that is certainly one approach. I'm actually documenting a default value that I would like user to see in the docstring, but I don't want it to become stale. – pelson Nov 15 '12 at 10:34
  • 11
    Using an ellipsis in the result might be an alternative solution if you do not care about the exact result, e.g., write `012345678901234567...0123456789` as the expected result. – davitenio Dec 05 '13 at 12:39
  • 7
    [Ellipsis](https://docs.python.org/2/library/doctest.html#doctest.ELLIPSIS) needs to be enabled by adding the [`# doctest: +ELLIPSIS` directive](https://docs.python.org/2/library/doctest.html#doctest-directives) to the end of the code line that produces the output. – qris Apr 09 '15 at 10:18
12

As suggested by davitenio and qris, I would recommend using the #doctest: +ELLIPSIS directive, like so.

>>> from test.test_ppp import MockForm
>>> form = MockForm(mock_file='no-errors.xlsx')
>>> form.get_languages(settings_default='English', survey_header=
... form.metadata['raw_data']['survey'][0])  #doctest: +ELLIPSIS
['Ateso', 'English', 'Luganda', ... 'Runyoro-Rutoro']
Joe Flack
  • 866
  • 8
  • 14