Repository navigation
Avoid raising OverflowError in len() when __len__() returns negative large value #74025
Description
Activity
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.
- added3.7 (EOL)end of lifeend of lifeinterpreter-core(Objects, Python, Grammar, and Parser dirs)(Objects, Python, Grammar, and Parser dirs)type-featureA feature request or enhancementA feature request or enhancement
on Mar 17, 2017 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.
https://docs.python.org/3/library/functions.html#len * does not specify the exception. In such cases, we occasionally change exception in x.y.0 releases without prior notice other than News and What's New. Also, I think unnecessarily exposing a compile-switch dependent internal detail, as now, is almost a bug. So +1 to applying in 3.7
- The doc does not specify that 'length' cannot be non-negative. Perhaps it should, so no-one will think that they can hijack '__len__' to return something that is not a length, as usually understood.
The doc does not specify that 'length' cannot be non-negative.
It does. https://docs.python.org/3/reference/datamodel.html#object.\_\_len__
.. method:: object.__len__(self)
Called to implement the built-in function :func:`len`. Should return the length
of the object, an integer ``>=`` 0.
Note: these values reflect the state of the issue at the time it was migrated and might not reflect the current state.
Show more details
GitHub fields:
bugs.python.org fields: