Search code examples
pythonpython-3.xdocstring

Docstring has inconsistent leading whitespace


In the following code:

def read_file(filename):
    """
    >>> read_file('text.txt')
    {'Donald Trump': [('Donald Trump', 'Join me live in Springfield, Ohio!\nLit!!\n', 1477604720, 'Twitter for iPhone', 5251, 1895)]}
    """

I get an error saying:

ValueError: line 4 of the docstring for __main__.read_file has inconsistent leading whitespace: 'Lit!!'

Any ideas what is causing this?


Solution

  • Escape all backslashes in the documentation string. That is:

    \nLit!!\n
    

    Should instead be:

    \\nLit!!\\n'
    

    Alternatively you could supply the docstring as a raw string and not worry about backslashes:

    r"""
    >>> read_file('text.txt')
    {'Donald Trump': [('Donald Trump', 'Join me live in Springfield, Ohio!\nLit!!\n', 1477604720, 'Twitter for iPhone', 5251, 1895)]}
    """