Title: Avoid raising OverflowError in len() when __len__() returns negative large value
Type: enhancement Stage: patch review
Components: Interpreter Core Versions: Python 3.7
Status: open Resolution:
Dependencies: Superseder:
Assigned To: Nosy List: Oren Milman, barry, haypo, serhiy.storchaka
Priority: normal Keywords:

Created on 2017-03-17 19:52 by serhiy.storchaka, last changed 2017-03-17 20:28 by barry.

Pull Requests
URL Status Linked Edit
PR 701 open serhiy.storchaka, 2017-03-17 19:57
Messages (2)
msg289779 - (view) Author: Serhiy Storchaka (serhiy.storchaka) * (Python committer) Date: 2017-03-17 19:52
For now len() raises ValueError if __len__() returns small negative integer and OverflowError if __len__() returns large negative integer. 

>>> class NegativeLen:
...     def __len__(self):
...         return -10
>>> len(NegativeLen())
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: __len__() should return >= 0
>>> class HugeNegativeLen:
...     def __len__(self):
...         return -sys.maxsize-10
>>> len(HugeNegativeLen())
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
OverflowError: cannot fit 'int' into an index-sized integer

Proposed patch makes it always raising ValueError.
msg289782 - (view) Author: Barry A. Warsaw (barry) * (Python committer) Date: 2017-03-17 20:28
I was going to say that this is an API change, but given that without this, folks would have to catch both exceptions and now only have to catch one of them, it isn't.
Date User Action Args
2017-03-17 20:35:34serhiy.storchakalinkissue29840 dependencies
2017-03-17 20:28:43barrysetnosy: + barry
messages: + msg289782
2017-03-17 19:58:01serhiy.storchakalinkissue29833 dependencies
2017-03-17 19:57:35serhiy.storchakasetpull_requests: + pull_request575
2017-03-17 19:52:14serhiy.storchakacreate