Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does a Python Iterator need an iter method that simply returns self?

I understand that the standard says that it does but I am trying to find the underlying reason for this.

If it simply always returns self what is the need for it?

You clearly always have access to the object since you are calling iter on that object, so what's the need for having it?

like image 206
Sid Avatar asked Jan 24 '14 22:01

Sid


1 Answers

Imagine you want to write code that iterates over any kind of iterable. Normally you'd just write a for statement or comprehension, but let's instead explicitly do what for does under the covers, to make things more obvious:

i = iter(iterable)
while True:
    try:
        val = next(i)
    except StopIteration:
        break
    else:
        do_stuff(val)

If you don't do that first line, your code won't work with lists, strings, tuples, or anything but iterator.

But if you do that first line, well, iter(iterable) had better return an iterator, or your code won't work with iterators.


You may wonder why iter couldn't just do the right thing without this? After all, it does have magic in it to create an iterator when given an object that has a __len__ and __getitem__ but no __iter__, so why couldn't it also have magic to just return its argument if it has a __next__ but no __iter__? That's a language-design issue, but generally, Python tries to have as little magic as possible. The magic to make not-quite-sequences iterable was necessary because such sequences existed (in widespread third-party code) before the iteration protocol was added to the language, and it would be too hard to remove for the small benefit of simplifying things.

like image 162
abarnert Avatar answered Oct 27 '22 11:10

abarnert