You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
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?
The text was updated successfully, but these errors were encountered:
Please consider the example below:
It will produce the following output:
To fix this we have modified
cached_property
decorator: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?
The text was updated successfully, but these errors were encountered: