I have a class in python, which has an iterable as instance variable. I want to iterate the instances of the class by iterating over the embedded iterable.
I implemented this as follows:
def __iter__(self):
return self._iterable.__iter__()
I don’t really feel that comfortable calling the __iter__() method on the iterable, as it is a special method. Is this how you would solve this problem in python or is there a more elegant solution?
The “best” way to way to delegate
__iter__would be:Alternately, it might be worth knowing about:
Which will let you fiddle with each item before returning it (ex, if you wanted
yield item * 2).And as @Lattyware mentions in the comments, PEP380 (slated for inclusion in Python 3.3) will allow:
Note that it may be tempting to do something like:
But this won’t work:
iter(foo)calls the__iter__method ontype(foo)directly, bypassingfoo.__iter__. Consider, for example:You would expect that
list(SurprisingIter())would return["a", "b", "c"], but it actually returns[1, 2, 3].