pydanny/cached-property

Caching GeneratorType results

veyesecurity opened this issue · 1 comments

Please consider the example below:

class Foo(object):
    def __init__(self, items):
        self.items = items

    @cached_property
    def squares(self):
        for item in self.items:
            yield item * item


foo = Foo([1, 2, 3])
print list(foo.squares)
print list(foo.squares)

It will produce the following output:

[1, 4, 9]
[]

To fix this we have modified cached_property decorator:

class cached_property(object):

    def __init__(self, func):
        self.func = func

    def __get__(self, obj, cls):
        value = self.func(obj)
        if isinstance(value, GeneratorType):
            value = list(value)
        obj.__dict__[self.func.__name__] = value
        return value

But now we loose the laziness of the method and also change its return type. Do you have in mind any elegant way to implement cached decorator that will cache items yielded so far, so when the property will be called second time it will first yield cached items and then continue with items yielded by the original (cached) method?

Not closing yet this as it adds excellent historical context for any work done on #100. Thanks @veyesecurity!