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

iterator, overloading, python

Solution

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

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

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

Problem

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:`.

Original source