Python KeyError和ValueError的不一致性?

3
我发现了ValueErrorKeyError之间的不一致性。前者将\n视为换行符;后者将其视为原始文本。这种行为是否正常/预期? TeX_dict是一个字典,用于将字典键的部分转换为TeX格式的字符串,在生成图时使用。 part是其中之一。以下是part的两个示例:
  • a&b成功拆分并转换为字典中的内容。
  • a,b&c则未能成功拆分。
当我引发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' 
1个回答

4

这是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'))

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接