Updated implementation of cached property

Cached value of properties are stored
in instance's '__dict__'.
pull/21/head
Mišo Belica 11 years ago
parent 4e3227521e
commit cf781bc595

@ -4,17 +4,16 @@
def cached_property(getter):
"""
Decorator that converts a method into memoized property.
The decorator will work as expected only for immutable properties.
The decorator works as expected only for classes with
attribute '__dict__' and immutable properties.
"""
def decorator(self):
if not hasattr(self, "__cached_property_data"):
self.__cached_property_data = {}
key = "_cached_property_" + getter.__name__
key = getter.__name__
if key not in self.__cached_property_data:
self.__cached_property_data[key] = getter(self)
if not hasattr(self, key):
setattr(self, key, getter(self))
return self.__cached_property_data[key]
return getattr(self, key)
decorator.__name__ = getter.__name__
decorator.__module__ = getter.__module__

Loading…
Cancel
Save