How does one check if a Python object supports iteration, a.k.a an iterable object (see definition
Ideally I would like function similar to isiterable(p_object) returning True or False (modelled after isinstance(p_object, type)).
How does one check if a Python object supports iteration, a.k.a an iterable object (see definition
Ideally I would like function similar to isiterable(p_object) returning True or False (modelled after isinstance(p_object, type)).
You can check for this using isinstance and collections.Iterable
>>> from collections.abc import Iterable # for python >= 3.6
>>> l = [1, 2, 3, 4]
>>> isinstance(l, Iterable)
True
Note: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated since Python 3.3, and in 3.9 it will stop working.
str is also iterable. So if you're thinking tuple, list, set.. it might be better to just check for those 3 typesfrom collections.abc import Iterable as importing the ABCs from collections is depracated since Python 3.3You don't "check". You assume.
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.
It's easier to ask forgiveness than to ask permission.
if not iterable: [obj] to assert that something is ALWAYS iterable. More likely to make for cleaner code imo.TypeError in “the real work” without a way to distinguish between the two.isinstance(x, Iterable) would be better from that point of view. (In Python, however, one must be careful with strings and bytestrings if you're considering those to be "single" values.)