Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python doctest with newline characters: inconsistent leading whitespace error

Tags:

python

doctest

When writing python doctests, how does one properly introduce newline characters within a string in the test? Here's a simple example:

def remove_newlines(text):
    """
    >>> remove_newlines("line1 \n"
    ...                 "still line 1\r"
    ...                 "now line2 \n"
    ...                 "more line2\n")
    line1 still line1
    now line2 more line2
    """
    return text.replace('\n', '')

import doctest
doctest.run_docstring_examples(remove_newlines, globals())

The output of which is:

Traceback (most recent call last):
...
ValueError: line 3 of the docstring for NoName has inconsistent leading whitespace: '"'
like image 506
kalefranz Avatar asked Sep 12 '13 19:09

kalefranz


3 Answers

The docstring docs actually allude to the problem, but not entirely clearly.

A couple of other stackoverflow threads here and here were helpful, but not easy to find given my own search criteria.

Here is my actual solution:

def remove_CRs(text):
    r"""
    >>> output = remove_CRs("line1 \r"
    ...                     "still line1\n"
    ...                     "now line2 \r"
    ...                     "more line2\r")
    >>> print(output)
    line1 still line1
    now line2 more line2
    """
    return text.replace('\r', '')

import doctest
doctest.run_docstring_examples(remove_CRs, globals())

Three things have changed from the original code snippet:

  1. The docstring had to be a raw python string.
  2. I had to use print() on the function output.
  3. I had to get over my own confusion with the difference between \n and \r. (That one's on me.)

Hope this saves someone else the couple of hours I spent on this.

like image 110
kalefranz Avatar answered Nov 19 '22 22:11

kalefranz


You need to escape the backslash.

The docstring is itself a string where \n means newline. In

def foo():
    """
    print "Hello world\n";
    """
    pass

the docstring doesn't contain a valid Python statement but contains instead a newline inside the quoted string

like image 45
6502 Avatar answered Nov 19 '22 23:11

6502


Just prefixing my docstring with 'r' worked in my case. Python 3.5.1.

like image 12
Love and peace - Joe Codeswell Avatar answered Nov 19 '22 23:11

Love and peace - Joe Codeswell