From ca04d8930a2c382bc0bae37e87d1bd9e6a9d7d5a Mon Sep 17 00:00:00 2001 From: tangyuan0821 Date: Mon, 22 Jun 2026 10:35:48 +0800 Subject: [PATCH 1/2] gh-130821: Add type info to error messages for __len__ and __sizeof__ --- Objects/typeobject.c | 4 ++-- Python/sysmodule.c | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/Objects/typeobject.c b/Objects/typeobject.c index 59593fd0f6a0b7..8abc1148064c7b 100644 --- a/Objects/typeobject.c +++ b/Objects/typeobject.c @@ -10625,8 +10625,8 @@ slot_sq_length(PyObject *self) assert(PyLong_Check(res)); if (_PyLong_IsNegative((PyLongObject *)res)) { Py_DECREF(res); - PyErr_SetString(PyExc_ValueError, - "__len__() should return >= 0"); + PyErr_Format(PyExc_ValueError, + "%T.__len__() must return >= 0", self); return -1; } diff --git a/Python/sysmodule.c b/Python/sysmodule.c index d9f7b9c449cfb9..6dd593e5340ccf 100644 --- a/Python/sysmodule.c +++ b/Python/sysmodule.c @@ -1933,8 +1933,8 @@ _PySys_GetSizeOf(PyObject *o) return (size_t)-1; if (size < 0) { - _PyErr_SetString(tstate, PyExc_ValueError, - "__sizeof__() should return >= 0"); + _PyErr_Format(tstate, PyExc_ValueError, + "%T.__sizeof__() must return >= 0", o); return (size_t)-1; } From abf13a8cd56177abace9730472646977f8e27e47 Mon Sep 17 00:00:00 2001 From: tangyuan0821 Date: Mon, 22 Jun 2026 10:42:12 +0800 Subject: [PATCH 2/2] gh-130821: Add news entry for __len__ and __sizeof__ error message fix --- .../2026-06-22-10-39-56.gh-issue-130821.b5e011.rst | 2 ++ 1 file changed, 2 insertions(+) create mode 100644 Misc/NEWS.d/next/Core_and_Builtins/2026-06-22-10-39-56.gh-issue-130821.b5e011.rst diff --git a/Misc/NEWS.d/next/Core_and_Builtins/2026-06-22-10-39-56.gh-issue-130821.b5e011.rst b/Misc/NEWS.d/next/Core_and_Builtins/2026-06-22-10-39-56.gh-issue-130821.b5e011.rst new file mode 100644 index 00000000000000..1f6bed1965ae2b --- /dev/null +++ b/Misc/NEWS.d/next/Core_and_Builtins/2026-06-22-10-39-56.gh-issue-130821.b5e011.rst @@ -0,0 +1,2 @@ +Add type information to error messages for ``__len__()`` and ``__sizeof__()``. +Patch by tangyuan0821.