A Python 3000 Question

Neil Cerutti horpner at yahoo.com
Wed Oct 31 08:44:53 EDT 2007


On 2007-10-30, Jean-Paul Calderone <exarkun at divmod.com> wrote:
> On Tue, 30 Oct 2007 15:25:54 GMT, Neil Cerutti <horpner at yahoo.com> wrote:
>>On 2007-10-30, Eduardo O. Padoan <eduardo.padoan at gmail.com> wrote:
>>> This is a FAQ:
>>> http://effbot.org/pyfaq/why-does-python-use-methods-for-some-functionality-e-g-list-index-but-functions-for-other-e-g-len-list.htm
>>
>>Holy Airy Persiflage Batman!
>>
>>Python 2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC v.1310 32 bit (Intel)] on
>>win32
>>Type "help", "copyright", "credits" or "license" for more information.
>>>>> import timeit
>>>>> timeit.Timer('len(seq)', 'seq = range(100)').timeit()
>>0.20332271187463391
>>>>> timeit.Timer('seq.__len__()', 'seq = range(100)').timeit()
>>0.48545737364457864
>
> Not sure what you're trying to demonstrate.  

That len as a builtin can be faster than len as an attribute, and
doesn't need any further explanation than that.

> Here's another pointless transcript, though:
>
>     exarkun at charm:~$ python -m timeit -s '
>     seq = range(100)
>     ' 'len(seq)'
>     1000000 loops, best of 3: 0.211 usec per loop
>     exarkun at charm:~$ python -m timeit -s '
>     seq = range(100)
>     ' 'seq.__len__()'
>     1000000 loops, best of 3: 0.317 usec per loop
>     exarkun at charm:~$ python -m timeit -s '
>     class X(object):
>       def __len__(self): return 100
>     seq = X()
>     ' 'seq.__len__()'
>     1000000 loops, best of 3: 0.427 usec per loop
>     exarkun at charm:~$ python -m timeit -s '
>     class X(object):
>       def __len__(self): return 100
>     seq = X()
>     ' 'len(seq)'
>     1000000 loops, best of 3: 0.701 usec per loop
>     exarkun at charm:~$
>
> I guess we've learned that sometimes something is faster than
> something else, and other times the contrary.

It demonstratess that len is faster than __len__ for lists (and
probably for all builtin types) but not for user defined type X
(and probably not for any user defined type).

Or it may demonstrate that I'm all wet. If so, I've brought my
shampoo.

But if I'm wrong about the performance benefits then I guess I'm
still in the dark about why len is a builtin. The only compelling
thing in the linked explation was the signatures of the guys who
wrote the artible. (Guido does admit he would, "hate to lose it
as a builtin," but doesn't explain why that should be a bad
thing).

-- 
Neil Cerutti
It isn't pollution that is hurting the environment; it's the impurities in our
air and water that are doing it. --Dan Quayle



More information about the Python-list mailing list