Skip to content

Commit 66bcdb3

Browse files
Update docs with example (#438)
Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
1 parent 638480f commit 66bcdb3

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed

docs/index.rst

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -111,6 +111,34 @@ The lock objects are recursive locks, which means that once acquired, they will
111111
cite2()
112112
# And released here.
113113
114+
It should also be noted that the lock is released during garbage collection.
115+
Put another way, if you do not assign an acquired lock to a variable,
116+
the lock will eventually be released (implicitly, not explicitly).
117+
For this reason, using the lock in the way shown below is not something you should ever do,
118+
always use the context manager (`with` form) instead.
119+
120+
This issue is illustrated with code below:
121+
122+
.. code-block:: python
123+
124+
import tempfile
125+
from pathlib import Path
126+
127+
import filelock
128+
129+
# If you create a lock and acquire it but don't assign it,
130+
# you will not actually hold the lock forever.
131+
# Instead, the lock is released
132+
# when the created variable is garbage collected.
133+
FileLock(lock_path).acquire()
134+
# At some point after the creation above,
135+
# the lock is released again even though there is no explicit call to `release`.
136+
137+
# If you instead assign to a dummy variable,
138+
# the lock will be hold
139+
_ = FileLock(lock_path).acquire()
140+
# Now the lock is being held
141+
# (at least until `_` is reassigned and the lock is garbage collected)
114142
115143
Timeouts and non-blocking locks
116144
-------------------------------

0 commit comments

Comments
 (0)