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

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

    Since Python 3.5 you can use the typing module from the standard library for type related things:

    from typing import Iterable
    
    ...
    
    if isinstance(my_item, Iterable):
        print(True)
    

提交回复
热议问题