I found this one out because some of the homework questions I met were tested by docstrings, and it gives me failures.
For example:
def foo(x):
"""
>>> foo(5)
25
>>> foo(6)
36 # Are you sure?
"""
return x**2
if __name__ == '__main__':
import doctest
doctest.testmod(verbose=True)
The example above fails with:
Expected:
36 # are you sure?
Got:
36
I wonder if we are not supposed to add comment in docstring? Or there is a way to make python to ignore the comment in docstring?
Doctest works by capturing stdout from your command line. The text supplied in the test string must match your output exactly. Doctest has no way of knowing what type of data you are outputting: it can only compare text outputs. In your case it is an integer followed by a comment, but what if you did the following instead:
>>> print('36 # are you sure?')
Any comments you want to have must be in the executable lines:
>>> foo(6) # are you sure?
36
This is not as visually appealing, perhaps, but serves nearly the same purpose and actually works. When a line with a comment is passed to the interpreter, the comment is handled correctly.
You can just add your comments like below
>>> # comments are ignored
Reference https://docs.python.org/3/library/doctest.html
Note: This must not be a part of output so if you want to add comment then you can use a new line to write your comment. So in your case "36" line must not contain any other string other than output.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With