4

In this question there are numerous ways to test for an iterable. Two of the solutions are:

  1. hasattr(object, '__iter__')
  2. isinstance(object, collections.Iterable)

They both seem to do the same thing and I can't find any doc that differentiates them. What is the difference and why would I choose one over the other?

1
  • 1
    3. Try and iterate it and catch the exception if it fails. Commented Dec 20, 2018 at 16:09

1 Answer 1

4

The pythonic way is

  • assume it is iterable
  • catch the exception if it is not

However, use it with common sense. That's, do it only if you have reason to believe that your object is iterable in the majority of cases.

Also, take care of strings, which are treated as iterables, but in most practical use cases, they should not be. In that case, the practice is to explicitly check isinstance(.., str)

Sign up to request clarification or add additional context in comments.

3 Comments

This follows the EAFP principle in Python.
@AndrewF: exactly. however, common sense should dictate whether that's appropriate, depending on the context
@blue_note the question has been edited for clarity.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.