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 functools
import itertools import itertools
from threading import Lock
def cached_property(fun): def cached_property(fun):
"""A memoize decorator for class properties.""" """A memoize decorator for class properties."""
lock = Lock()
locks = {}
@functools.wraps(fun) @functools.wraps(fun)
def get(self): def get(self):
with lock:
try: try:
return self._cache[fun] obj_lock = self._lock
except AttributeError: except AttributeError:
self._cache = {} obj_lock = self._lock = Lock()
with obj_lock:
try:
cache = self._cache
except AttributeError:
cache = self._cache = {}
try:
ret = cache[fun]
except KeyError: except KeyError:
pass ret = cache[fun] = fun(self)
ret = self._cache[fun] = fun(self)
return ret return ret
return property(get) return property(get)