【问题标题】:Python doctest with newline characters: inconsistent leading whitespace error带有换行符的 Python doctest:不一致的前导空格错误
【发布时间】:2013-09-17 08:31:02
【问题描述】:

在编写 python 文档测试时,如何在测试中正确地在字符串中引入换行符?这是一个简单的例子:

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())

其输出为:

Traceback (most recent call last):
...
ValueError: line 3 of the docstring for NoName has inconsistent leading whitespace: '"'

【问题讨论】:

    标签: python doctest


    【解决方案1】:

    在我的情况下,只需在我的文档字符串前面加上 'r' 就可以了。 Python 3.5.1。

    【讨论】:

      【解决方案2】:

      您需要转义反斜杠。

      文档字符串本身就是一个字符串,其中\n 表示换行符。在

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

      文档字符串不包含有效的 Python 语句,而是在引用的字符串中包含换行符

      【讨论】:

      • 这应该是公认的答案。只需将每个 \n 替换为 \\n
      • 或者不要将\n替换为\\n,而是将文档字符串设为原始python字符串:r"""print "Hello world\n";"""
      【解决方案3】:

      docstring docs 实际上暗示了这个问题,但并不完全清楚。

      其他几个 stackoverflow 线程 herehere 很有帮助,但根据我自己的搜索条件,不容易找到。

      这是我的实际解决方案:

      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())
      

      与原来的代码sn-p相比有三处变化:

      1. 文档字符串必须是原始 python 字符串。
      2. 我不得不在函数输出上使用print()
      3. 我不得不克服自己对\n\r 之间区别的困惑。 (那个在我身上。)

      希望这可以节省其他人我花在这上面的几个小时。

      【讨论】:

      • 顺便说一句,我认为 remove_newlines 这个名字如果不删除 \n 会很容易产生误导。
      • 很公平@flornquake。由于我上面的第 3 条子弹,问题就潜入了。将函数名称更改为remove_CRs。 :)
      • 建议使用 print 是个好主意 - 谢谢。
      猜你喜欢
      • 1970-01-01
      • 2018-05-01
      • 2023-03-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-01
      相关资源
      最近更新 更多