|
5 | 5 | import os
|
6 | 6 | import time
|
7 | 7 | import warnings
|
8 |
| -from abc import ABC, abstractmethod |
| 8 | +from abc import ABCMeta, abstractmethod |
9 | 9 | from dataclasses import dataclass
|
10 | 10 | from threading import local
|
11 |
| -from typing import TYPE_CHECKING, Any |
| 11 | +from typing import TYPE_CHECKING, Any, cast |
12 | 12 | from weakref import WeakValueDictionary
|
13 | 13 |
|
14 | 14 | from ._error import Timeout
|
@@ -77,33 +77,63 @@ class ThreadLocalFileContext(FileLockContext, local):
|
77 | 77 | """A thread local version of the ``FileLockContext`` class."""
|
78 | 78 |
|
79 | 79 |
|
80 |
| -class BaseFileLock(ABC, contextlib.ContextDecorator): |
81 |
| - """Abstract base class for a file lock object.""" |
82 |
| - |
83 |
| - _instances: WeakValueDictionary[str, Self] |
84 |
| - |
85 |
| - def __new__( # noqa: PLR0913 |
| 80 | +class FileLockMeta(ABCMeta): |
| 81 | + def __call__( # noqa: PLR0913 |
86 | 82 | cls,
|
87 | 83 | lock_file: str | os.PathLike[str],
|
88 |
| - timeout: float = -1, # noqa: ARG003 |
89 |
| - mode: int = 0o644, # noqa: ARG003 |
90 |
| - thread_local: bool = True, # noqa: FBT001, FBT002, ARG003 |
| 84 | + timeout: float = -1, |
| 85 | + mode: int = 0o644, |
| 86 | + thread_local: bool = True, # noqa: FBT001, FBT002 |
91 | 87 | *,
|
92 |
| - blocking: bool = True, # noqa: ARG003 |
| 88 | + blocking: bool = True, |
93 | 89 | is_singleton: bool = False,
|
94 |
| - **kwargs: Any, # capture remaining kwargs for subclasses # noqa: ARG003, ANN401 |
95 |
| - ) -> Self: |
96 |
| - """Create a new lock object or if specified return the singleton instance for the lock file.""" |
97 |
| - if not is_singleton: |
98 |
| - return super().__new__(cls) |
99 |
| - |
100 |
| - instance = cls._instances.get(str(lock_file)) |
101 |
| - if not instance: |
102 |
| - self = super().__new__(cls) |
103 |
| - cls._instances[str(lock_file)] = self |
104 |
| - return self |
| 90 | + **kwargs: Any, # capture remaining kwargs for subclasses # noqa: ANN401 |
| 91 | + ) -> BaseFileLock: |
| 92 | + if is_singleton: |
| 93 | + instance = cls._instances.get(str(lock_file)) # type: ignore[attr-defined] |
| 94 | + if instance: |
| 95 | + params_to_check = { |
| 96 | + "thread_local": (thread_local, instance.is_thread_local()), |
| 97 | + "timeout": (timeout, instance.timeout), |
| 98 | + "mode": (mode, instance.mode), |
| 99 | + "blocking": (blocking, instance.blocking), |
| 100 | + } |
| 101 | + |
| 102 | + non_matching_params = { |
| 103 | + name: (passed_param, set_param) |
| 104 | + for name, (passed_param, set_param) in params_to_check.items() |
| 105 | + if passed_param != set_param |
| 106 | + } |
| 107 | + if not non_matching_params: |
| 108 | + return cast(BaseFileLock, instance) |
| 109 | + |
| 110 | + # parameters do not match; raise error |
| 111 | + msg = "Singleton lock instances cannot be initialized with differing arguments" |
| 112 | + msg += "\nNon-matching arguments: " |
| 113 | + for param_name, (passed_param, set_param) in non_matching_params.items(): |
| 114 | + msg += f"\n\t{param_name} (existing lock has {set_param} but {passed_param} was passed)" |
| 115 | + raise ValueError(msg) |
| 116 | + |
| 117 | + instance = super().__call__( |
| 118 | + lock_file=lock_file, |
| 119 | + timeout=timeout, |
| 120 | + mode=mode, |
| 121 | + thread_local=thread_local, |
| 122 | + blocking=blocking, |
| 123 | + is_singleton=is_singleton, |
| 124 | + **kwargs, |
| 125 | + ) |
| 126 | + |
| 127 | + if is_singleton: |
| 128 | + cls._instances[str(lock_file)] = instance # type: ignore[attr-defined] |
| 129 | + |
| 130 | + return cast(BaseFileLock, instance) |
| 131 | + |
| 132 | + |
| 133 | +class BaseFileLock(contextlib.ContextDecorator, metaclass=FileLockMeta): |
| 134 | + """Abstract base class for a file lock object.""" |
105 | 135 |
|
106 |
| - return instance # type: ignore[return-value] # https://github.com/python/mypy/issues/15322 |
| 136 | + _instances: WeakValueDictionary[str, BaseFileLock] |
107 | 137 |
|
108 | 138 | def __init_subclass__(cls, **kwargs: dict[str, Any]) -> None:
|
109 | 139 | """Setup unique state for lock subclasses."""
|
@@ -136,34 +166,6 @@ def __init__( # noqa: PLR0913
|
136 | 166 | to pass the same object around.
|
137 | 167 |
|
138 | 168 | """
|
139 |
| - if is_singleton and hasattr(self, "_context"): |
140 |
| - # test whether other parameters match existing instance. |
141 |
| - if not self.is_singleton: |
142 |
| - msg = "__init__ should only be called on initialized object if it is a singleton" |
143 |
| - raise RuntimeError(msg) |
144 |
| - |
145 |
| - params_to_check = { |
146 |
| - "thread_local": (thread_local, self.is_thread_local()), |
147 |
| - "timeout": (timeout, self.timeout), |
148 |
| - "mode": (mode, self.mode), |
149 |
| - "blocking": (blocking, self.blocking), |
150 |
| - } |
151 |
| - |
152 |
| - non_matching_params = { |
153 |
| - name: (passed_param, set_param) |
154 |
| - for name, (passed_param, set_param) in params_to_check.items() |
155 |
| - if passed_param != set_param |
156 |
| - } |
157 |
| - if not non_matching_params: |
158 |
| - return # bypass initialization because object is already initialized |
159 |
| - |
160 |
| - # parameters do not match; raise error |
161 |
| - msg = "Singleton lock instances cannot be initialized with differing arguments" |
162 |
| - msg += "\nNon-matching arguments: " |
163 |
| - for param_name, (passed_param, set_param) in non_matching_params.items(): |
164 |
| - msg += f"\n\t{param_name} (existing lock has {set_param} but {passed_param} was passed)" |
165 |
| - raise ValueError(msg) |
166 |
| - |
167 | 169 | self._is_thread_local = thread_local
|
168 | 170 | self._is_singleton = is_singleton
|
169 | 171 |
|
|
0 commit comments