Commit ee1ae7cc authored by Benjamin Peterson's avatar Benjamin Peterson

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

parent c7055a59
...@@ -611,6 +611,18 @@ class BuiltinTest(unittest.TestCase): ...@@ -611,6 +611,18 @@ class BuiltinTest(unittest.TestCase):
def __len__(self): def __len__(self):
raise ValueError raise ValueError
self.assertRaises(ValueError, len, BadSeq()) 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): def test_map(self):
self.assertEqual( self.assertEqual(
......
...@@ -12,6 +12,9 @@ What's New in Python 3.1 alpha 0 ...@@ -12,6 +12,9 @@ What's New in Python 3.1 alpha 0
Core and Builtins 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 #5182: Removed memoryview.__str__.
- Issue #1717: Removed builtin cmp() function, dropped tp_compare - Issue #1717: Removed builtin cmp() function, dropped tp_compare
......
...@@ -4618,7 +4618,7 @@ slot_sq_length(PyObject *self) ...@@ -4618,7 +4618,7 @@ slot_sq_length(PyObject *self)
if (res == NULL) if (res == NULL)
return -1; return -1;
len = PyLong_AsSsize_t(res); len = PyNumber_AsSsize_t(res, PyExc_OverflowError);
Py_DECREF(res); Py_DECREF(res);
if (len < 0) { if (len < 0) {
if (!PyErr_Occurred()) if (!PyErr_Occurred())
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment