Skip to content

Commit 8947e72

Browse files
hirschalterhirsch-alter-lynxightpre-commit-ci[bot]
authored
Enable use as a context decorator (#128)
Co-authored-by: Hirsch Alter <[email protected]> Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
1 parent 541baba commit 8947e72

File tree

4 files changed

+28
-1
lines changed

4 files changed

+28
-1
lines changed

docs/changelog.rst

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,10 @@
11
Changelog
22
=========
33

4+
v3.5.0 (2022-01-03)
5+
-------------------
6+
- Enable use as context decorator
7+
48
v3.4.2 (2021-12-16)
59
-------------------
610
- Drop support for python ``3.6``

docs/index.rst

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -67,6 +67,14 @@ locks:
6767
finally:
6868
lock.release()
6969
70+
71+
@lock
72+
def decorated():
73+
print("You're a decorated Jedi!")
74+
75+
76+
decorated()
77+
7078
The :meth:`acquire <filelock.BaseFileLock.acquire>` method accepts also a ``timeout`` parameter. If the lock cannot be
7179
acquired within ``timeout`` seconds, a :class:`Timeout <filelock.Timeout>` exception is raised:
7280

src/filelock/_api.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
from __future__ import annotations
22

3+
import contextlib
34
import logging
45
import os
56
import time
@@ -35,7 +36,7 @@ def __exit__(
3536
self.lock.release()
3637

3738

38-
class BaseFileLock(ABC):
39+
class BaseFileLock(ABC, contextlib.ContextDecorator):
3940
"""Abstract base class for a file lock object."""
4041

4142
def __init__(self, lock_file: str | os.PathLike[Any], timeout: float = -1) -> None:

tests/test_filelock.py

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -368,3 +368,17 @@ def test_poll_intervall_deprecated(lock_type: type[BaseFileLock], tmp_path: Path
368368
break
369369
else: # pragma: no cover
370370
pytest.fail("No warnings of stacklevel=2 matching.")
371+
372+
373+
@pytest.mark.parametrize("lock_type", [FileLock, SoftFileLock])
374+
def test_context_decorator(lock_type: type[BaseFileLock], tmp_path: Path) -> None:
375+
lock_path = tmp_path / "a"
376+
lock = lock_type(str(lock_path))
377+
378+
@lock
379+
def decorated_method() -> None:
380+
assert lock.is_locked
381+
382+
assert not lock.is_locked
383+
decorated_method()
384+
assert not lock.is_locked

0 commit comments

Comments
 (0)