https://github.com/python/cpython/commit/71db05a12d9953a96f809d84b4d0d452a464e431
commit: 71db05a12d9953a96f809d84b4d0d452a464e431
branch: main
author: Peter Bierma <[email protected]>
committer: ZeroIntensity <[email protected]>
date: 2025-10-21T08:10:01-04:00
summary:
gh-140406: Fix memory leak upon `__hash__` returning a non-integer (GH-140411)
files:
A
Misc/NEWS.d/next/Core_and_Builtins/2025-10-21-06-51-50.gh-issue-140406.0gJs8M.rst
M Lib/test/test_builtin.py
M Objects/typeobject.c
diff --git a/Lib/test/test_builtin.py b/Lib/test/test_builtin.py
index 85cfe5c90f48af..034cd5f7f9e89f 100644
--- a/Lib/test/test_builtin.py
+++ b/Lib/test/test_builtin.py
@@ -1184,6 +1184,16 @@ def __hash__(self):
return self
self.assertEqual(hash(Z(42)), hash(42))
+ def test_invalid_hash_typeerror(self):
+ # GH-140406: The returned object from __hash__() would leak if it
+ # wasn't an integer.
+ class A:
+ def __hash__(self):
+ return 1.0
+
+ with self.assertRaises(TypeError):
+ hash(A())
+
def test_hex(self):
self.assertEqual(hex(16), '0x10')
self.assertEqual(hex(-16), '-0x10')
diff --git
a/Misc/NEWS.d/next/Core_and_Builtins/2025-10-21-06-51-50.gh-issue-140406.0gJs8M.rst
b/Misc/NEWS.d/next/Core_and_Builtins/2025-10-21-06-51-50.gh-issue-140406.0gJs8M.rst
new file mode 100644
index 00000000000000..3506ba42581faa
--- /dev/null
+++
b/Misc/NEWS.d/next/Core_and_Builtins/2025-10-21-06-51-50.gh-issue-140406.0gJs8M.rst
@@ -0,0 +1,2 @@
+Fix memory leak when an object's :meth:`~object.__hash__` method returns an
+object that isn't an :class:`int`.
diff --git a/Objects/typeobject.c b/Objects/typeobject.c
index 29233c1959c4d0..721d48712446a0 100644
--- a/Objects/typeobject.c
+++ b/Objects/typeobject.c
@@ -10569,6 +10569,7 @@ slot_tp_hash(PyObject *self)
return PyObject_HashNotImplemented(self);
}
if (!PyLong_Check(res)) {
+ Py_DECREF(res);
PyErr_SetString(PyExc_TypeError,
"__hash__ method should return an integer");
return -1;
_______________________________________________
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]