fix: Reprs of subclasses of weakref now contain actual type name

This commit is contained in:
OhBonsai 2020-04-25 11:04:12 +08:00
parent ebebb6429c
commit 967c8f57c0
3 changed files with 28 additions and 10 deletions

View File

@ -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):

View File

@ -0,0 +1 @@
Reprs for weakref's subclass now contain actual type name

View File

@ -166,7 +166,8 @@ weakref_repr(PyWeakReference *self)
PyObject* obj = PyWeakref_GET_OBJECT(self);
if (obj == Py_None) {
return PyUnicode_FromFormat("<weakref at %p; dead>", 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(
"<weakref at %p; to '%s' at %p>",
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(
"<weakref at %p; to '%s' at %p (%U)>",
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. */