summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorRaymond Hettinger <python@rcn.com>2007-02-07 21:40:49 (GMT)
committerRaymond Hettinger <python@rcn.com>2007-02-07 21:40:49 (GMT)
commit113776c41134bd499efe2b404e25446b31b5c48d (patch)
treedfb8307321fb2f8cd09e42c5b85e3383c895b845
parent05d59e2df7a780ad56b4e40f16c0a7584457b1cd (diff)
downloadcpython-113776c41134bd499efe2b404e25446b31b5c48d.zip
cpython-113776c41134bd499efe2b404e25446b31b5c48d.tar.gz
cpython-113776c41134bd499efe2b404e25446b31b5c48d.tar.bz2
Check for a common user error with defaultdict().
-rw-r--r--Lib/test/test_defaultdict.py7
-rw-r--r--Misc/NEWS2
-rw-r--r--Modules/collectionsmodule.c8
3 files changed, 13 insertions, 4 deletions
diff --git a/Lib/test/test_defaultdict.py b/Lib/test/test_defaultdict.py
index 134b5a8..1834f90 100644
--- a/Lib/test/test_defaultdict.py
+++ b/Lib/test/test_defaultdict.py
@@ -47,6 +47,7 @@ class TestDefaultDict(unittest.TestCase):
self.assertEqual(err.args, (15,))
else:
self.fail("d2[15] didn't raise KeyError")
+ self.assertRaises(TypeError, defaultdict, 1)
def test_missing(self):
d1 = defaultdict()
@@ -60,10 +61,10 @@ class TestDefaultDict(unittest.TestCase):
self.assertEqual(repr(d1), "defaultdict(None, {})")
d1[11] = 41
self.assertEqual(repr(d1), "defaultdict(None, {11: 41})")
- d2 = defaultdict(0)
- self.assertEqual(d2.default_factory, 0)
+ d2 = defaultdict(int)
+ self.assertEqual(d2.default_factory, int)
d2[12] = 42
- self.assertEqual(repr(d2), "defaultdict(0, {12: 42})")
+ self.assertEqual(repr(d2), "defaultdict(<type 'int'>, {12: 42})")
def foo(): return 43
d3 = defaultdict(foo)
self.assert_(d3.default_factory is foo)
diff --git a/Misc/NEWS b/Misc/NEWS
index 1f216f7..e628f44 100644
--- a/Misc/NEWS
+++ b/Misc/NEWS
@@ -103,6 +103,8 @@ Core and builtins
Extension Modules
-----------------
+- collections.defaultdict() now verifies that the factory function is callable.
+
- Bug #1486663: don't reject keyword arguments for subclasses of builtin
types.
diff --git a/Modules/collectionsmodule.c b/Modules/collectionsmodule.c
index a4cdcfa..f98bd49 100644
--- a/Modules/collectionsmodule.c
+++ b/Modules/collectionsmodule.c
@@ -1252,8 +1252,14 @@ defdict_init(PyObject *self, PyObject *args, PyObject *kwds)
newargs = PyTuple_New(0);
else {
Py_ssize_t n = PyTuple_GET_SIZE(args);
- if (n > 0)
+ if (n > 0) {
newdefault = PyTuple_GET_ITEM(args, 0);
+ if (!PyCallable_Check(newdefault)) {
+ PyErr_SetString(PyExc_TypeError,
+ "first argument must be callable");
+ return -1;
+ }
+ }
newargs = PySequence_GetSlice(args, 1, n);
}
if (newargs == NULL)