@@ -35,6 +35,7 @@ def _get_lock_context(path):
3535
3636 lock_context = contextlib .nullcontext ()
3737 lock_path = Path (f"{ os .fspath (path )} .lock" )
38+ lock_path = _normalize_lock_path (lock_path )
3839 have_lock = False
3940
4041 if filelock :
@@ -77,20 +78,25 @@ def _open_lock(path, *args, **kwargs):
7778 with lock_context , open (path , * args , ** kwargs ) as fid :
7879 yield fid
7980 finally :
80- if have_lock and lock_path . exists () :
81+ if have_lock :
8182 try :
82- lock_path .unlink ()
83+ lock_path .unlink (missing_ok = True )
8384 except OSError :
8485 pass
8586
8687
8788@contextmanager
8889def _file_lock (path ):
8990 """Acquire a lock on ``path`` without opening the file."""
90- lock_context , lock_path , have_lock = _get_lock_context (path )
9191 normalized = _normalize_lock_path (path )
92+ lock_path = _normalize_lock_path (Path (f"{ os .fspath (path )} .lock" ))
93+ already_locked = _path_is_locked (normalized )
94+ if already_locked :
95+ lock_context , have_lock = contextlib .nullcontext (), False
96+ else :
97+ lock_context , lock_path , have_lock = _get_lock_context (path )
9298 token = None
93- if not _path_is_locked ( normalized ) :
99+ if have_lock and not already_locked :
94100 current = _LOCKED_PATHS .get ()
95101 token = _LOCKED_PATHS .set (current + (normalized ,))
96102 try :
@@ -99,8 +105,8 @@ def _file_lock(path):
99105 finally :
100106 if token is not None :
101107 _LOCKED_PATHS .reset (token )
102- if have_lock and lock_path . exists () :
108+ if have_lock :
103109 try :
104- lock_path .unlink ()
110+ lock_path .unlink (missing_ok = True )
105111 except OSError :
106112 pass
0 commit comments