diff options
author | prettyboy <prettyboy@yandex-team.com> | 2022-12-20 18:29:21 +0300 |
---|---|---|
committer | prettyboy <prettyboy@yandex-team.com> | 2022-12-20 18:29:21 +0300 |
commit | 0f48a8e8854b8a279fe20ef415dcf58103207fbb (patch) | |
tree | 30cd244159c404e4bebcff16536e60b83b79fcf7 /library/python/func | |
parent | f37198778abfc9966a20b45117657a92c31d0e17 (diff) | |
download | ydb-0f48a8e8854b8a279fe20ef415dcf58103207fbb.tar.gz |
[library/python/func] Made lazy and lazy_property thread safe
Diffstat (limited to 'library/python/func')
-rw-r--r-- | library/python/func/__init__.py | 22 |
1 files changed, 17 insertions, 5 deletions
diff --git a/library/python/func/__init__.py b/library/python/func/__init__.py index 7424361635..12a280bddc 100644 --- a/library/python/func/__init__.py +++ b/library/python/func/__init__.py @@ -20,14 +20,20 @@ class _Result(object): def lazy(func): result = _Result() + lock = threading.Lock() + @functools.wraps(func) def wrapper(*args): try: return result.result except AttributeError: - result.result = func(*args) + with lock: + try: + return result.result + except AttributeError: + result.result = func(*args) - return result.result + return result.result return wrapper @@ -35,11 +41,17 @@ def lazy(func): def lazy_property(fn): attr_name = '_lazy_' + fn.__name__ + lock = threading.Lock() + @property def _lazy_property(self): - if not hasattr(self, attr_name): - setattr(self, attr_name, fn(self)) - return getattr(self, attr_name) + if hasattr(self, attr_name): + return getattr(self, attr_name) + + with lock: + if not hasattr(self, attr_name): + setattr(self, attr_name, fn(self)) + return getattr(self, attr_name) return _lazy_property |