Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any case where len(someObj) does not call someObj's __len__ function?

Is there any case where len(someObj) does not call someObj's __len__ function?

I recently replaced the former with the latter in a (sucessful) effort to speed up some code. I want to make sure there's not some edge case somewhere where len(someObj) is not the same as someObj.__len__().

like image 501
David Locke Avatar asked Jan 30 '09 15:01

David Locke


1 Answers

If __len__ returns a length over sys.maxsize, len() will raise an exception. This isn't true of calling __len__ directly. (In fact you could return any object from __len__ which won't be caught unless it goes through len().)

like image 74
Benjamin Peterson Avatar answered Nov 06 '22 10:11

Benjamin Peterson