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

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

    This isn't sufficient: the object returned by __iter__ must implement the iteration protocol (i.e. next method). See the relevant section in the documentation.

    In Python, a good practice is to "try and see" instead of "checking".

提交回复
热议问题