Python Doctest 中的特殊字符和换行符

Bob*_*all 6 python string docstring special-characters python-3.x

我有一个带有如下所示文档字符串的函数,我想测试文档字符串是否正确。我目前正在使用 doctest 模块来执行此操作。但是,我找不到一种方法来表示文档字符串中的新行字符和换行符而不崩溃。这是一个重现该问题的示例:

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

import doctest
doctest.testmod()
Run Code Online (Sandbox Code Playgroud)

这会导致错误:

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
Run Code Online (Sandbox Code Playgroud)

我将如何实现这个目标?

Den*_*zov 6

使用省略号...

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

import doctest
doctest.testmod()
Run Code Online (Sandbox Code Playgroud)

来源