Skip to content

Instantly share code, notes, and snippets.

@ljwolf

ljwolf/getset.py Secret

Created July 25, 2015 00:53
Show Gist options
  • Save ljwolf/f90b85f7901a5367d00c to your computer and use it in GitHub Desktop.
Save ljwolf/f90b85f7901a5367d00c to your computer and use it in GitHub Desktop.
Get/set with cache (needs decorator)
@property
def cached_foo(self):
try:
return self._cache[foo]
except AttributeError:
self._cache = {}
self._cache[foo] = calculate_foo()
except KeyError:
self._cache[foo] = calculate_foo()
return self._cache[foo]
@cached_foo.setter
def cached_foo(self, bar):
try:
self._cache[foo] = bar
except AttributeError:
self._cache = {}
self._cache[foo] = bar
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment