diff --git a/Lib/asyncio/locks.py b/Lib/asyncio/locks.py index c59ea15111bef2..75712f28d65839 100644 --- a/Lib/asyncio/locks.py +++ b/Lib/asyncio/locks.py @@ -84,8 +84,9 @@ def __repr__(self): return f'<{res[1:-1]} [{extra}]>' def locked(self): - """Return True if lock is acquired.""" - return self._locked + """Return True if lock is acquired or if there are active waiters.""" + return not self._locked or ( + any(not w.cancelled() for w in (self._waiters or ()))) async def acquire(self): """Acquire a lock. diff --git a/Lib/test/test_asyncio/test_locks.py b/Lib/test/test_asyncio/test_locks.py index 320a933e144813..c5b0ebcefc65b8 100644 --- a/Lib/test/test_asyncio/test_locks.py +++ b/Lib/test/test_asyncio/test_locks.py @@ -186,7 +186,7 @@ async def lockit(name, blocker): tb.cancel() self.assertTrue(lock._waiters[0].cancelled()) await asyncio.sleep(0) - self.assertFalse(lock.locked()) + self.assertTrue(lock.locked()) self.assertTrue(ta.done()) self.assertTrue(tb.cancelled()) await tc @@ -272,6 +272,19 @@ async def test_release_no_waiters(self): lock.release() self.assertFalse(lock.locked()) + async def test_locked_with_waiters(self): + lock = asyncio.Lock() + + await lock.acquire() + waiter = asyncio.create_task(lock.acquire()) + await asyncio.sleep(0) + + lock.release() + self.assertTrue(lock.locked()) + + # Cleanup + await waiter + async def test_context_manager(self): lock = asyncio.Lock() self.assertFalse(lock.locked()) diff --git a/Misc/NEWS.d/next/Library/2026-11-26-14-05-07.gh-issue-138121.-AVsWv.rst b/Misc/NEWS.d/next/Library/2026-11-26-14-05-07.gh-issue-138121.-AVsWv.rst new file mode 100644 index 00000000000000..7348b5cb23a194 --- /dev/null +++ b/Misc/NEWS.d/next/Library/2026-11-26-14-05-07.gh-issue-138121.-AVsWv.rst @@ -0,0 +1,2 @@ +:meth:`asyncio.Lock.locked` now returns ``True`` when it has active waiters. +Contributed by Emerson Beckwith.