Python KeyError 和ValueError 不一致?

Python KeyError and ValueError inconsistency?

我发现 ValueErrorKeyError 之间存在不一致。前者会将 \n 视为换行符;后者将其视为原始文本。这种行为是 normal/expected 吗?

TeX_dict 是一个字典,用于将部分字典键转换为生成图时使用的 TeX 格式字符串。 part 就是其中之一。以下是 part 的两个示例:

当我提出 ValueError 时,\n 换行符生成一个新行。当我提出 KeyError 时,他们没有提出。

geo_split = lambda thing: '\&'.join([
                                      TeX_dict[x]
                                      for x in thing.split('&')
                                    ])

try:

    TeX = geo_split(part)

except KeyError:

    msg = ("You have programmed limited functionality for "
           "geometric mean keys. They can only handle species "
           "that are hard coded into "
           "``pccv.TeX_labels.axis_labels``.\n\n" #
           "The following part failed: {}\n"
          ).format(part)

    raise ValueError(msg) # If this is KeyError, the new lines don't print.

以下是每个示例的输出:

ValueError: You have programmed limited functionality for geometric mean keys. 
They can only handle species that are hard coded into 
``pccv.TeX_labels.axis_labels``.

KeyError: 'You have programmed limited functionality for geometric mean keys. 
They can only handle species that are hard coded into 
``pccv.TeX_labels.axis_labels``.\n\nThe following part failed: a,p1&p2\n' 

这是 KeyError 实现的一个特点。

/* If args is a tuple of exactly one item, apply repr to args[0].
   This is done so that e.g. the exception raised by {}[''] prints
     KeyError: ''
   rather than the confusing
     KeyError
   alone.  The downside is that if KeyError is raised with an explanatory
   string, that string will be displayed in quotes.  Too bad.
   If args is anything else, use the default BaseException__str__().

您可以通过传递覆盖 __repr__:

的内容来解决它
class Wrapper(str):
    def __repr__(self):
        return str(self)

raise KeyError(Wrapper('hello\nthere'))