Skip to content

Commit cf5376c

Browse files
cmaloneyclaude
andcommitted
Match main's error text when complex() gets more than 2 arguments
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 68195ff commit cf5376c

2 files changed

Lines changed: 9 additions & 6 deletions

File tree

‎Lib/test/test_complex.py‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -611,8 +611,10 @@ def check(z, x, y):
611611
check(complex(4.25, imag=1.5), 4.25, 1.5)
612612
self.assertRaisesRegex(TypeError, r"given by name \('real'\) and position \(1\)",
613613
complex, 4.25, real=1.5)
614-
self.assertRaisesRegex(TypeError, r"given by name \('imag'\) and position \(2\)",
614+
self.assertRaisesRegex(TypeError, r"takes at most 2 arguments \(3 given\)",
615615
complex, 4.25, 1.5, imag=1.5)
616+
self.assertRaisesRegex(TypeError, r"takes at most 2 arguments \(3 given\)",
617+
complex, 1, 2, real=3)
616618

617619
# check that the sign of a zero in the real or imaginary part
618620
# is preserved when constructing from two floats.

‎Objects/complexobject.c‎

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1214,6 +1214,12 @@ complex_new_impl(PyTypeObject *type, PyObject *real_pos, PyObject *imag_pos,
12141214
int ci_is_complex = 0;
12151215

12161216
/* See the comment before complex_from_arg(). */
1217+
int nargs = (real_pos != NULL) + (imag_pos != NULL) + (r != NULL) + (i != NULL);
1218+
if (nargs > 2) {
1219+
PyErr_Format(PyExc_TypeError,
1220+
"complex() takes at most 2 arguments (%d given)", nargs);
1221+
return NULL;
1222+
}
12171223
if (real_pos != NULL) {
12181224
if (r != NULL) {
12191225
PyErr_SetString(PyExc_TypeError, "argument for complex() given "
@@ -1226,11 +1232,6 @@ complex_new_impl(PyTypeObject *type, PyObject *real_pos, PyObject *imag_pos,
12261232
r = real_pos;
12271233
}
12281234
if (imag_pos != NULL) {
1229-
if (i != NULL) {
1230-
PyErr_SetString(PyExc_TypeError, "argument for complex() given "
1231-
"by name ('imag') and position (2)");
1232-
return NULL;
1233-
}
12341235
i = imag_pos;
12351236
}
12361237
if (r == NULL) {

0 commit comments

Comments
 (0)