Make cached_property thread-safe.

This commit is contained in:
Andrey Golovizin 2014-08-27 21:58:59 +02:00
parent a7f10da92b
commit 20e8ce597d

View file

@ -16,19 +16,29 @@
import functools
import itertools
from threading import Lock
def cached_property(fun):
"""A memoize decorator for class properties."""
lock = Lock()
locks = {}
@functools.wraps(fun)
def get(self):
try:
return self._cache[fun]
except AttributeError:
self._cache = {}
except KeyError:
pass
ret = self._cache[fun] = fun(self)
with lock:
try:
obj_lock = self._lock
except AttributeError:
obj_lock = self._lock = Lock()
with obj_lock:
try:
cache = self._cache
except AttributeError:
cache = self._cache = {}
try:
ret = cache[fun]
except KeyError:
ret = cache[fun] = fun(self)
return ret
return property(get)