Skip to content

bpo-29839: Raise ValueError rather than OverflowError in len() for negative values. #701

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Apr 16, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions Lib/test/test_builtin.py
Original file line number Diff line number Diff line change
Expand Up @@ -770,10 +770,18 @@ class FloatLen:
def __len__(self):
return 4.5
self.assertRaises(TypeError, len, FloatLen())
class NegativeLen:
def __len__(self):
return -10
self.assertRaises(ValueError, len, NegativeLen())
class HugeLen:
def __len__(self):
return sys.maxsize + 1
self.assertRaises(OverflowError, len, HugeLen())
class HugeNegativeLen:
def __len__(self):
return -sys.maxsize-10
self.assertRaises(ValueError, len, HugeNegativeLen())
class NoLenMethod(object): pass
self.assertRaises(TypeError, len, NoLenMethod())

Expand Down
3 changes: 3 additions & 0 deletions Misc/NEWS
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,9 @@ What's New in Python 3.7.0 alpha 1?
Core and Builtins
-----------------

- bpo-29839: len() now raises ValueError rather than OverflowError if
__len__() returned a large negative integer.

- bpo-11913: README.rst is now included in the list of distutils standard
READMEs and therefore included in source distributions.

Expand Down
19 changes: 13 additions & 6 deletions Objects/typeobject.c
Original file line number Diff line number Diff line change
Expand Up @@ -5924,14 +5924,21 @@ slot_sq_length(PyObject *self)

if (res == NULL)
return -1;
len = PyNumber_AsSsize_t(res, PyExc_OverflowError);
Py_DECREF(res);
if (len < 0) {
if (!PyErr_Occurred())
PyErr_SetString(PyExc_ValueError,
"__len__() should return >= 0");

Py_SETREF(res, PyNumber_Index(res));
if (res == NULL)
return -1;

assert(PyLong_Check(res));
if (Py_SIZE(res) < 0) {
PyErr_SetString(PyExc_ValueError,
"__len__() should return >= 0");
return -1;
}

len = PyNumber_AsSsize_t(res, PyExc_OverflowError);
assert(len >= 0 || PyErr_ExceptionMatches(PyExc_OverflowError));
Py_DECREF(res);
return len;
}

Expand Down