Debian Codegraph @

lib/ansible/utils/lock.py

raw
1 # Copyright (c) 2020 Matt Martz <[email protected]>
2 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
3
4 from __future__ import annotations
5
6 from functools import wraps
7
8
9 def lock_decorator(attr='missing_lock_attr', lock=None):
10 """This decorator is a generic implementation that allows you
11 to either use a pre-defined instance attribute as the location
12 of the lock, or to explicitly pass a lock object.
13
14 This code was implemented with ``threading.Lock`` in mind, but
15 may work with other locks, assuming that they function as
16 context managers.
17
18 When using ``attr``, the assumption is the first argument to
19 the wrapped method, is ``self`` or ``cls``.
20
21 Examples:
22
23 @lock_decorator(attr='_callback_lock')
24 def send_callback(...):
25
26 @lock_decorator(lock=threading.Lock())
27 def some_method(...):
28 """
29 def outer(func):
30 @wraps(func)
31 def inner(*args, **kwargs):
32 # Python2 doesn't have ``nonlocal``
33 # assign the actual lock to ``_lock``
34 if lock is None:
35 _lock = getattr(args[0], attr)
36 else:
37 _lock = lock
38 with _lock:
39 return func(*args, **kwargs)
40 return inner
41 return outer