Home >Backend Development >Python Tutorial >How Can I Reliably Check if an Object is Iterable in Python?
Determining Object Iterability in Python
Iterating through a sequence of elements is a fundamental operation in Python. To determine whether an object supports iteration, one may wonder if there exists a straightforward method like isiterable.
hasattr(myObj, '__iter__')
The solution mentioned in the question, hasattr(myObj, '__iter__'), checks for the presence of the __iter__ method in the object. While it works for most sequence types, it falls short in Python 2 when handling strings.
Iter Built-in Function
A more foolproof approach is to use the iter built-in function. It attempts to call the __iter__ method of the object or the __getitem__ method in the case of strings, making it suitable for a broader range of iterables.
try: some_object_iterator = iter(some_object) except TypeError as te: print(some_object, 'is not iterable')
Duck Typing
Another Pythonic approach is to embrace duck typing. This involves assuming that an object is iterable and handling exceptions if it's not. The EAFP (Easier to Ask Forgiveness than Permission) style is often used for this:
try: _ = (e for e in my_object) except TypeError: print(my_object, 'is not iterable')
Collections Module
The Python collections module offers abstract base classes to check for class or instance iterability. However, these classes do not cover all cases, particularly iterables with __getitem__ methods.
from collections.abc import Iterable if isinstance(e, Iterable): # e is iterable
The above is the detailed content of How Can I Reliably Check if an Object is Iterable in Python?. For more information, please follow other related articles on the PHP Chinese website!