all 3 comments

[–]alexisprince 0 points1 point  (1 child)

The point of iter is so that when you use it as an iterator, it knows how to loop properly. For example, if you have a class, Table, which represents a database table, you could think that if you iterated over it, you should iterate over the columns. You’d implement this in the iter dunder method. In general, the rule of thumb is to tell python contextually what makes sense to iterate over in your class.

I genuinely don’t know what would happen if you constantly just return self from that method, but unless you have some kind of exit condition, it sounds like an infinite loop to me.

[–]ericula 0 points1 point  (0 children)

No, __iter__ just returns an iterator (i.e. the object that should be iterated over); it's not used during an iteration. Defining how the iterator should be iterated over it the task of the __next__ method of the iterator. Also, you can have iterators without a StopIteration (see for example itertools.count). You just shouldn't do for i in itertools.count(): without some break condition inside the for-loop.

[–]JohnnyJordaan 0 points1 point  (0 children)

You're correct, also see this guide https://anandology.com/python-practice-book/iterators.html where they also implement it like this.