我的元组子类的用法:
class MyTuple(tuple):
def __new__(cls, columns=()):
return tuple.__new__(cls, tuple(columns))
a, b = MyTuple(columns=('hello', 'world', 42))
给出以下异常:
Traceback (most recent call last):
File "<stdin>", line 6, in <module>
ValueError: too many values to unpack
ValueError
可能有多种原因,所以我需要使用以下方法来捕获它吗?
try:
a, b = MyTuple(columns=('hello', 'world', 42))
except ValueError as e:
if not str(e).endswith('unpack'):
raise # false alarm
# handle unpacking error here..
这看起来相当不雅..有什么方法可以覆盖元组解包引发的异常吗?
更新:实际用例如下
>>> dice = FactSet()
>>> for i in range(1, 7):
... dice.add('dice', n=i)
...
>>> print dice.n + dice.n == 10 # give me all combinations that add up to 10
XPROD((dice(n=4), dice(n=6))
(dice(n=5), dice(n=5))
(dice(n=6), dice(n=4)))
>>> a, b = dice.n + dice.n == 10 # same as above, but unpack the individual die
>>> a
FactSet([
dice(n=4),
dice(n=5),
dice(n=6),
])
>>> b
FactSet([
dice(n=6),
dice(n=5),
dice(n=4),
])
>>> a, b = dice.n + dice.n == 13 # no result should probably raise a more specific exception?
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: need more than 0 values to unpack
>>> ab = dice.n + dice.n == 13 # this is much more awkward and forces you to deal with the error in-situ (which might not be what you wanted)
>>> if ab:
>>> a, b = ab
最佳答案
而不是做:
a, b = <expression>
做:
value = <expression>
try:
a, b = value
except ValueError:
...
这是解决此类问题的一般方法:当您的语句可能出于多种原因引发同一类型的异常时,只需将语句分成多个部分,将“关键”部分与代码的其余部分隔离开来.
Is there any way I can override which exception the tuple unpacking raises?
没有。异常不是由 tuple
对象引发的,它是由 Python 解释器引发的。当您执行:a, b, ..., z = something
时,解释器将在幕后执行以下代码:
it = iter(something)
try:
a = next(it)
b = next(it)
...
z = next(it)
except StopIteration:
raise ValueError('need more than X values to unpack')
try:
next(it)
except StopIteration:
pass
else:
raise ValueError('too many values to unpack (expected Y)')
如您所见,元组(或一般情况下的可迭代对象)仅被迭代。它不知道发生了什么。
正如您在阅读 CPython's source code 中看到的那样,这些异常是硬编码的,不能被“覆盖”。
关于python - 有什么方法可以捕获 "too many values to unpack"错误吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32317254/