When wrapping an (internal) iterator one often has to reroute the __iter__
method to the underlying iterable. Consider the following example:
class FancyNewClass(collections.Iterable):
def __init__(self):
self._internal_iterable = [1,2,3,4,5]
# ...
# variant A
def __iter__(self):
return iter(self._internal_iterable)
# variant B
def __iter__(self):
yield from self._internal_iterable
Is there any significant difference between variant A and B?
Variant A returns an iterator object that has been queried via iter()
from the internal iterable. Variant B returns a generator object that returns values from the internal iterable. Is one or the other preferable for some reason? In collections.abc
the yield from
version is used. The return iter()
variant is the pattern that I have used until now.