gpt4 book ai didi

Python KeyError 和 ValueError 不一致?

转载 作者:行者123 更新时间:2023-12-05 03:12:36 25 4
gpt4 key购买 nike

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

最佳答案

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

关于Python KeyError 和 ValueError 不一致?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33158501/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com