Skip to content

Instantly share code, notes, and snippets.

@kyleterry
Created February 1, 2013 18:58
Show Gist options
  • Save kyleterry/4693278 to your computer and use it in GitHub Desktop.
Save kyleterry/4693278 to your computer and use it in GitHub Desktop.
from functools import wraps
from django.conf import settings
class cached_property(object):
"""A read-only @property that is only evaluated once. The value is cached
on the object itself rather than the function or class; this should prevent
memory leakage."""
def __init__(self, fget, doc=None):
self.fget = fget
self.__doc__ = doc or fget.__doc__
self.__name__ = fget.__name__
self.__module__ = fget.__module__
def __get__(self, obj, cls):
if obj is None:
return self
result = self.fget(obj)
if settings.ENABLE_CACHED_PROPERTY:
obj.__dict__[self.__name__] = result
return result
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment