fix(lock): Fix LockError message when releasing a lock. by shenxiangzhuang · Pull Request #3534 · redis/redis-py (original) (raw)
In the original code, we have the following:
def release(self) -> None:
"""
Releases the already acquired lock
"""
expected_token = self.local.token
if expected_token is None:
raise LockError("Cannot release an unlocked lock", lock_name=self.name)
self.local.token = None
self.do_release(expected_token)
This code can raise the LockError in several cases(Refering in some of the cases to the example in the reported issue):
- When the token object is not initialized or is already reset to None - it can happen if in thread 1 we have already called release and we call it again - in this case, the error handling is fine - the lock has really been already unlocked.
- We are in another thread that hasn't acquired a lock - which sounds like the message and meaning of LockNotOwnedError
- We might get in a similar to the first situation using the locks with context manager and trying to call the release function additionally.
If we are in Thread1 and we call release after the lock has expired, we get to self.do_release(expected_token)
which raises the LockNotOwnedError with message "Cannot release a lock that's no longer owned" - which sound correct.
Overall I think that we can just change the Exception to LockNotOwnedError(won't be breaking change, because it is a subtype of the LockError) with a proper error message, something like "Cannot release a lock that's not owned or is already unlocked."