Search code examples
pythonspecial-charactersdocstringdoctest

Python docstring: inconsistent leading whitespace error without new line


my docstring:

def some_f():
    """
    1. First story
        >>> str(5)
        if you want to see the value:
        >>> print(str(5))
    2. Another story
        bla bla
    """

When using doctest, I'm getting:

ValueError: line 6 of the docstring for File.Class.some_f has inconsistent leading whitespace: '2. Another story'

I've read (here and here) that this problem may occur when one use \n or other special character in the docstring, but it's not the case here. No idea why this is happenning and how to fix that. In fact it expects me to move the second point to the right, since this is working properly:

def some_f():
    """
    1. First story
        >>> str(5)
        if you want to see the value:
        >>> print(str(5))
        2. Another story
        bla bla
    """

But it's not what I want.


Solution

  • The question and title should include the clarification that this error occurs because you are running doctest.testmod(); otherwise Python doesn't care about your formatting.

    The problem is that doctest expects each line that appears to be an interactive prompt to be followed by the expected output for the doctest, and it considers a blank line or another appearance of >>> to be the end of the expected results.

    Leave a blank line to show the end of expected output, and it won't care about the whitespace of the next line.

    
    def some_f():
        """
        1. First story
            >>> str(5)
            '5'
            
            if you want to see the value:
            >>> print(str(5))
            5
            
        2. Another story
            bla bla
        """
        pass
    
    if __name__ == '__main__':
        import doctest
        doctest.testmod()
    

    Without the line break after '5' that case would fail as doctest would include if you want to see the value: as part of the expected output from >>>str(5)