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

前端 未结 8 1886
天命终不由人
天命终不由人 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 10:47

    There is a better method than other answers have suggested.

    In Python we have two kinds of things: Iterable and Iterator. An object is Iterable if it can give you Iterator. It does so when you use iter() on it. An object is Iterator if you can use next() to sequentially browse through its elements. For example, map() returns Iterator and list is Iterable.

    Here are more details.

    Below code illustrates how to check for these types:

    from collections.abc import Iterable, Iterator
    
    r = [1, 2, 3]
    e = map(lambda x:x, r)
    
    print(isinstance(r, Iterator)) # False, because can't apply next
    print(isinstance(e, Iterator)) # True
    print(isinstance(r, Iterable)) # True, because can apply iter()
    print(isinstance(e, Iterable)) # True, note iter() returns self
    

提交回复
热议问题