In Python, how do I determine if an object is iterable?

前端 未结 21 2211
太阳男子
太阳男子 2020-11-22 00:35

Is there a method like isiterable? The only solution I have found so far is to call

hasattr(myObj, \'__iter__\')

But I am not

21条回答
  •  独厮守ぢ
    2020-11-22 00:49

    Duck typing

    try:
        iterator = iter(theElement)
    except TypeError:
        # not iterable
    else:
        # iterable
    
    # for obj in iterator:
    #     pass
    

    Type checking

    Use the Abstract Base Classes. They need at least Python 2.6 and work only for new-style classes.

    from collections.abc import Iterable   # import directly from collections for Python < 3.3
    
    if isinstance(theElement, Iterable):
        # iterable
    else:
        # not iterable
    

    However, iter() is a bit more reliable as described by the documentation:

    Checking isinstance(obj, Iterable) detects classes that are registered as Iterable or that have an __iter__() method, but it does not detect classes that iterate with the __getitem__() method. The only reliable way to determine whether an object is iterable is to call iter(obj).

提交回复
热议问题