-3

Why do we return self in the iter method when we define the next method in the iterable and iterator classes?

This topic was taught in the course, but it was hard to understand and I didn't understand why we had to return self.

class PowTwo:
    def __init__(self, max_pow):
        self.n = 0
        self.max_pow = max_pow

    def __iter__(self):
        return self # What's the purpose?

    def __next__(self):
        if self.n <= self.max_pow:
            result = self.n ** 2
            self.n += 1
            return result
        else:
            raise StopIteration
    n = PowTwo(5)
    for i in n:
        print(i)
2

1 Answer 1

1

The __iter__ function returns a reference to the object that provides the __next__ functionality which may or may not be self.

Here's a contrived example that shows two classes. Foo is iterable but Reader provides the underlying functionality.

class Reader:
    def __init__(self, filename):
        self._fd = open(filename)

    def __next__(self):
        if line := self._fd.readline():
            return line
        self._fd.close()
        raise StopIteration


class Foo:
    def __init__(self, filename):
        self._filename = filename

    def __iter__(self):
        return Reader(self._filename)


for line in Foo("foo.txt"):
    print(line)
Sign up to request clarification or add additional context in comments.

3 Comments

Reader is required to have __iter__ as well, see Iterator Types.
@KellyBundy Interesting that it works without it. If __iter__ was implemented, what would it return? self? Is there a context in which the code in this answer might not work?
Yes, like the doc says: "Return the iterator object itself". It won't work if you for example do it = iter(Foo("foo.txt")) and then try to iterate that with for line in it or list(it) or zip(it, it) etc. Also see this recent issue about something like this no longer working even without an explicit iter().

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.