Is there a case where len (someObj) does not call the someObj __len__ function?

Is there a case where len (someObj) does not call the someObj __len__ function?

I recently replaced the first with the last in a (successful) attempt to speed up work on some code. I want to make sure that there is no boundary case where len (someObj) does not match someObj. __len__ ().

+5
python
Jan 30 '09 at 15:58
source share
4 answers

If __len__ returns a length over sys.maxsize , len() will throw an exception. This is not true for a direct call to __len__ . (In fact, you can return any object from __len__ that will not be detected if it does not go through len() .)

+5
Jan 30 '09 at 20:21
source share

What acceleration have you seen? I can’t imagine that it was noticeable?

From http://mail.python.org/pipermail/python-list/2002-May/147079.html

there is no difference in certain situations, but using len () is preferable for several reasons.

Firstly, it is not recommended to call __methods__ independently, they are intended for use by other parts of python.

len() will work on any type of sequence object ( lists , tuples and all). __len__ will only work with class instances using the __len__ method.

len() will return a more appropriate exception on objects without length.

+8
Jan 30 '09 at 16:07
source share

I think the answer is that it will always work - according to Python docs:

 __len__(self): 

Called to implement the built-in len () function. Should return the length of the object, an integer> = 0. In addition, an object that does not define the __nonzero__() method and the __len__() method returns zero, is considered logical in a Boolean context.

+1
Jan 30 '09 at 16:03
source share

According to Mark Pilgrim, this seems like no. len(someObj) same as someObj.__len__() ;

Hurrah!

-one
Jan 30 '09 at 16:01
source share



All Articles