Last active
January 13, 2017 14:51
-
-
Save newlawrence/8aa5baf388428bd617ce19e2535b34d8 to your computer and use it in GitHub Desktop.
A simple decorator to define memoized properties in Python
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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