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?

E.Beach
  • 1,829
  • 2
  • 22
  • 34

1 Answers1

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)

blue_note
  • 27,712
  • 9
  • 72
  • 90