[Python-3000] Should len() clip to sys.maxsize or raiseOverflowError?

Raymond Hettinger python at rcn.com
Tue Sep 2 22:35:18 CEST 2008


>> That makes sense to me and there a probably plenty of examples.
>> However, I worry more about other examples that will fail
>> and do so it a way that is nearly impossible to find through
>> code review (because the code IS correct as written).
>>
>>  n = len(log_entries)
>>  if log_entries[n] in handled:
> 
> This should raise an IndexError. I think you meant something else?
> 
>>     log_entries.pop(n)

Right. It should have been n-1 in my quick example.
The idea is that if the len() return value is actually being use for something
(in this case indexing, but possibly also slicing, resource managment, etc),
then the app will silently start doing the wrong thing.

  next_ticket_number = len(tickets)
  create_new_ticket_form(time(), next_ticket_number)

ISTM, there are many uses for len() when it is bad news if the result
is less than the real length.  Those cases will be harder to detect and
correct than if an overflow was raised.

Raymond



More information about the Python-3000 mailing list