8000 gh-134322: Fix `repr(threading.RLock)` (#134389) · python/cpython@fade146 · GitHub
[go: up one dir, main page]

Skip to content

Commit fade146

Browse files
authored
gh-134322: Fix repr(threading.RLock) (#134389)
Fix the `__repr__` value of `threading.RLock` from `_thread` module, when just created.
1 parent 4a4ac3a commit fade146

File tree

3 files changed

+28
-1
lines changed

3 files changed

+28
-1
lines changed

Lib/test/lock_tests.py

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -337,6 +337,26 @@ class RLockTests(BaseLockTests):
337337
"""
338338
Tests for recursive locks.
339339
"""
340+
def test_repr_count(self):
341+
# see gh-134322: check that count values are correct:
342+
# when a rlock is just created,
343+
# in a second thread when rlock is acquired in the main thread.
344+
lock = self.locktype()
345+
self.assertIn("count=0", repr(lock))
346+
self.assertIn("<unlocked", repr(lock))
347+
lock.acquire()
348+
lock.acquire()
349+
self.assertIn("count=2", repr(lock))
350+
self.assertIn("<locked", repr(lock))
351+
352+
result = []
353+
def call_repr():
354+
result.append(repr(lock))
355+
with Bunch(call_repr, 1):
356+
pass
357+
self.assertIn("count=2", result[0])
358+
self.assertIn("<locked", result[0])
359+
340360
def test_reacquire(self):
341361
lock = self.locktype()
342362
lock.acquire()

Lib/test/test_importlib/test_locks.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,7 @@ class ModuleLockAsRLockTests:
3434
# lock status in repr unsupported
3535
test_repr = None
3636
test_locked_repr = None
37+
test_repr_count = None
3738

3839
def tearDown(self):
3940
for splitinit in init.values():

Modules/_threadmodule.c

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1225,7 +1225,13 @@ rlock_repr(PyObject *op)
12251225
rlockobject *self = rlockobject_CAST(op);
12261226
PyThread_ident_t owner = self->lock.thread;
12271227
int locked = rlock_locked_impl(self);
1228-
size_t count = self->lock.level + 1;
1228+
size_t count;
1229+
if (locked) {
1230+
count = self->lock.level + 1;
1231+
}
1232+
else {
1233+
count = 0;
1234+
}
12291235
return PyUnicode_FromFormat(
12301236
"<%s %s object owner=%" PY_FORMAT_THREAD_IDENT_T " count=%zu at %p>",
12311237
locked ? "locked" : "unlocked",

0 commit comments

Comments
 (0)
0