为什么 Python 在 __doc__ 中不自动转义 '\'?

Why doesn't Python auto escape '\' in __doc__?

似乎某些转义字符在文档字符串中仍然很重要。例如,如果我们 运行 python foo.py (Python 2.7.10),它会发出类似 ValueError: invalid \x escape.

的错误
def f():
    """
    do not deal with '\x0'
    """
    pass

实际上,正确的文档应该是:

    """
    do not deal with '\\x0'
    """

此外,它还会影响 import

对于Python 3.4.3+,错误信息是:

  File "foo.py", line 4
    """
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 24-25: truncated \xXX escape

我觉得有点奇怪,因为我认为它只会影响 __doc__ 而对模块本身没有副作用。

为什么设计成这样?它是 Python 中的 flaw/bug 吗?

注意

我知道 """ 和原始文字的含义,但是我认为 python 解释器应该能够特别处理文档字符串,至少在理论上是这样。

来自PEP 257

For consistency, always use """triple double quotes""" around docstrings. Use r"""raw triple double quotes""" if you use any backslashes in your docstrings. For Unicode docstrings, use u"""Unicode triple-quoted strings""" .

There are two forms of docstrings: one-liners and multi-line docstrings.


也来自here

There's no such python type as "raw string" -- there are raw string literals, which are just one syntax approach (out of many) to specify constants (i.e., literals) that are of string types.

So "getting" something "as a raw string" just makes no sense. You can write docstrings as raw string literals (i.e., with the prefix r -- that's exactly what denotes a raw string literal, the specific syntax that identifies such a constant to the python compiler), or else double up any backslashes in them (an alternative way to specify constant strings including backslash characters), but that has nothing to do with "getting" them one way or another.