Search code examples
pythoniteratoroverloading

Why does defining __getitem__ on a class make it iterable in python?


Why does defining __getitem__ on a class make it iterable?

For instance if I write:

class B:
    def __getitem__(self, k):
        return k
    
cb = B()
        
for k in cb:
    print k

I get the output:

0
1
2
3
4
5
...

I would really expect to see an error returned from for k in cb:.


Solution

  • If you take a look at PEP234 defining iterators, it says:

    1. An object can be iterated over with for if it implements __iter__() or __getitem__().

    2. An object can function as an iterator if it implements next().