-1

Why do semicolons not suppress output in doctests? A workaround is to assign the result, but I am curious as to why this does not work.

"""
>>> 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
mforbes
  • 7,062
  • 3
  • 16
  • 21

3 Answers3

4

Unlike other languages like C/C++, semicolons are optional terminators for statements in Python, as you can see in the Repl below:

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

However, you may observe a different behavior in say IPython:

In [120]: 1 + 1;

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

The docs for IPython suggest using semicolons to suppress output. However, this behavior is only specific to IPython and does not in any way extend to Python or its standard libraries(like doctest).

jpaugh
  • 6,634
  • 4
  • 38
  • 90
amanb
  • 5,276
  • 3
  • 19
  • 38
3

You're thinking of MATLAB or IPython or something. Python semicolons don't normally suppress anything. doctest simulates a normal interactive Python session, not an IPython session, so the semicolon does nothing.

user2357112
  • 260,549
  • 28
  • 431
  • 505
-1

The semicolon has no effect at all.

Doctest reads the expected result from the line following the Python statement (i.e. the part after >>>). In your example, there is no result, so doctest expects no result. That's why it reports "Expected nothing". However, 1+1 returns 2.

The second expression, x = 1+1, has no result, so the test is successful (although nothing really is tested).

Try this for example:

"""
>>> 1+1      # without semicolon
2
>>> 1+1;     # with semicolon
2
>>> x = 1+1  # not so useful test
"""
wovano
  • 4,543
  • 5
  • 22
  • 49