Skip to content

Commit 3576e1a

Browse files
[3.13] gh-78465: Fix error message for cls.__new__(cls, ...) where cls is not instantiable (GH-135981) (GH-136031)
Previous error message suggested to use cls.__new__(), which obviously does not work. Now the error message is the same as for cls(...). (cherry picked from commit c45f4f3)
1 parent ea25f4a commit 3576e1a

File tree

4 files changed

+9
-6
lines changed

4 files changed

+9
-6
lines changed

Lib/test/support/__init__.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2269,6 +2269,7 @@ def check_disallow_instantiation(testcase, tp, *args, **kwds):
22692269
qualname = f"{name}"
22702270
msg = f"cannot create '{re.escape(qualname)}' instances"
22712271
testcase.assertRaisesRegex(TypeError, msg, tp, *args, **kwds)
2272+
testcase.assertRaisesRegex(TypeError, msg, tp.__new__, tp, *args, **kwds)
22722273

22732274
def get_recursion_depth():
22742275
"""Get the recursion depth of the caller function.

Lib/test/test_sys.py

Lines changed: 1 addition & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -894,12 +894,7 @@ def test_sys_flags(self):
894894
def assert_raise_on_new_sys_type(self, sys_attr):
895895
# Users are intentionally prevented from creating new instances of
896896
# sys.flags, sys.version_info, and sys.getwindowsversion.
897-
arg = sys_attr
898-
attr_type = type(sys_attr)
899-
with self.assertRaises(TypeError):
900-
attr_type(arg)
901-
with self.assertRaises(TypeError):
902-
attr_type.__new__(attr_type, arg)
897+
support.check_disallow_instantiation(self, type(sys_attr), sys_attr)
903898

904899
def test_sys_flags_no_instantiation(self):
905900
self.assert_raise_on_new_sys_type(sys.flags)
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Fix error message for ``cls.__new__(cls, ...)`` where ``cls`` is not
2+
instantiable builtin or extension type (with ``tp_new`` set to ``NULL``).

Objects/typeobject.c

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9087,6 +9087,11 @@ tp_new_wrapper(PyObject *self, PyObject *args, PyObject *kwds)
90879087
/* If staticbase is NULL now, it is a really weird type.
90889088
In the spirit of backwards compatibility (?), just shut up. */
90899089
if (staticbase && staticbase->tp_new != type->tp_new) {
9090+
if (staticbase->tp_new == NULL) {
9091+
PyErr_Format(PyExc_TypeError,
9092+
"cannot create '%s' instances", subtype->tp_name);
9093+
return NULL;
9094+
}
90909095
PyErr_Format(PyExc_TypeError,
90919096
"%s.__new__(%s) is not safe, use %s.__new__()",
90929097
type->tp_name,

0 commit comments

Comments
 (0)