如何检查 Python 对象是否支持迭代,也就是可迭代对象(见定义
理想情况下,我想要类似于isiterable(p_object)
返回 True 或 False 的函数(以 为模型isinstance(p_object, type)
)。
您可以使用isinstance
和collections.Iterable
>>> from collections.abc import Iterable # for python >= 3.6
>>> l = [1, 2, 3, 4]
>>> isinstance(l, Iterable)
True
注意:从 Python 3.3 开始,不推荐使用或从 'collections' 而不是从 'collections.abc' 导入 ABC,在 3.9 中它将停止工作。
试试这个代码
def isiterable(p_object):
try:
it = iter(p_object)
except TypeError:
return False
return True
你不“检查”。你假设。
try:
for var in some_possibly_iterable_object:
# the real work.
except TypeError:
# some_possibly_iterable_object was not actually iterable
# some other real work for non-iterable objects.
请求宽恕比请求许可更容易。