Skip to content

Instantly share code, notes, and snippets.

@malthe
Created February 24, 2012 18:58
Show Gist options
  • Save malthe/1902962 to your computer and use it in GitHub Desktop.
Save malthe/1902962 to your computer and use it in GitHub Desktop.
Cached property in Python with invalidation
import functools
_invalid = object()
def cached_property(_get, _set, _del=None):
name = _get.__name__
mangled = "_" + name
@functools.wraps(_get)
def cached_get(inst):
d = inst.__dict__
try:
value = d[mangled]
if value is not _invalid:
return value
except KeyError:
pass
value = _get(inst)
d[mangled] = value
return value
@functools.wraps(_set)
def set_and_invalidate_cache(inst, value):
_set(inst, value)
d = inst.__dict__
d[mangled] = _invalid
@functools.wraps(_del)
def del_and_invalidate_cache(inst, value):
_del(inst, value)
d = inst.__dict__
d[mangled] = _invalid
return property(
cached_get,
set_and_invalidate_cache,
del_and_invalidate_cache if _del is not None else None,
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment