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

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

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

8条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-25 10:54

    answer from python sourcecode doc comments:

    {python install path}/Versions/3.5/lib/python3.5/types.py

    # Iterators in Python aren't a matter of type but of protocol.  A large
    # and changing number of builtin types implement *some* flavor of
    # iterator.  Don't check the type!  Use hasattr to check for both
    # "__iter__" and "__next__" attributes instead.
    

提交回复
热议问题