【问题标题】:Python KeyError and ValueError inconsistency?Python KeyError 和 ValueError 不一致?
【发布时间】:2015-10-15 21:03:18
【问题描述】:

我发现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' 

【问题讨论】:

    标签: python keyerror


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-04-04
      • 1970-01-01
      • 2016-09-19
      • 2018-01-23
      • 1970-01-01
      • 1970-01-01
      • 2015-04-12
      相关资源
      最近更新 更多