Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Caching GeneratorType results #34

Open
veyesecurity opened this issue Jun 16, 2016 · 1 comment
Open

Caching GeneratorType results #34

veyesecurity opened this issue Jun 16, 2016 · 1 comment

Comments

@veyesecurity
Copy link

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?

@pydanny
Copy link
Owner

pydanny commented Sep 30, 2018

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants