Is there a method like isiterable? The only solution I have found so far is to call
hasattr(myObj, '__iter__')
But I am not sure how fool-proof this is.
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Checking for
__iter__works on sequence types, but it would fail on e.g. strings in Python 2. I would like to know the right answer too, until then, here is one possibility (which would work on strings, too):The
iterbuilt-in checks for the__iter__method or in the case of strings the__getitem__method.Another general pythonic approach is to assume an iterable, then fail gracefully if it does not work on the given object. The Python glossary:
The
collectionsmodule provides some abstract base classes, which allow to ask classes or instances if they provide particular functionality, for example:However, this does not check for classes that are iterable through
__getitem__.