Skip to content

Instantly share code, notes, and snippets.

@newlawrence
Last active January 13, 2017 14:51
Show Gist options
  • Save newlawrence/8aa5baf388428bd617ce19e2535b34d8 to your computer and use it in GitHub Desktop.
Save newlawrence/8aa5baf388428bd617ce19e2535b34d8 to your computer and use it in GitHub Desktop.
A simple decorator to define memoized properties in Python
import weakref
class memoized_property(property):
def __init__(self, *args, **kwargs):
super(memoized_property, self).__init__(*args, **kwargs)
self.data = weakref.WeakKeyDictionary()
def __get__(self, instance, owner=None):
result = self.data.get(instance, None) if instance is not None else None
if result is None:
result = super(memoized_property, self).__get__(instance, owner)
if instance is not None:
self.data[instance] = result
return result
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment