Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit b02bb5e

Browse files
committed
Replace BadInternalCall with TypeError. Add a test case. Fix whitespace.
Just van Rossum showed a weird, but clever way for pure python code to trigger the BadInternalCall. The C code had assumed that calling a class constructor would return an instance of that class; however, classes that abuse __new__ can invalidate that assumption.
1 parent 21d77f5 commit b02bb5e

2 files changed

Lines changed: 10 additions & 2 deletions

File tree

Lib/test/test_types.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -558,6 +558,13 @@ class dictlike(dict): pass
558558
raise TestFailed, 'dictsubclass.fromkeys created wrong type'
559559
if type(dictlike().fromkeys('a')) is not dictlike:
560560
raise TestFailed, 'dictsubclass.fromkeys created wrong type'
561+
from UserDict import UserDict
562+
class mydict(dict):
563+
def __new__(cls, *args, **kwargs):
564+
return UserDict(*args, **kwargs)
565+
try: mydict.fromkeys('a b c'.split())
566+
except TypeError: pass
567+
else: raise TestFailed, 'dict.fromkeys() failed to detect non-dict class.'
561568
# dict.copy()
562569
d = {1:1, 2:2, 3:3}
563570
if d.copy() != {1:1, 2:2, 3:3}: raise TestFailed, 'dict copy'

Objects/dictobject.c

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -973,15 +973,16 @@ dict_fromkeys(PyObject *mp, PyObject *args)
973973
PyObject *cls;
974974
int status;
975975

976-
if (!PyArg_ParseTuple(args, "OO|O:fromkeys", &cls, &seq, &value))
976+
if (!PyArg_ParseTuple(args, "OO|O:fromkeys", &cls, &seq, &value))
977977
return NULL;
978978

979979
d = PyObject_CallObject(cls, NULL);
980980
if (d == NULL)
981981
return NULL;
982982
if (!PyDict_Check(d)) {
983-
PyErr_BadInternalCall();
984983
Py_DECREF(d);
984+
PyErr_SetString(PyExc_TypeError,
985+
"class constructor must return a subclass of dict");
985986
return NULL;
986987
}
987988

0 commit comments

Comments
 (0)