A Python 3000 Question

Carl Banks pavlovevidence at gmail.com
Wed Oct 31 15:59:58 CET 2007

On Oct 31, 8:44 am, Neil Cerutti <horp... at yahoo.com> wrote:
> On 2007-10-30, George Sakkis <george.sak... at gmail.com> wrote:
> > On Oct 30, 11:25 am, Neil Cerutti <horp... at yahoo.com> wrote:
> >> On 2007-10-30, Eduardo O. Padoan <eduardo.pad... at gmail.com> wrote:
> >> > This is a FAQ:
> >> >http://effbot.org/pyfaq/why-does-python-use-methods-for-some-function...
> >> 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
> > Common mistake; try this instead:
> > timeit.Timer('seqlen()',
> >              'seq = range(100); seqlen=seq.__len__').timeit()
> Why would I want to do that?

If your point is to measure the time of just the operation as
accurately as possible, you don't want the extra dict lookup in
seq.__len__ affecting things.  Though it seems to me that if your
intention is to determine if builtin or method style is faster, it's
not such a great idea to replace the method call with a builtin call.

As for what benefit there is for len to be a builtin:

Python considers len to be an operator for all intents and purposes.
Python chose to spell this operator like a regular function, but it
could easily have given a special syntax to the length operation (for
instance, $#x).

Do you think that, if the length operation had its own syntax, people
would be saying "No, length shouldn't be an operator, it should be a
method"?  I don't think so; length is a fundamental and ubiquitous
operation and it wouldn't be unreasonable to give it its own syntax.

That suggests to me that, when people complain that len should be a
method, their complaint is a superficial complaint about spelling.
They are not considering whether len is important enough to be an
operator or not.

Carl Banks

More information about the Python-list mailing list