I realised I still don't quite understand how to implement an iterator class. So a class where one can "for-loop" over some of its contents.
I have looked at these answers (I still don't get it):
What exactly are Python's iterator, iterable, and iteration protocols?
As far as I understand, an iterable is one that implements __iter__
and returns an iterator which is something that has __next__
implemented.
From this I somehow understood that if I want my class to be an iterator, and iterable. I must define __iter__
to return self, and have __next__
defined. Am I wrong so far?
Here is a scaffold for my class:
class Wrapper:
def __init__(self, low, high):
self.store = OrderedDict() # it is imported (ommited)
def __getitem__(self, key):
return self.store[key]
def __iter__(self):
return self
# Option 3
return self.store
def __next__(self):
# Option 1
for key in self.store:
return key
# Option 2
for key in self.store.keys():
return key
Tried the above options, none worked. :(
What happens is I have some py.tests prepared to test the iteration if it works correctly, just a simple for loop, nothing fancy. And the tests just run forever (or longer then my patience < 5 min), but the mock class has 5 items, so it should not take long.
What am I doing wrong?