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

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

    To be an iterator an object must pass three tests:

    • obj has an __iter__ method
    • obj has a next method (or __next__ in Python 3)
    • obj.__iter__() returns obj

    So, a roll-your-own test would look like:

    def is_iterator(obj):
        if (
                hasattr(obj, '__iter__') and
                hasattr(obj, 'next') and      # or __next__ in Python 3
                callable(obj.__iter__) and
                obj.__iter__() is obj
            ):
            return True
        else:
            return False
    

提交回复
热议问题