Created
February 24, 2012 18:58
-
-
Save malthe/1902962 to your computer and use it in GitHub Desktop.
Cached property in Python with invalidation
This file contains 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 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