Search code examples
pythonstringpython-3.xspecial-charactersdocstring

Special Characters and Line Breaks in Python Doctest


I have a function with a docstring that looks like the following and I want to test that the docstring is correct. I am currently using the doctest module to do so. However, I cannot find a way to represent new line characters and line breaks in the docstring without it crashing. Here is an example that replicates the problem:

def foo():
    r"""
    >>> foo() == ['1\n2\n',\
    '3']
    True
    """
    return ['1\n2\n', '3']

import doctest
doctest.testmod()

This results in the error:

Failed example:
foo() == ['1\n2\n',\
Exception raised:
    Traceback (most recent call last):
      File "C:\Python34\lib\doctest.py", line 1318, in __run
        compileflags, 1), test.globs)
      File "<doctest __main__.foo[0]>", line 1
        foo() == ['1\n2\n',\
                           ^
    SyntaxError: unexpected EOF while parsing

How would I accomplish this?


Solution

  • Use ellipsis ...:

    def foo():
        r"""
        >>> foo() == ['1\n2\n',
        ... '3']
        True
        """
        return ['1\n2\n', '3']
    
    import doctest
    doctest.testmod()
    

    (source)