I am trying to understand how the for x in y
statement works in python. I found the documentation here: https://docs.python.org/3/reference/compound_stmts.html#for. It says that the expression y
is evaluated once and must yield an iterable object.
The following code prints the numbers 1,2,3,4,5 even though my class does not implement __iter__
(which is my understanding of being an iterable).
class myclass:
def __init__(self):
self.x = [1,2,3,4,5]
def __getitem__(self,index):
return self.x[index]
m = myclass()
for i in m:
print(i)
I know that there is a built-in method iter()
that returns an iterator for a sequence object using its .__getitem__()
function and a counter that starts at 0.
My guess is that python is calling the iter()
function on the expression y
in the for x in y
statement. So it is converting my object that implements .__getitem__
into an iterator, and when my object raises a IndexError
exception during the .__getitem__
call, the iterator turns this into a StopIteration
exception, and the for loop ends.
Is this correct? Right or wrong, is this explained in the documentation somewhere, or do I need to go look inside the source code of the implementation?