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

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

    try:
      #treat object as iterable
    except TypeError, e:
      #object is not actually iterable
    

    Don't run checks to see if your duck really is a duck to see if it is iterable or not, treat it as if it was and complain if it wasn't.

提交回复
热议问题