Определить атрибут, который содержит длину, и вернуть его для __len__
.
def generator2iterator(generator, length=None):
class Iterator(object):
def __iter__(self):
for i, e in enumerate(generator(), 1):
self._len = i
yield e
#self.__len__ = types.MethodType(lambda self: i, self)
def __len__(self):
if not hasattr(self, '_len'):
raise TypeError("object of type 'Iterator' has no defined len() yet.")
return self._len
return Iterator()
# examples:
## define a generator with 10 elements
def g():
for i in range(10):
yield i
# pass it to the iterator
it = generator2iterator(g)
# check len
len(it)
TypeError: object of type 'Iterator' has no defined len() yet.
# run the iterator
for _ in it:
pass
# check the length
len(it)
# returns:
10