如何在 doctest 变量中包含换行符?

How to include a new-line in a doctest variable?

我想将输入到 doctest 的文本换行。这是一个最小的例子:

import doctest

def example1():
    """
    >>> txt = '\n'.join(['abcd', 'efg'])
    """

    return '\n'.join(['abcd', 'efg'])


def example2():
    """
    >>> txt = '\n'.join(['abcd',
    'efg'])
    """

    return '\n'.join(['abcd',
    'efg'])

doctest.testmod()

结果是:

File "example.py", line 16, in __main__.example2
Failed example:
    txt = '\n'.join(['abcd',
Exception raised:
    Traceback (most recent call last):
      File "/usr/local/Cellar/python/3.7.4/Frameworks/Python.framework/Versions/3.7/lib/python3.7/doctest.py", line 1329, in __run
        compileflags, 1), test.globs)
      File "<doctest __main__.example2[0]>", line 1
        txt = '\n'.join(['abcd',
                               ^
    SyntaxError: unexpected EOF while parsing

数组中换行的语法适用于函数体,但不适用于文档测试。如何将 doc-tests 中的长字符串排列成新行?

文档测试需要明确的换行符转义。所以加一个反斜杠:

"""
>>> txt = '\n'.join(['abcd', \
'efg'])
"""