|
| 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 typing import Any |
| 13 | + |
| 14 | + |
| 15 | +class ThreadLocal: |
| 16 | + """ |
| 17 | + Manages thread-local state. ThreadLocal forwards getattr and setattr to a |
| 18 | + threading.local() instance. The passed kwargs defines the available attributes |
| 19 | + on the threadlocal and their default values. |
| 20 | +
|
| 21 | + The only supported names to geattr and setattr are the keys of the passed kwargs. |
| 22 | + """ |
| 23 | + |
| 24 | + def __init__(self, **kwargs: Any) -> None: |
| 25 | + self.__initialized = False |
| 26 | + self.__kwargs = kwargs |
| 27 | + self.__threadlocal = threading.local() |
| 28 | + self.__initialized = True |
| 29 | + |
| 30 | + def __getattr__(self, name: str) -> Any: |
| 31 | + if name not in self.__kwargs: |
| 32 | + raise AttributeError(f"No attribute {name}") |
| 33 | + if not hasattr(self.__threadlocal, name): |
| 34 | + setattr(self.__threadlocal, name, self.__kwargs[name]) |
| 35 | + return getattr(self.__threadlocal, name) |
| 36 | + |
| 37 | + def __setattr__(self, name: str, value: Any) -> None: |
| 38 | + # disable attribute-forwarding while initializing |
| 39 | + if "_ThreadLocal__initialized" not in self.__dict__ or not self.__initialized: |
| 40 | + super().__setattr__(name, value) |
| 41 | + else: |
| 42 | + if name not in self.__kwargs: |
| 43 | + raise AttributeError(f"No attribute {name}") |
| 44 | + setattr(self.__threadlocal, name, value) |
0 commit comments