How can I check if an object is an iterator in Python?

前端 未结 8 1700
天命终不由人
天命终不由人 2020-12-25 10:10

I can check for a next() method, but is that enough? Is there an ideomatic way?

8条回答
  •  隐瞒了意图╮
    2020-12-25 11:03

    An object is iterable if it implements the iterator protocol.
    You could check the presence of __iter__() method with:

    hasattr(object,'__iter__')
    

    in Python 2.x this approach misses str objects and other built-in sequence types like unicode, xrange, buffer. It works in Python 3.

    Another way is to test it with iter method :

    try:
       iter(object)
    except TypeError:
       #not iterable
    

提交回复
热议问题