diff --git a/Lib/test/test_weakref.py b/Lib/test/test_weakref.py index 563507fee3d..a15abc76afd 100644 --- a/Lib/test/test_weakref.py +++ b/Lib/test/test_weakref.py @@ -1156,6 +1156,19 @@ class WeakMethodTestCase(unittest.TestCase): # If it wasn't hashed when alive, a dead WeakMethod cannot be hashed. self.assertRaises(TypeError, hash, c) + def test_extend_repr(self): + class ExtendRef(weakref.ref): + pass + + # Dead weak ref + a = Object(1) + ra = ExtendRef(a) + self.assertIn("ExtendRef", repr(ra)) + + b = Object(1) + c = {"ref": b} + rb = ExtendRef(b) + self.assertIn("ExtendRef", repr(rb)) class MappingTestCase(TestBase): diff --git a/Misc/NEWS.d/next/Core and Builtins/2020-04-25-09-45-38.bpo-40383.cGqWeA.rst b/Misc/NEWS.d/next/Core and Builtins/2020-04-25-09-45-38.bpo-40383.cGqWeA.rst new file mode 100644 index 00000000000..cf76514b0c3 --- /dev/null +++ b/Misc/NEWS.d/next/Core and Builtins/2020-04-25-09-45-38.bpo-40383.cGqWeA.rst @@ -0,0 +1 @@ +Reprs for weakref's subclass now contain actual type name \ No newline at end of file diff --git a/Objects/weakrefobject.c b/Objects/weakrefobject.c index 9640d93aaf2..bf6050cb987 100644 --- a/Objects/weakrefobject.c +++ b/Objects/weakrefobject.c @@ -166,7 +166,8 @@ weakref_repr(PyWeakReference *self) PyObject* obj = PyWeakref_GET_OBJECT(self); if (obj == Py_None) { - return PyUnicode_FromFormat("", self); + return PyUnicode_FromFormat("<%s at %p; dead>", + _PyType_Name(Py_TYPE(self)), self); } Py_INCREF(obj); @@ -176,24 +177,27 @@ weakref_repr(PyWeakReference *self) } if (name == NULL || !PyUnicode_Check(name)) { repr = PyUnicode_FromFormat( - "", - self, - Py_TYPE(PyWeakref_GET_OBJECT(self))->tp_name, - obj); + "<%s at %p; to '%s' at %p>", + _PyType_Name(Py_TYPE(self)), + self, + Py_TYPE(PyWeakref_GET_OBJECT(self))->tp_name, + obj); } else { repr = PyUnicode_FromFormat( - "", - self, - Py_TYPE(PyWeakref_GET_OBJECT(self))->tp_name, - obj, - name); + "<%s at %p; to '%s' at %p (%U)>", + _PyType_Name(Py_TYPE(self)), + self, + Py_TYPE(PyWeakref_GET_OBJECT(self))->tp_name, + obj, + name); } Py_DECREF(obj); Py_XDECREF(name); return repr; } + /* Weak references only support equality, not ordering. Two weak references are equal if the underlying objects are equal. If the underlying object has gone away, they are equal if they are identical. */