https://github.com/python/cpython/commit/fade146cfb1616ad7b3b918bedb86756dedf79e6
commit: fade146cfb1616ad7b3b918bedb86756dedf79e6
branch: main
author: Duprat <[email protected]>
committer: vstinner <[email protected]>
date: 2025-05-22T16:46:57Z
summary:

gh-134322: Fix `repr(threading.RLock)` (#134389)

Fix the `__repr__` value of `threading.RLock` from `_thread` module, when just 
created.

files:
M Lib/test/lock_tests.py
M Lib/test/test_importlib/test_locks.py
M Modules/_threadmodule.c

diff --git a/Lib/test/lock_tests.py b/Lib/test/lock_tests.py
index 850450c1e81a16..691029a1a54f7f 100644
--- a/Lib/test/lock_tests.py
+++ b/Lib/test/lock_tests.py
@@ -337,6 +337,26 @@ class RLockTests(BaseLockTests):
     """
     Tests for recursive locks.
     """
+    def test_repr_count(self):
+        # see gh-134322: check that count values are correct:
+        # when a rlock is just created,
+        # in a second thread when rlock is acquired in the main thread.
+        lock = self.locktype()
+        self.assertIn("count=0", repr(lock))
+        self.assertIn("<unlocked", repr(lock))
+        lock.acquire()
+        lock.acquire()
+        self.assertIn("count=2", repr(lock))
+        self.assertIn("<locked", repr(lock))
+
+        result = []
+        def call_repr():
+            result.append(repr(lock))
+        with Bunch(call_repr, 1):
+            pass
+        self.assertIn("count=2", result[0])
+        self.assertIn("<locked", result[0])
+
     def test_reacquire(self):
         lock = self.locktype()
         lock.acquire()
diff --git a/Lib/test/test_importlib/test_locks.py 
b/Lib/test/test_importlib/test_locks.py
index befac5d62b0abf..655e5881a1530b 100644
--- a/Lib/test/test_importlib/test_locks.py
+++ b/Lib/test/test_importlib/test_locks.py
@@ -34,6 +34,7 @@ class ModuleLockAsRLockTests:
     # lock status in repr unsupported
     test_repr = None
     test_locked_repr = None
+    test_repr_count = None
 
     def tearDown(self):
         for splitinit in init.values():
diff --git a/Modules/_threadmodule.c b/Modules/_threadmodule.c
index 10123700f90f32..74b972b201a546 100644
--- a/Modules/_threadmodule.c
+++ b/Modules/_threadmodule.c
@@ -1225,7 +1225,13 @@ rlock_repr(PyObject *op)
     rlockobject *self = rlockobject_CAST(op);
     PyThread_ident_t owner = self->lock.thread;
     int locked = rlock_locked_impl(self);
-    size_t count = self->lock.level + 1;
+    size_t count;
+    if (locked) {
+        count = self->lock.level + 1;
+    }
+    else {
+        count = 0;
+    }
     return PyUnicode_FromFormat(
         "<%s %s object owner=%" PY_FORMAT_THREAD_IDENT_T " count=%zu at %p>",
         locked ? "locked" : "unlocked",

_______________________________________________
Python-checkins mailing list -- [email protected]
To unsubscribe send an email to [email protected]
https://mail.python.org/mailman3//lists/python-checkins.python.org
Member address: [email protected]

Reply via email to