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