如何确定 Python 类型错误的原因
How can I determine the reason for a Python Type Error
我目前正在使用 try/except
块尽可能将特定变量视为可迭代变量,但在它不可迭代时以不同但正确的方式处理它。
我的问题是抛出 TypeException 的原因可能不是尝试使用不可迭代对象进行迭代。我的检查是使用附加到 TypeException 的消息来确保这是原因,而不是类似于不受支持的操作数。
但作为异常一部分的消息已被弃用。那么,如何检查我的 TypeException 的原因?
为了完整起见,我使用的代码与此非常相似:
try:
deref = [orig[x].value.flatten() for x in y]
except TypeError as ex:
if "object is not iterable" in ex.message:
x = y
deref = [orig[x].value.flatten()]
else:
raise
将抛出您感兴趣的异常的部分与抛出无关异常的部分分开:
try:
iterator = iter(y)
except TypeError:
handle_that()
else:
do_whatever_with([orig[x].value.flatten() for x in iterator])
如果适合您的用例,最好的方法是使用 collections.Iterable
。因为这是一项如此常见的任务,所以我倾向于将其包装在一个函数中:
from collections import Iterable
def iterify(obj):
return obj if isinstance(obj, Iterable) else [obj]
deref = [orig[x].value.flatten() for x in iterify(y)]
但请注意 documentation:
Checking isinstance(obj, Iterable)
detects classes that are registered
as Iterable or that have an __iter__()
method, but it does not detect
classes that iterate with the __getitem__()
method. The only reliable
way to determine whether an object is iterable is to call iter(obj)
.
我目前正在使用 try/except
块尽可能将特定变量视为可迭代变量,但在它不可迭代时以不同但正确的方式处理它。
我的问题是抛出 TypeException 的原因可能不是尝试使用不可迭代对象进行迭代。我的检查是使用附加到 TypeException 的消息来确保这是原因,而不是类似于不受支持的操作数。
但作为异常一部分的消息已被弃用。那么,如何检查我的 TypeException 的原因?
为了完整起见,我使用的代码与此非常相似:
try:
deref = [orig[x].value.flatten() for x in y]
except TypeError as ex:
if "object is not iterable" in ex.message:
x = y
deref = [orig[x].value.flatten()]
else:
raise
将抛出您感兴趣的异常的部分与抛出无关异常的部分分开:
try:
iterator = iter(y)
except TypeError:
handle_that()
else:
do_whatever_with([orig[x].value.flatten() for x in iterator])
如果适合您的用例,最好的方法是使用 collections.Iterable
。因为这是一项如此常见的任务,所以我倾向于将其包装在一个函数中:
from collections import Iterable
def iterify(obj):
return obj if isinstance(obj, Iterable) else [obj]
deref = [orig[x].value.flatten() for x in iterify(y)]
但请注意 documentation:
Checking
isinstance(obj, Iterable)
detects classes that are registered as Iterable or that have an__iter__()
method, but it does not detect classes that iterate with the__getitem__()
method. The only reliable way to determine whether an object is iterable is to calliter(obj)
.