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
注: 「collections.abc」の代わりに「collections」から ABC を使用またはインポートすることは、Python 3.3 以降では非推奨であり、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.
許可を求めるより許しを求める方が簡単です。