Make cached_property thread-safe.
This commit is contained in:
parent
a7f10da92b
commit
20e8ce597d
1 changed files with 17 additions and 7 deletions
|
|
@ -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)
|
||||
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue