API Reference¶
This section documents all public classes, exceptions, and attributes. For usage examples and task-oriented guidance, see Tutorials and How-to guides.
A platform independent file lock that supports the with-statement.
- filelock.__version__¶
version of the project as a string
- class filelock.AcquireReturnProxy(lock)[source]¶
Bases:
objectA context-aware object that will release the lock file when exiting.
- class filelock.AsyncAcquireReadWriteReturnProxy(lock)[source]¶
Bases:
objectContext-aware object that releases the async read/write lock on exit.
- class filelock.AsyncAcquireReturnProxy(lock)[source]¶
Bases:
objectA context-aware object that will release the lock file when exiting.
- class filelock.AsyncAcquireSoftReadWriteReturnProxy(lock)[source]¶
Bases:
objectAsync context-aware object that releases an
AsyncSoftReadWriteLockon exit.
- filelock.AsyncFileLock¶
alias of
AsyncUnixFileLock
- class filelock.AsyncReadWriteLock(lock_file, timeout=-1, *, blocking=True, is_singleton=True, loop=None, executor=None)[source]¶
Bases:
objectAsync wrapper around
ReadWriteLockfor use inasyncioapplications.Because Python’s
sqlite3module has no async API, all blocking SQLite operations are dispatched to a thread pool vialoop.run_in_executor(). Reentrancy, upgrade/downgrade rules, and singleton behavior are delegated to the underlyingReadWriteLock.- Parameters:
lock_file (
str|PathLike[str]) – path to the SQLite database file used as the locktimeout (
float) – maximum wait time in seconds;-1means block indefinitelyblocking (
bool) – ifFalse, raiseTimeoutimmediately when the lock is unavailableis_singleton (
bool) – ifTrue, reuse existingReadWriteLockinstances for the same resolved pathloop (
AbstractEventLoop|None) – event loop forrun_in_executor;Noneuses the running loopexecutor (
Executor|None) – executor forrun_in_executor. WhenNonea dedicated single-thread executor is created and owned by this lock, ensuring every operation runs on the same thread (required for SQLite affinity); it is shut down byclose(). A caller-supplied executor is used as-is and never shut down here, so when no executor is passed remember to callclose()to release the owned one.
Added in version 3.21.0.
- property lock_file¶
- Returns:
the path to the lock file.
- property timeout¶
- Returns:
the default timeout.
- property blocking¶
- Returns:
whether blocking is enabled by default.
- property loop¶
- Returns:
the event loop (or
Nonefor the running loop).
- property executor¶
- Returns:
the executor used for
run_in_executor(a dedicated single-thread one if none was supplied).
- async acquire_read(timeout=-1, *, blocking=True)[source]¶
Acquire a shared read lock.
See
ReadWriteLock.acquire_read()for full semantics.- Parameters:
- Return type:
- Returns:
a proxy that can be used as an async context manager to release the lock
- Raises:
RuntimeError – if a write lock is already held on this instance
Timeout – if the lock cannot be acquired within timeout seconds
- async acquire_write(timeout=-1, *, blocking=True)[source]¶
Acquire an exclusive write lock.
See
ReadWriteLock.acquire_write()for full semantics.- Parameters:
- Return type:
- Returns:
a proxy that can be used as an async context manager to release the lock
- Raises:
RuntimeError – if a read lock is already held, or a write lock is held by a different thread
Timeout – if the lock cannot be acquired within timeout seconds
- async release(*, force=False)[source]¶
Release one level of the current lock.
See
ReadWriteLock.release()for full semantics.- Parameters:
force (
bool) – ifTrue, release the lock completely regardless of the current lock level- Raises:
RuntimeError – if no lock is currently held and force is
False- Return type:
- read_lock(timeout=None, *, blocking=None)[source]¶
Async context manager that acquires and releases a shared read lock.
Falls back to instance defaults for timeout and blocking when
None.
- class filelock.AsyncSoftFileLock(lock_file, timeout=-1, mode=-1, thread_local=False, *, blocking=True, is_singleton=False, poll_interval=0.05, lifetime=None, loop=None, run_in_executor=True, executor=None)[source]¶
Bases:
SoftFileLock,BaseAsyncFileLockSimply watches the existence of the lock file.
- class filelock.AsyncSoftReadWriteLock(lock_file, timeout=-1, *, blocking=True, is_singleton=True, heartbeat_interval=30.0, stale_threshold=None, poll_interval=0.25, loop=None, executor=None)[source]¶
Bases:
objectAsync wrapper around
SoftReadWriteLockforasyncioapplications.The sync class’s blocking filesystem operations run on a thread pool via
loop.run_in_executor(). Reentrancy, upgrade/downgrade rules, fork handling, heartbeat and TTL stale detection, and singleton behavior are delegated to the underlyingSoftReadWriteLock.- Parameters:
lock_file (
str|PathLike[str]) – path to the lock file; sidecar state/write/readers live next to ittimeout (
float) – maximum wait time in seconds;-1means block indefinitelyblocking (
bool) – ifFalse, raiseTimeoutimmediately on contentionis_singleton (
bool) – ifTrue, reuse existingSoftReadWriteLockinstances per resolved pathheartbeat_interval (
float) – seconds between heartbeat refreshes; default 30 sstale_threshold (
float|None) – seconds of mtime inactivity before a marker is stale; defaults to3 * heartbeat_intervalpoll_interval (
float) – seconds between acquire retries under contention; default 0.25 sloop (
AbstractEventLoop|None) – event loop forrun_in_executor;Noneuses the running loopexecutor (
Executor|None) – executor forrun_in_executor;Noneuses the default executor
Added in version 3.27.0.
- property lock_file¶
- Returns:
the path to the lock file passed to the constructor.
- property timeout¶
- Returns:
the default timeout applied when
acquire_read/acquire_writeis called without one.
- property blocking¶
- Returns:
whether
acquire_*defaults to blocking;Falsemakes contention raise immediately.
- property loop¶
- Returns:
the event loop used for
run_in_executor, orNonefor the running loop.
- property executor¶
- Returns:
the executor used for
run_in_executor, orNonefor the default executor.
- async acquire_read(timeout=None, *, blocking=None)[source]¶
Acquire a shared read lock.
See
SoftReadWriteLock.acquire_read()for the full reentrancy / upgrade / fork semantics. The blocking work runs insiderun_in_executorso other coroutines on the same loop continue to progress while this call waits.- Parameters:
- Return type:
- Returns:
a proxy usable as an async context manager to release the lock
- Raises:
RuntimeError – if a write lock is already held, if this instance was invalidated by
os.fork(), or ifclose()was calledTimeout – if the lock cannot be acquired within timeout seconds
- async acquire_write(timeout=None, *, blocking=None)[source]¶
Acquire an exclusive write lock.
See
SoftReadWriteLock.acquire_write()for the two-phase writer-preferring semantics. The blocking work runs insiderun_in_executor.- Parameters:
- Return type:
- Returns:
a proxy usable as an async context manager to release the lock
- Raises:
RuntimeError – if a read lock is already held, if a write lock is held by a different thread, if this instance was invalidated by
os.fork(), or ifclose()was calledTimeout – if the lock cannot be acquired within timeout seconds
- async release(*, force=False)[source]¶
Release one level of the current lock.
- Parameters:
force (
bool) – ifTrue, release the lock completely regardless of the current lock level- Raises:
RuntimeError – if no lock is currently held and force is
False- Return type:
- read_lock(timeout=None, *, blocking=None)[source]¶
Async context manager that acquires and releases a shared read lock.
- Parameters:
- Raises:
RuntimeError – if a write lock is already held on this instance
Timeout – if the lock cannot be acquired within timeout seconds
- Return type:
- write_lock(timeout=None, *, blocking=None)[source]¶
Async context manager that acquires and releases an exclusive write lock.
- Parameters:
- Raises:
RuntimeError – if a read lock is already held, or a write lock is held by a different thread
Timeout – if the lock cannot be acquired within timeout seconds
- Return type:
- class filelock.AsyncUnixFileLock(lock_file, timeout=-1, mode=-1, thread_local=False, *, blocking=True, is_singleton=False, poll_interval=0.05, lifetime=None, loop=None, run_in_executor=True, executor=None)[source]¶
Bases:
UnixFileLock,BaseAsyncFileLockUses the
fcntl.flock()to hard lock the lock file on unix systems.
- class filelock.AsyncWindowsFileLock(lock_file, timeout=-1, mode=-1, thread_local=False, *, blocking=True, is_singleton=False, poll_interval=0.05, lifetime=None, loop=None, run_in_executor=True, executor=None)[source]¶
Bases:
WindowsFileLock,BaseAsyncFileLockUses the
msvcrt.locking()to hard lock the lock file on windows systems.
- class filelock.BaseAsyncFileLock(lock_file, timeout=-1, mode=-1, thread_local=False, *, blocking=True, is_singleton=False, poll_interval=0.05, lifetime=None, loop=None, run_in_executor=True, executor=None)[source]¶
Bases:
BaseFileLockBase class for asynchronous file locks.
Added in version 3.15.0.
- property run_in_executor¶
- Returns:
whether run in executor.
- property executor¶
- Returns:
the executor.
- property loop¶
- Returns:
the event loop.
- async acquire(timeout=None, poll_interval=None, *, blocking=None, cancel_check=None)[source]¶
Try to acquire the file lock.
- Parameters:
timeout (
float|None) – maximum wait time for acquiring the lock,Nonemeans use the defaulttimeoutis and iftimeout < 0, there is no timeout and this method will block until the lock could be acquiredpoll_interval (
float|None) – interval of trying to acquire the lock file,Nonemeans use the defaultpoll_intervalblocking (
bool|None) – defaults to True. If False, function will return immediately if it cannot obtain a lock on the first attempt. Otherwise, this method will block until the timeout expires or the lock is acquired.cancel_check (
Callable[[],bool] |None) – a callable returningTruewhen the acquisition should be canceled. Checked on each poll iteration. When triggered, raisesTimeoutjust like an expired timeout.
- Return type:
- Returns:
a context object that will unlock the file when the context is exited
- Raises:
Timeout – if fails to acquire lock within the timeout period
# You can use this method in the context manager (recommended) with lock.acquire(): pass # Or use an equivalent try-finally construct: lock.acquire() try: pass finally: lock.release()
- class filelock.BaseFileLock(lock_file, timeout=-1, mode=-1, thread_local=True, *, blocking=True, is_singleton=False, poll_interval=0.05, lifetime=None)[source]¶
Bases:
ContextDecoratorAbstract base class for a file lock object.
Provides a reentrant, cross-process exclusive lock backed by OS-level primitives. Subclasses implement the actual locking mechanism (
UnixFileLock,WindowsFileLock,SoftFileLock).- is_thread_local()[source]¶
- Return type:
- Returns:
a flag indicating if this lock is thread local or not
- property is_singleton¶
- Returns:
a flag indicating if this lock is singleton or not
Added in version 3.13.0.
- property lock_file¶
- Returns:
path to the lock file
- property timeout¶
- Returns:
the default timeout value, in seconds
Added in version 2.0.0.
- property blocking¶
- Returns:
whether the locking is blocking or not
Added in version 3.14.0.
- property poll_interval¶
- Returns:
the default polling interval, in seconds
Added in version 3.24.0.
- property lifetime¶
- Returns:
the lock lifetime in seconds, or
Noneif the lock never expires
Added in version 3.24.0.
- property mode¶
- Returns:
the file permissions for the lockfile
- property has_explicit_mode¶
- Returns:
whether the file permissions were explicitly set
- property is_locked¶
- Returns:
A boolean indicating if the lock file is holding the lock currently.
Changed in version 2.0.0: This was previously a method and is now a property.
- property lock_counter¶
- Returns:
The number of times this lock has been acquired (but not yet released).
- acquire(timeout=None, poll_interval=None, *, poll_intervall=None, blocking=None, cancel_check=None)[source]¶
Try to acquire the file lock.
- Parameters:
timeout (
float|None) – maximum wait time for acquiring the lock,Nonemeans use the defaulttimeoutis and iftimeout < 0, there is no timeout and this method will block until the lock could be acquiredpoll_interval (
float|None) – interval of trying to acquire the lock file,Nonemeans use the defaultpoll_intervalpoll_intervall (
float|None) – deprecated, kept for backwards compatibility, usepoll_intervalinsteadblocking (
bool|None) – defaults to True. If False, function will return immediately if it cannot obtain a lock on the first attempt. Otherwise, this method will block until the timeout expires or the lock is acquired.cancel_check (
Callable[[],bool] |None) – a callable returningTruewhen the acquisition should be canceled. Checked on each poll iteration. When triggered, raisesTimeoutjust like an expired timeout.
- Return type:
- Returns:
a context object that will unlock the file when the context is exited
- Raises:
Timeout – if fails to acquire lock within the timeout period
# You can use this method in the context manager (recommended) with lock.acquire(): pass # Or use an equivalent try-finally construct: lock.acquire() try: pass finally: lock.release()
Changed in version 2.0.0: This method returns now a proxy object instead of self, so that it can be used in a with statement without side effects.
- filelock.FileLock¶
Alias for the lock, which should be used for the current platform.
- class filelock.ReadWriteLock(lock_file, timeout=-1, *, blocking=True, is_singleton=True)[source]¶
Bases:
objectCross-process read-write lock backed by SQLite.
Allows concurrent shared readers or a single exclusive writer. The lock is reentrant within the same mode (multiple
acquire_readcalls nest, as do multipleacquire_writecalls from the same thread), but upgrading from read to write or downgrading from write to read raisesRuntimeError. Write locks are pinned to the thread that acquired them.By default,
is_singleton=True: callingReadWriteLock(path)with the same resolved path returns the same instance. The lock file must use a.dbextension (SQLite database).- Parameters:
lock_file (
str|PathLike[str]) – path to the SQLite database file used as the locktimeout (
float) – maximum wait time in seconds;-1means block indefinitelyblocking (
bool) – ifFalse, raiseTimeoutimmediately when the lock is unavailableis_singleton (
bool) – ifTrue, reuse existing instances for the same resolved path
Added in version 3.21.0.
- classmethod get_lock(lock_file, timeout=-1, *, blocking=True)[source]¶
Return the singleton
ReadWriteLockfor lock_file.- Parameters:
- Return type:
- Returns:
the singleton lock instance
- Raises:
ValueError – if an instance already exists for this path with different timeout or blocking values
- acquire_read(timeout=-1, *, blocking=True)[source]¶
Acquire a shared read lock.
If this instance already holds a read lock, the lock level is incremented (reentrant). Attempting to acquire a read lock while holding a write lock raises
RuntimeError(downgrade not allowed).- Parameters:
- Return type:
- Returns:
a proxy that can be used as a context manager to release the lock
- Raises:
RuntimeError – if a write lock is already held on this instance
Timeout – if the lock cannot be acquired within timeout seconds
- acquire_write(timeout=-1, *, blocking=True)[source]¶
Acquire an exclusive write lock.
If this instance already holds a write lock from the same thread, the lock level is incremented (reentrant). Attempting to acquire a write lock while holding a read lock raises
RuntimeError(upgrade not allowed). Write locks are pinned to the acquiring thread: a different thread trying to re-enter also raisesRuntimeError.- Parameters:
- Return type:
- Returns:
a proxy that can be used as a context manager to release the lock
- Raises:
RuntimeError – if a read lock is already held, or a write lock is held by a different thread
Timeout – if the lock cannot be acquired within timeout seconds
- release(*, force=False)[source]¶
Release one level of the current lock.
When the lock level reaches zero the underlying SQLite transaction is rolled back, releasing the database lock.
- Parameters:
force (
bool) – ifTrue, release the lock completely regardless of the current lock level- Raises:
RuntimeError – if no lock is currently held and force is
False- Return type:
- read_lock(timeout=None, *, blocking=None)[source]¶
Context manager that acquires and releases a shared read lock.
Falls back to instance defaults for timeout and blocking when
None.
- class filelock.SoftFileLock(lock_file, timeout=-1, mode=-1, thread_local=True, *, blocking=True, is_singleton=False, poll_interval=0.05, lifetime=None)[source]¶
Bases:
BaseFileLockPortable file lock based on file existence.
Unlike
UnixFileLockandWindowsFileLock, this lock does not use OS-level locking primitives. Instead, it creates the lock file withO_CREAT | O_EXCLand treats its existence as the lock indicator. This makes it work on any filesystem but leaves stale lock files behind if the process crashes without releasing the lock.To mitigate stale locks, the lock file contains the PID and hostname of the holding process. On contention, if the holder is on the same host and its PID no longer exists, the stale lock is broken automatically.
- property pid¶
The PID of the process holding this lock, read from the lock file.
- Returns:
the PID as an integer, or
Noneif the lock file does not exist or cannot be parsed
- property is_lock_held_by_us¶
Whether this lock is held by the current process.
- Returns:
Trueif the lock file exists and names the current process’s PID and hostname
- class filelock.SoftReadWriteLock(lock_file, timeout=-1, *, blocking=True, is_singleton=True, heartbeat_interval=30.0, stale_threshold=None, poll_interval=0.25)[source]¶
Bases:
objectCross-process and cross-host reader/writer lock built on
SoftFileLockprimitives.Use this class instead of
ReadWriteLockwhen the lock file lives on a network filesystem (NFS, Lustre with-o flock, HPC cluster shared storage).ReadWriteLockis backed by SQLite and cannot run on NFS because SQLite’sfcntllocking is unreliable there.Layout on disk for a lock at
foo.lock:foo.lock.state— aSoftFileLocktaken only during state transitions (microseconds).foo.lock.write— writer marker; its presence means a writer is claiming or holding the lock.foo.lock.readers/<host>.<pid>.<uuid>— one file per reader.
Each marker stores a random token (
secrets.token_hex(16)), the holder’s pid, and the holder’s hostname. A daemon heartbeat thread refreshesmtimeon every held marker. A marker whose mtime has not advanced instale_thresholdseconds may be evicted by any process on any host, giving correct behavior when a compute node crashes with a lock held.Writer acquire is two-phase and writer-preferring: phase 1 claims
.write(blocking any new reader), phase 2 waits for existing readers to drain. Writer starvation is impossible.Reentrancy, upgrade/downgrade rules, thread pinning, and singleton caching by resolved path match
ReadWriteLock.Forking while holding a lock invalidates the inherited instance in the child so the child cannot double-own the lock with its parent;
release()on a fork-invalidated instance is a no-op, and the child must re-acquire if it needs a lock.Trust boundary: protects against same-UID non-cooperating processes (one host or cross-host) and same-host different-UID users via
0o600/0o700permissions. Does not protect against root compromise, NTP tampering on same-UID cross-host nodes, or multi-tenant mounts where hostile co-tenants share the UID.- Parameters:
lock_file (
str|PathLike[str]) – path to the lock file; sidecar state/write/readers live next to ittimeout (
float) – maximum wait time in seconds;-1means block indefinitelyblocking (
bool) – ifFalse, raiseTimeoutimmediately on contentionis_singleton (
bool) – ifTrue, reuse existing instances for the same resolved pathheartbeat_interval (
float) – seconds between heartbeat refreshes; default 30 sstale_threshold (
float|None) – seconds ofmtimeinactivity before a marker is stale; defaults to3 * heartbeat_interval, matching etcd’sLeaseKeepAliveconventionpoll_interval (
float) – seconds between acquire retries under contention; default 0.25 s
Added in version 3.27.0.
- read_lock(timeout=None, *, blocking=None)[source]¶
Context manager that acquires and releases a shared read lock.
Falls back to instance defaults for timeout and blocking when
None.- Parameters:
- Raises:
RuntimeError – if a write lock is already held on this instance
Timeout – if the lock cannot be acquired within timeout seconds
- Return type:
- write_lock(timeout=None, *, blocking=None)[source]¶
Context manager that acquires and releases an exclusive write lock.
Falls back to instance defaults for timeout and blocking when
None.- Parameters:
- Raises:
RuntimeError – if a read lock is already held, or a write lock is held by a different thread
Timeout – if the lock cannot be acquired within timeout seconds
- Return type:
- acquire_read(timeout=None, *, blocking=None)[source]¶
Acquire a shared read lock.
If this instance already holds a read lock, the lock level is incremented (reentrant). Attempting to acquire a read lock while holding a write lock raises
RuntimeError(downgrade not allowed). On the 0→1 transition a daemon heartbeat thread is started that refreshes the reader marker’smtimeeveryheartbeat_intervalseconds so peers on other hosts do not evict the marker as stale.- Parameters:
- Return type:
- Returns:
a proxy that can be used as a context manager to release the lock
- Raises:
RuntimeError – if a write lock is already held on this instance, if this instance was invalidated by
os.fork(), or ifclose()was calledTimeout – if the lock cannot be acquired within timeout seconds
- acquire_write(timeout=None, *, blocking=None)[source]¶
Acquire an exclusive write lock.
If this instance already holds a write lock from the same thread, the lock level is incremented (reentrant). Attempting to acquire a write lock while holding a read lock raises
RuntimeError(upgrade not allowed). Write locks are pinned to the acquiring thread: a different thread trying to re-enter also raisesRuntimeError.Writer acquisition runs in two phases. Phase 1 atomically claims
<path>.writeviaO_CREAT | O_EXCL, which immediately blocks any new reader on any host. Phase 2 waits for existing readers to drain. Writer starvation is impossible: new readers see<path>.writeduring phase 2 and wait behind the pending writer.- Parameters:
- Return type:
- Returns:
a proxy that can be used as a context manager to release the lock
- Raises:
RuntimeError – if a read lock is already held, if a write lock is held by a different thread, if this instance was invalidated by
os.fork(), or ifclose()was calledTimeout – if the lock cannot be acquired within timeout seconds
- close()[source]¶
Release any held lock and release internal filesystem resources.
Idempotent. After calling this method the instance can no longer acquire locks — subsequent acquires raise
RuntimeError. A fork-invalidated instance is closed without raising.- Return type:
- release(*, force=False)[source]¶
Release one level of the current lock.
When the lock level reaches zero the heartbeat thread is stopped and the held marker file is unlinked. On a fork-invalidated instance (that is, the child of a
os.fork()call made while the parent held a lock) this method is a no-op so inheritedwithblocks can unwind cleanly in the child.- Parameters:
force (
bool) – ifTrue, release the lock completely regardless of the current lock level- Raises:
RuntimeError – if no lock is currently held and force is
False- Return type:
- classmethod get_lock(lock_file, timeout=-1, *, blocking=True)[source]¶
Return the singleton
SoftReadWriteLockfor lock_file.- Parameters:
- Return type:
- Returns:
the singleton lock instance
- Raises:
ValueError – if an instance already exists for this path with different timeout or blocking values
- exception filelock.Timeout(lock_file)[source]¶
Bases:
TimeoutErrorRaised when the lock could not be acquired in timeout seconds.
- property lock_file¶
- Returns:
The path of the file lock.
- class filelock.UnixFileLock(lock_file, timeout=-1, mode=-1, thread_local=True, *, blocking=True, is_singleton=False, poll_interval=0.05, lifetime=None)[source]¶
Bases:
BaseFileLockUses the
fcntl.flock()to hard lock the lock file on unix systems.Lock file cleanup: Unix and macOS delete the lock file reliably after release, even in multi-threaded scenarios. Unlike Windows, Unix allows unlinking files that other processes have open.
- class filelock.WindowsFileLock(lock_file, timeout=-1, mode=-1, thread_local=True, *, blocking=True, is_singleton=False, poll_interval=0.05, lifetime=None)[source]¶
Bases:
BaseFileLockUses the
msvcrt.locking()function to hard lock the lock file on Windows systems.