how to customize implementation of the for in statement

Question:

When we implement our own obj in python which support for i in obj statement, what magic method we need to create?

Is there a link to the official document that I can check?

During my reading of some other’s source code, I found there’s a __getitem__ method, it has a signatue of __getitem__(slef, index), then when we instantiate an object of this class, and call

for i in obj:
   print(i)

what method would python try to find and pass what argument?

Asked By: Allen Huang

||

Answers:

You can make a class iterable by implementing

  • __getitem, it’ll receive ints starting at 0, your code needs to raise a IndexError to stop it

    class Foo:
        def __getitem__(self, item):
            if isinstance(item, int) and item > 10:
                raise IndexError
            return item * 2
    
  • __iter__ and __next__

    class Foo:
    
        def __init__(self):
            self.counter = 0
    
        def __iter__(self):
            return self
    
        def __next__(self):
            if self.counter > 10:
                raise StopIteration
            result = self.counter * 2
            self.counter += 1
            return result
    

Both leads to same output

for i in Foo():
    print(i)

0
2
4
6
8
10
12
14
16
18
20
Answered By: azro
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.