From 649986ba50f6fac4d0df596f0a91975c0cc000c5 Mon Sep 17 00:00:00 2001 From: Peter Bierma Date: Tue, 21 Oct 2025 08:10:01 -0400 Subject: [PATCH 1/2] gh-140406: Fix memory leak upon `__hash__` returning a non-integer (GH-140411) (cherry picked from commit 71db05a12d9953a96f809d84b4d0d452a464e431) --- Lib/test/test_builtin.py | 10 ++++++++++ .../2025-10-21-06-51-50.gh-issue-140406.0gJs8M.rst | 2 ++ Objects/typeobject.c | 1 + 3 files changed, 13 insertions(+) create mode 100644 Misc/NEWS.d/next/Core and Builtins/2025-10-21-06-51-50.gh-issue-140406.0gJs8M.rst diff --git a/Lib/test/test_builtin.py b/Lib/test/test_builtin.py index 88ece3cd8deacd..bbc18d08695d3a 100644 --- a/Lib/test/test_builtin.py +++ b/Lib/test/test_builtin.py @@ -1094,6 +1094,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 2dface4b758224..7e6cdd1ede309e 100644 --- a/Objects/typeobject.c +++ b/Objects/typeobject.c @@ -9530,6 +9530,7 @@ slot_tp_hash(PyObject *self) return -1; if (!PyLong_Check(res)) { + Py_DECREF(res); PyErr_SetString(PyExc_TypeError, "__hash__ method should return an integer"); return -1; From 1341fa3ad42184d25a7c2c8a634a37e77592fa7f Mon Sep 17 00:00:00 2001 From: Peter Bierma Date: Tue, 21 Oct 2025 20:45:37 -0400 Subject: [PATCH 2/2] [3.13] gh-140406: Fix memory leak upon `__hash__` returning a non-integer (GH-140411) (cherry picked from commit 71db05a12d9953a96f809d84b4d0d452a464e431) Co-authored-by: Peter Bierma