There are cases where len(someObj)
is not the same as someObj.__len__()
since len()
validates __len__()
's return value. Here are the possible errors in Python 3.6.9:
Too low, i.e. less than 0
ValueError: __len__() should return >= 0
Too high, i.e. greater than sys.maxsize
(CPython-specific, per the docs)
OverflowError: cannot fit 'int' into an index-sized integer
An invalid type, e.g float
TypeError: 'float' object cannot be interpreted as an integer
Missing, e.g. len(object)
TypeError: object of type 'type' has no len()
I mention this because object.__len__()
raises a different exception, AttributeError
.
It's also worth noting that range(sys.maxsize+1)
is valid, but its __len__()
raises an exception:
OverflowError: Python int too large to convert to C ssize_t
len
is supposed to be return the number of elements in a collection, returning something bigger thansys.maxsize
is almost certainly nonsense. – Mendez