Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python comment in docstring

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?

like image 701
jxie0755 Avatar asked Jan 28 '23 05:01

jxie0755


2 Answers

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.

like image 133
Mad Physicist Avatar answered Jan 29 '23 19:01

Mad Physicist


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.

like image 22
Viswanath Polaki Avatar answered Jan 29 '23 18:01

Viswanath Polaki