◐ Shell
clean mode source ↗

Message 289779 - Python tracker

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.