Is there a method like isiterable
? The only solution I have found so far is to call
hasattr(myObj, \'__iter__\')
But I am not
try:
iterator = iter(theElement)
except TypeError:
# not iterable
else:
# iterable
# for obj in iterator:
# pass
Use the Abstract Base Classes. They need at least Python 2.6 and work only for new-style classes.
from collections.abc import Iterable # import directly from collections for Python < 3.3
if isinstance(theElement, Iterable):
# iterable
else:
# not iterable
However, iter()
is a bit more reliable as described by the 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)
.