list.__len__() or len(list)

Carl Banks pavlovevidence at gmail.com
Wed May 14 15:35:17 EDT 2008


On May 14, 11:07 am, Nikhil <mnik... at gmail.com> wrote:
> Christian Heimes wrote:
> > Ian Kelly schrieb:
> >> The purpose of obj.__len__() is to implement len(obj), which simply
> >> calls it.  So obj.__len__() may be faster, but only marginally.  The
> >> reason to prefer len(obj) is that if you inadvertently pass an object
> >> that does not implement __len__, you get the more appropriate
> >> TypeError rather than an AttributeError.
>
> > len(obj) is faster than obj.__len__() for several types like str. In
> > general len() is as least as fast __len__(). len() also does some extra
> > sanity checks.
>
> > python2.5 -m timeit "'abc'.__len__()"
> > 1000000 loops, best of 3: 0.453 usec per loop
>
> > python2.5 -m timeit "len('abc')"
> > 1000000 loops, best of 3: 0.292 usec per loop
>
> > Common code paths are already highly optimized. Don't try to be clever
> > unless you really understand what happens inside the interpreter. The
> > __internal__ methods are called magic methods for a reason. ;)
>
> > Christian
>
> Thanks for the useful insight.
> Then why to have __len__() internal method at all when the built-in
> len() is faster?
> I heard, in Python3, this internal method is being pruned/renamed to
> something else? Can someone please shed light here?

My advice is to think of len() as an operator.  Like other operators,
it can be overloaded using the __opname__ syntax:

-x calls x.__neg__
x+2 calls x.__add__
len(x) calls x.__len__

It's not really an operator: it's a regular built-in function, has no
special syntax, and no opcodes associated with it, but in sometimes it
helps to think of it as one.


Carl Banks



More information about the Python-list mailing list