MCPcopy Create free account
hub / github.com/tox-dev/filelock / BaseFileLock

Class BaseFileLock

src/filelock/_api.py:142–397  ·  view source on GitHub ↗

Abstract base class for a file lock object.

Source from the content-addressed store, hash-verified

140
141
142class BaseFileLock(contextlib.ContextDecorator, metaclass=FileLockMeta):
143 """Abstract base class for a file lock object."""
144
145 _instances: WeakValueDictionary[str, BaseFileLock]
146
147 def __init_subclass__(cls, **kwargs: dict[str, Any]) -> None:
148 """Setup unique state for lock subclasses."""
149 super().__init_subclass__(**kwargs)
150 cls._instances = WeakValueDictionary()
151
152 def __init__( # noqa: PLR0913
153 self,
154 lock_file: str | os.PathLike[str],
155 timeout: float = -1,
156 mode: int = 0o644,
157 thread_local: bool = True, # noqa: FBT001, FBT002
158 *,
159 blocking: bool = True,
160 is_singleton: bool = False,
161 ) -> None:
162 """
163 Create a new lock object.
164
165 :param lock_file: path to the file
166 :param timeout: default timeout when acquiring the lock, in seconds. It will be used as fallback value in \
167 the acquire method, if no timeout value (``None``) is given. If you want to disable the timeout, set it \
168 to a negative value. A timeout of 0 means that there is exactly one attempt to acquire the file lock.
169 :param mode: file permissions for the lockfile
170 :param thread_local: Whether this object's internal context should be thread local or not. If this is set to \
171 ``False`` then the lock will be reentrant across threads.
172 :param blocking: whether the lock should be blocking or not
173 :param is_singleton: If this is set to ``True`` then only one instance of this class will be created \
174 per lock file. This is useful if you want to use the lock object for reentrant locking without needing \
175 to pass the same object around.
176
177 """
178 self._is_thread_local = thread_local
179 self._is_singleton = is_singleton
180
181 # Create the context. Note that external code should not work with the context directly and should instead use
182 # properties of this class.
183 kwargs: dict[str, Any] = {
184 "lock_file": os.fspath(lock_file),
185 "timeout": timeout,
186 "mode": mode,
187 "blocking": blocking,
188 }
189 self._context: FileLockContext = (ThreadLocalFileContext if thread_local else FileLockContext)(**kwargs)
190
191 def is_thread_local(self) -> bool:
192 """:return: a flag indicating if this lock is thread local or not"""
193 return self._is_thread_local
194
195 @property
196 def is_singleton(self) -> bool:
197 """:return: a flag indicating if this lock is singleton or not"""
198 return self._is_singleton
199

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected