python - 有什么方法可以捕获 "too many values to unpack"错误吗?

标签 python

我的元组子类的用法:

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/

相关文章:

python - 行和列的 ndarray 字段名称?

python - 迭代多个Excel文件,使用python将特定单元格保存到数据框中

python - 从他们输入的名字中显示一个人的首字母大写字母

python - asyncio.ensure_future vs. BaseEventLoop.create_task vs. 简单协程?

Python - 将数据拆分为 n 个分层部分

python - 如何使用两个不同的用户运行 selenium webdriver?

python - ValueError : Expected 2D array,得到一维数组而不是: array=[0. 31818181 0.40082645 0.49173555 ... 0.14049587 0.14876033 0.15289256]

python - 使用 pandas 获取该行中第一个非零值的列名

python - 使用单词列表计算列表中的特定单词

python - 更新 python 模块