dimanche 14 avril 2019

Dynamically add len method?

How do I add __len__(...) to an existing object in a way that len(...) likes?

The use case is remembering the length of a generator after its first iteration in a way that does not require writing/changing code in between the sites of the iterations.

Here is what I have so far:

def generator2iterator(generator, length=None):
    class Iterator(object):
        def __iter__(self):
            i = 0
            for e in generator():
                i += 1
                yield e
            #self.__len__ = types.MethodType(lambda self: i, self)
            self.__len__ = (lambda self: i).__get__(self)
    return Iterator()

def test_generator():
    yield 3

iterator = generator2iterator(test_generator)

print(list(iterator))
# [3]

print(iterator.__len__())
# 1

print(len(iterator))
# TypeError: object of type 'Foo' has no len()





Aucun commentaire:

Enregistrer un commentaire