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

前端 未结 21 2231
太阳男子
太阳男子 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 01:03

    Kinda late to the party but I asked myself this question and saw this then thought of an answer. I don't know if someone already posted this. But essentially, I've noticed that all iterable types have __getitem__() in their dict. This is how you would check if an object was an iterable without even trying. (Pun intended)

    def is_attr(arg):
        return '__getitem__' in dir(arg)
    

提交回复
热议问题