为什么分号不抑制doctest中的输出?

2024-04-29 18:43:33 发布

您现在位置:Python中文网/ 问答频道 /正文

为什么分号不抑制doctest中的输出?一个解决方法是分配结果,但我很好奇为什么这不起作用。你知道吗

"""
>>> 1+1;     # Semicolons typically suppress output, but this fails
>>> x = 1+1  # Workaround: assign result to suppress output.
"""
Failed example:
    1+1;
Expected nothing
Got:
    2

Tags: to方法outputexampleresultthisdoctestbut
2条回答
<>与其他语言(如C/C++)不同,分号是Python中语句的EM>可选EME>终结符,如下面的RePL中所见:

Python 3.6.5 |Anaconda custom (64-bit)| (default, Mar 29 2018, 13:32:41) [MSC v
1900 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> 1 + 1;
2
>>> 1 + 1
2

但是,您可能会在IPython中观察到不同的行为:

In [120]: 1 + 1;

In [121]: 1 + 1
Out[121]: 2

IPython的docs建议使用分号来抑制输出。但是,这种行为只针对IPython,并没有以任何方式扩展到Python或其标准库(如doctest)。你知道吗

你在想MATLAB或者IPython什么的。Python分号通常不会抑制任何内容。doctest模拟正常的交互式Python会话,而不是IPython会话,因此分号不起任何作用。你知道吗

相关问题 更多 >