Debian Codegraph @

hypothesis-python/src/hypothesis/utils/dynamicvariables.py

raw
1 # This file is part of Hypothesis, which may be found at
2 # https://github.com/HypothesisWorks/hypothesis/
3 #
4 # Copyright the Hypothesis Authors.
5 # Individual contributors are listed in AUTHORS.rst and the git log.
6 #
7 # This Source Code Form is subject to the terms of the Mozilla Public License,
8 # v. 2.0. If a copy of the MPL was not distributed with this file, You can
9 # obtain one at https://mozilla.org/MPL/2.0/.
10
11 import threading
12 from collections.abc import Generator
13 from contextlib import contextmanager
14 from typing import Generic, TypeVar
15
16 T = TypeVar("T")
17
18
19 class DynamicVariable(Generic[T]):
20 def __init__(self, default: T) -> None:
21 self.default = default
22 self.data = threading.local()
23
24 @property
25 def value(self) -> T:
26 return getattr(self.data, "value", self.default)
27
28 @value.setter
29 def value(self, value: T) -> None:
30 self.data.value = value
31
32 @contextmanager
33 def with_value(self, value: T) -> Generator[None, None, None]:
34 old_value = self.value
35 try:
36 self.data.value = value
37 yield
38 finally:
39 self.data.value = old_value