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

前端 未结 21 2197
太阳男子
太阳男子 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:53

    The easiest way, respecting the Python's duck typing, is to catch the error (Python knows perfectly what does it expect from an object to become an iterator):

    class A(object):
        def __getitem__(self, item):
            return something
    
    class B(object):
        def __iter__(self):
            # Return a compliant iterator. Just an example
            return iter([])
    
    class C(object):
        def __iter__(self):
            # Return crap
            return 1
    
    class D(object): pass
    
    def iterable(obj):
        try:
            iter(obj)
            return True
        except:
            return False
    
    assert iterable(A())
    assert iterable(B())
    assert iterable(C())
    assert not iterable(D())
    

    Notes:

    1. It is irrelevant the distinction whether the object is not iterable, or a buggy __iter__ has been implemented, if the exception type is the same: anyway you will not be able to iterate the object.
    2. I think I understand your concern: How does callable exists as a check if I could also rely on duck typing to raise an AttributeError if __call__ is not defined for my object, but that's not the case for iterable checking?

      I don't know the answer, but you can either implement the function I (and other users) gave, or just catch the exception in your code (your implementation in that part will be like the function I wrote - just ensure you isolate the iterator creation from the rest of the code so you can capture the exception and distinguish it from another TypeError.

提交回复
热议问题