预期的数组导致doctest。文本错误'没有预期'。 Python 3.3.2

时间:2014-02-19 08:20:04

标签: python python-3.x doctest

我尝试使用doctest来跟踪源代码:

def add_greeting(L=[]):
    """ (list) -> NoneType

    Append 'hello' to L and print L.

    >>> greetings_list = ['hi', 'bonjour']
    >>> add_greeting(greetings_list)
    >>> greetings_list
    ['hi', 'bonjour', 'hello']
    """

    L.append('hello')
    print(L)


if __name__ == '__main__':
    import doctest
    print(doctest.testmod())

当我像'python my_file.py'一样启动此文件时,我得到以下内容:

python my_file.py
**********************************************************************
File "my_file.py", line 9, in __main__.add_greeting
Failed example:
    add_greeting(greetings_list)
Expected nothing
Got:
    ['hi', 'bonjour', 'hello']
**********************************************************************
1 items had failures:
   1 of   3 in __main__.add_greeting
***Test Failed*** 1 failures.
TestResults(failed=1, attempted=3)

有人可以帮我解决这个错误吗? 为什么我在这种情况下得到'没有期待'? 如何解决?

1 个答案:

答案 0 :(得分:0)

尝试

def add_greeting(L=[]):
    """ (list) -> NoneType

    Append 'hello' to L and print L.

    >>> greetings_list = ['hi', 'bonjour']
    >>> add_greeting(greetings_list)
    ['hi', 'bonjour', 'hello']
    >>> greetings_list
    ['hi', 'bonjour', 'hello']
    """

    L.append('hello')
    print(L)


if __name__ == '__main__':
    import doctest
    print(doctest.testmod())

您收到错误是因为print(L)末尾有add_greeting,但文档字符串中的示例控制台输出不希望add_greeting打印或返回任何内容。