I don't understand exactly why the __iter__
special method just returns the object it's called on (if it's called on an iterator). Is it essentially just a flag indicating that the object is an iterator?
EDIT: Actually, I discovered that "This is required to allow both containers and iterators to be used with the for
and in
statements." https://docs.python.org/3/library/stdtypes.html#iterator.iter
Alright, here's how I understand it: When writing a for
loop, you're allowed to specify either an iterable or an iterator to loop over. But Python ultimately needs an iterator for the loop, so it calls the __iter__
method on whatever it's given. If it's been given an iterable, the __iter__
method will produce an iterator, and if it's been given an iterator, the __iter__
method will likewise produce an iterator (the original object given).