I can check for a next()
method, but is that enough? Is there an ideomatic way?
To be an iterator an object must pass three tests:
obj
has an __iter__
methodobj
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