|
| 1 | +import copy as cpy |
| 2 | +import threading |
| 3 | +from collections.abc import Callable |
| 4 | +from contextlib import contextmanager |
| 5 | +from typing import Any, Generic, TypeVar |
| 6 | + |
| 7 | +T = TypeVar("T") |
| 8 | + |
| 9 | + |
| 10 | +def value_is_immutable(obj: Any) -> bool: |
| 11 | + """ |
| 12 | + Check if a value is of a known immutable type. Just a heuristic for common |
| 13 | + cases and not perfect. |
| 14 | + """ |
| 15 | + immutable_types = (int, float, bool, str, tuple, frozenset, type(None), bytes, complex) |
| 16 | + if isinstance(obj, immutable_types): |
| 17 | + return True |
| 18 | + if hasattr(obj, "__dataclass_params__") and getattr(obj.__dataclass_params__, "frozen", False): |
| 19 | + return True |
| 20 | + return False |
| 21 | + |
| 22 | + |
| 23 | +class AtomicVar(Generic[T]): |
| 24 | + """ |
| 25 | + `AtomicVar` is a simple zero-dependency thread-safe variable that works |
| 26 | + for any type. |
| 27 | +
|
| 28 | + Often the standard "Pythonic" approach is to use locks directly, but for |
| 29 | + some common use cases, `AtomicVar` may be simpler and more readable. |
| 30 | + Works on any type, including lists and dicts. |
| 31 | +
|
| 32 | + Other options include `threading.Event` (for shared booleans), |
| 33 | + `threading.Queue` (for producer-consumer queues), and `multiprocessing.Value` |
| 34 | + (for process-safe primitives). |
| 35 | +
|
| 36 | + Examples: |
| 37 | +
|
| 38 | + ```python |
| 39 | + # Immutable types are always safe: |
| 40 | + count = AtomicVar(0) |
| 41 | + count.update(lambda x: x + 5) # In any thread. |
| 42 | + count.set(0) # In any thread. |
| 43 | + current_count = count.value # In any thread. |
| 44 | +
|
| 45 | + # Useful for flags: |
| 46 | + global_flag = AtomicVar(False) |
| 47 | + global_flag.set(True) # In any thread. |
| 48 | + if global_flag: # In any thread. |
| 49 | + print("Flag is set") |
| 50 | +
|
| 51 | +
|
| 52 | + # For mutable types,consider using `copy` or `deepcopy` to access the value: |
| 53 | + my_list = AtomicVar([1, 2, 3]) |
| 54 | + my_list_copy = my_list.copy() # In any thread. |
| 55 | + my_list_deepcopy = my_list.deepcopy() # In any thread. |
| 56 | +
|
| 57 | + # For mutable types, the `updates()` context manager gives a simple way to |
| 58 | + # lock on updates: |
| 59 | + with my_list.updates() as value: |
| 60 | + value.append(5) |
| 61 | +
|
| 62 | + # Or if you prefer, via a function: |
| 63 | + my_list.update(lambda x: x.append(4)) # In any thread. |
| 64 | +
|
| 65 | + # You can also use the var's lock directly. In particular, this encapsulates |
| 66 | + # locked one-time initialization: |
| 67 | + initialized = AtomicVar(False) |
| 68 | + with initialized.lock: |
| 69 | + if not initialized: # checks truthiness of underlying value |
| 70 | + expensive_setup() |
| 71 | + initialized.set(True) |
| 72 | +
|
| 73 | + # Or: |
| 74 | + lazy_var: AtomicVar[list[str] | None] = AtomicVar(None) |
| 75 | + with lazy_var.lock: |
| 76 | + if not lazy_var: |
| 77 | + lazy_var.set(expensive_calculation()) |
| 78 | + ``` |
| 79 | + """ |
| 80 | + |
| 81 | + def __init__(self, initial_value: T, is_immutable: bool | None = None): |
| 82 | + self._value: T = initial_value |
| 83 | + # Use an RLock just in case we read from the var while in an update(). |
| 84 | + self.lock: threading.RLock = threading.RLock() |
| 85 | + self.is_immutable: bool |
| 86 | + if is_immutable is None: |
| 87 | + self.is_immutable = value_is_immutable(initial_value) |
| 88 | + else: |
| 89 | + self.is_immutable = is_immutable |
| 90 | + |
| 91 | + @property |
| 92 | + def value(self) -> T: |
| 93 | + """ |
| 94 | + Current value. For immutable types, this is thread safe. For mutable types, |
| 95 | + this gives direct access to the value, so you should consider using `copy` or |
| 96 | + `deepcopy` instead. |
| 97 | + """ |
| 98 | + with self.lock: |
| 99 | + return self._value |
| 100 | + |
| 101 | + def copy(self) -> T: |
| 102 | + """ |
| 103 | + Shallow copy of the current value. |
| 104 | + """ |
| 105 | + with self.lock: |
| 106 | + return cpy.copy(self._value) |
| 107 | + |
| 108 | + def deepcopy(self) -> T: |
| 109 | + """ |
| 110 | + Deep copy of the current value. |
| 111 | + """ |
| 112 | + with self.lock: |
| 113 | + return cpy.deepcopy(self._value) |
| 114 | + |
| 115 | + def set(self, new_value: T) -> None: |
| 116 | + with self.lock: |
| 117 | + self._value = new_value |
| 118 | + |
| 119 | + def swap(self, new_value: T) -> T: |
| 120 | + """ |
| 121 | + Set to new value and return the old value. |
| 122 | + """ |
| 123 | + with self.lock: |
| 124 | + old_value = self._value |
| 125 | + self._value = new_value |
| 126 | + return old_value |
| 127 | + |
| 128 | + def update(self, update_func: Callable[[T], T | None]) -> T: |
| 129 | + """ |
| 130 | + Update value with a function and return the new value. |
| 131 | +
|
| 132 | + The `update_func` can either return a new value or update a mutable type in place, |
| 133 | + in which case it should return None. Always returns the final value of the |
| 134 | + variable after the update. |
| 135 | + """ |
| 136 | + with self.lock: |
| 137 | + result = update_func(self._value) |
| 138 | + if result is not None: |
| 139 | + self._value = result |
| 140 | + # Always return the potentially updated self._value |
| 141 | + return self._value |
| 142 | + |
| 143 | + @contextmanager |
| 144 | + def updates(self): |
| 145 | + """ |
| 146 | + Context manager for convenient thread-safe updates. Only applicable to |
| 147 | + mutable types. |
| 148 | +
|
| 149 | + Example usage: |
| 150 | + ``` |
| 151 | + my_list = AtomicVar([1, 2, 3]) |
| 152 | + with my_list.updates() as value: |
| 153 | + value.append(4) |
| 154 | + ``` |
| 155 | + """ |
| 156 | + # Sanity check to avoid accidental use with atomic/immutable types. |
| 157 | + if self.is_immutable: |
| 158 | + raise ValueError("Cannot use AtomicVar.updates() context manager on an immutable value") |
| 159 | + with self.lock: |
| 160 | + yield self._value |
| 161 | + |
| 162 | + def __bool__(self) -> bool: |
| 163 | + """ |
| 164 | + Truthiness matches that of the underlying value. |
| 165 | + """ |
| 166 | + return bool(self.value) |
| 167 | + |
| 168 | + def __repr__(self) -> str: |
| 169 | + return f"{self.__class__.__name__}({self.value!r})" |
| 170 | + |
| 171 | + def __str__(self) -> str: |
| 172 | + return str(self.value) |
0 commit comments