Is there a method like isiterable
? The only solution I have found so far is to call
hasattr(myObj, \'__iter__\')
But I am not
According to the Python 2 Glossary, iterables are
all sequence types (such as
list
,str
, andtuple
) and some non-sequence types likedict
andfile
and objects of any classes you define with an__iter__()
or__getitem__()
method. Iterables can be used in a for loop and in many other places where a sequence is needed (zip(), map(), ...). When an iterable object is passed as an argument to the built-in function iter(), it returns an iterator for the object.
Of course, given the general coding style for Python based on the fact that it's “Easier to ask for forgiveness than permission.”, the general expectation is to use
try:
for i in object_in_question:
do_something
except TypeError:
do_something_for_non_iterable
But if you need to check it explicitly, you can test for an iterable by hasattr(object_in_question, "__iter__") or hasattr(object_in_question, "__getitem__")
. You need to check for both, because str
s don't have an __iter__
method (at least not in Python 2, in Python 3 they do) and because generator
objects don't have a __getitem__
method.