5

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?

Dimitris Fasarakis Hilliard
  • 150,925
  • 31
  • 268
  • 253
Monty
  • 197
  • 2
  • 10
  • Where is the error triggered? It looks like you are running doctests. As someone already answered, the problem is those unescaped `\n` newlines in the test data. But in any case, doctests are not optimal for functions with side effects. This test will fail if `text.txt` can't be found, or the contents is different from what's expected. – Håken Lid Dec 01 '16 at 19:02

1 Answers1

12

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)]}
"""
Dimitris Fasarakis Hilliard
  • 150,925
  • 31
  • 268
  • 253