]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
gh-134322: Fix `repr(threading.RLock)` (#134389)
authorDuprat <yduprat@gmail.com>
Thu, 22 May 2025 16:46:57 +0000 (18:46 +0200)
committerGitHub <noreply@github.com>
Thu, 22 May 2025 16:46:57 +0000 (16:46 +0000)
Fix the `__repr__` value of `threading.RLock` from `_thread` module, when just created.

Lib/test/lock_tests.py
Lib/test/test_importlib/test_locks.py
Modules/_threadmodule.c

index 850450c1e81a16ce4a193175bd223a872154b909..691029a1a54f7fc5f3472cf762fbdedba4d8d407 100644 (file)
@@ -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()
index befac5d62b0abf1ef607b880f5ab1373c8339acc..655e5881a1530b3d0b5a708fed2765268e0175ea 100644 (file)
@@ -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():
index 10123700f90f32139fdd19e71fad83e7c57c1b9b..74b972b201a546849aa5c24ecfacd93f64a05393 100644 (file)
@@ -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",