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

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

    I often find convenient, inside my scripts, to define an iterable function. (Now incorporates Alfe's suggested simplification):

    import collections
    
    def iterable(obj):
        return isinstance(obj, collections.Iterable):
    

    so you can test if any object is iterable in the very readable form

    if iterable(obj):
        # act on iterable
    else:
        # not iterable
    

    as you would do with thecallable function

    EDIT: if you have numpy installed, you can simply do: from numpy import iterable, which is simply something like

    def iterable(obj):
        try: iter(obj)
        except: return False
        return True
    

    If you do not have numpy, you can simply implement this code, or the one above.

提交回复
热议问题