Asynchronous context manager performing a file lock.
The Lock class implements the asynchronous context manager
protocol (__aenter__/__aexit__) and uses portalocker to
create a platform-native file lock. The implementation is non-blocking
for the event loop because it polls to acquire the lock using
asyncio.sleep between attempts.
Example
async with Lock("/tmp/my.lock", timeout=2.0):
# critical section
await do_something()
| Parameters | |
| file | Path to the lock file. |
| mode | File open mode passed to portalocker (default: "a"). |
| create | File mode used when creating the lock file (default: 0o644). Ignored if the file already exists. |
| shared | If True, acquire a shared (read) lock; otherwise
acquire an exclusive (write) lock. |
| timeout | Maximum time in seconds to wait for the lock. If None,
wait indefinitely. |
| polling | Time in seconds between lock acquisition attempts, defaults to 0.25 seconds. |
| **fopen | Additional keyword arguments passed to the
underlying open call used by portalocker. |
| Async Method | __aenter__ |
Attempt to acquire the file lock. |
| Async Method | __aexit__ |
Release the previously acquired lock. |
| Method | __init__ |
Create an asynchronous file lock. |
| Instance Variable | create |
File mode used when creating the lock file. |
| Instance Variable | file |
Path to the lock file. |
| Instance Variable | fopen |
Additional keyword arguments passed to the underlying open call used by portalocker. |
| Instance Variable | lock |
Underlying portalocker.Lock instance. |
| Instance Variable | mode |
File open mode passed to portalocker. |
| Instance Variable | polling |
Time in seconds between lock acquisition attempts, defaults to 0.25 seconds. |
| Instance Variable | shared |
If True, acquire a shared (read) lock; otherwise acquire an exclusive (write) lock. |
| Instance Variable | timeout |
Maximum time in seconds to wait for the lock. If None, wait indefinitely. |
Attempt to acquire the file lock.
The function will repeatedly attempt to acquire the underlying
portalocker lock in a non-blocking fashion. Between attempts it
sleeps for polling_interval seconds. If a timeout is set
and exceeded a TimeoutError is raised.
| Returns | |
IO[ | The file-like object returned by portalocker's acquire (suitable for use as a file context manager). |
type[ BaseException] | None, exc_val: BaseException | None, exc_tb: Any):
(source)
¶
Release the previously acquired lock.
The release operation delegates to portalocker and does
not re-raise exceptions to the caller.
str | Path, mode: str = 'a', create_mode: int = 420, shared: bool = False, timeout: timedelta | float | None = None, polling_interval: timedelta | float = timedelta(Any):
(source)
¶
Create an asynchronous file lock.