contrapsych
contrapsych

Reputation: 1949

Should my iterable objects in Python also be the iterator like most examples

In most code examples of implementing __iter__ in Python, I see them returning self instead of another object. I know this is the required behavior for an iterator, but for an object that is an iterable, shouldn't it return something other than self?

My reasoning: (GIL Aside, not CPU bound)

Any example I have in mind is a class called Search that uses an HTTP REST API to initialize a search. Once it's done, you can do several things.

Overall, what's the most robust way to implement an iterator in idiomatic Python that is thread safe. Maybe I should even abstract the HTTP REST API to a cursor object like many database libraries (which would be like option 3).

Upvotes: 2

Views: 184

Answers (1)

Ethan Furman
Ethan Furman

Reputation: 69051

The __iter__ protocol needs to return an iterator -- that can be either the same object (self, and self needs to have a __next__ method), or another object (and that other object will have __iter__ and __next__).

In just about all non-trivial use cases, a different and dedicated object should be returned for the iterator as it makes the whole process much simpler, easier to reason about, more likely to be thread-safe, etc.

Upvotes: 3

Related Questions