]> granicus.if.org Git - python/commitdiff
Validate that __length_hint__ returns a usable result.
authorRaymond Hettinger <python@rcn.com>
Tue, 3 Feb 2009 02:12:10 +0000 (02:12 +0000)
committerRaymond Hettinger <python@rcn.com>
Tue, 3 Feb 2009 02:12:10 +0000 (02:12 +0000)
Lib/test/test_iterlen.py
Objects/abstract.c

index 2123501bcb55f6599da5d2a989b5e1a0969668de..cd928013f56750ccf97ab988585834972363c43c 100644 (file)
@@ -208,6 +208,11 @@ class BadLengthHint(object):
     def __length_hint__(self):
         raise RuntimeError('hello')
 
+class NoneLengthHint(object):
+    def __iter__(self): return iter(range(10))
+    def __length_hint__(self):
+        return None
+
 class TestLengthHintExceptions(unittest.TestCase):
 
     def test_issue1242657(self):
@@ -219,6 +224,11 @@ class TestLengthHintExceptions(unittest.TestCase):
         self.assertRaises(RuntimeError, b.extend, BadLen())
         self.assertRaises(RuntimeError, b.extend, BadLengthHint())
 
+    def test_invalid_hint(self):
+        # Make sure an invalid result doesn't muck-up the works
+        self.assertEqual(list(NoneLengthHint()), list(range(10)))
+
+
 def test_main():
     unittests = [
         TestRepeat,
index 86e2c394804b2dd33fe9dbe0937c670623906f80..7d0ed06117f3781e13b6f7599b8a54a55de49e6f 100644 (file)
@@ -105,7 +105,7 @@ _PyObject_LengthHint(PyObject *o, Py_ssize_t defaultvalue)
                PyErr_Clear();
                return defaultvalue;
        }
-       rv = PyLong_AsSsize_t(ro);
+       rv = PyLong_Check(ro) ? PyLong_AsSsize_t(ro) : defaultvalue;
        Py_DECREF(ro);
        return rv;
 }