tox-dev / filelock

A platform-independent file lock for Python.
https://py-filelock.readthedocs.io
The Unlicense
747 stars 107 forks source link

is_singleton=True with nested lock hangs #331

Closed yugokato closed 3 months ago

yugokato commented 3 months ago

I noticed the following code hangs. Is this not a supported usage?

from filelock import FileLock

with FileLock('.lock', is_singleton=True):
    with FileLock('.lock', is_singleton=True):
        ...

This works fine:

from filelock import FileLock

lock1 = FileLock('.lock', is_singleton=True)
lock2 = FileLock('.lock', is_singleton=True)
with lock1:
    with lock2:
        ...

Environment:

ethanbb commented 3 months ago

I think this is happening because the __init__ method of BaseFileLock is always called when a new FileLock is constructed, even if it's just returning an existing instance. This sets self._context to a new object. In particular, in the nested situation, the context whose counter was incremented by the first call to acquire will be discarded and replaced with a new context; thus, it will not know that the lock has already been acquired and will try to open the lock file again, but will be unable to.

My humble suggestion would be to avoid this by only calling the contents of __init__ once when the FileLock is actually constructed. This could be done by renaming it to something like _initialize and calling it within __new__ after each call to super().__new__.