1. Armin Rigo
  2. cpython-withatomic

Commits

Benjamin Peterson  committed da0070c

Merged revisions 69451 via svnmerge from
svn+ssh://pythondev@svn.python.org/python/branches/py3k

........
r69451 | benjamin.peterson | 2009-02-08 15:07:20 -0600 (Sun, 08 Feb 2009) | 1 line

fix len() when __len__() returns a non number type #5137
........

  • Participants
  • Parent commits fd74b0c
  • Branches 3.0

Comments (0)

Files changed (3)

File Lib/test/test_builtin.py

View file
  • Ignore whitespace
             def __len__(self):
                 raise ValueError
         self.assertRaises(ValueError, len, BadSeq())
+        class InvalidLen:
+            def __len__(self):
+                return None
+        self.assertRaises(TypeError, len, InvalidLen())
+        class FloatLen:
+            def __len__(self):
+                return 4.5
+        self.assertRaises(TypeError, len, FloatLen())
+        class HugeLen:
+            def __len__(self):
+                return sys.maxsize + 1
+        self.assertRaises(OverflowError, len, HugeLen())
 
     def test_map(self):
         self.assertEqual(

File Misc/NEWS

View file
  • Ignore whitespace
 Core and Builtins
 -----------------
 
+- Issue #5137: Make len() correctly raise a TypeError when a __len__ method
+  returns a non-number type.
+
 - Issue #5182: Removed memoryview.__str__.
 
 - Issue #1717: Removed builtin cmp() function, dropped tp_compare

File Objects/typeobject.c

View file
  • Ignore whitespace
 
 	if (res == NULL)
 		return -1;
-	len = PyLong_AsSsize_t(res);
+	len = PyNumber_AsSsize_t(res, PyExc_OverflowError);
 	Py_DECREF(res);
 	if (len < 0) {
 		if (!PyErr_Occurred())