why no 'length' method in sequences ?

Michael Gilfix mgilfix at eecs.tufts.edu
Fri Apr 19 11:27:39 EDT 2002


On Fri, Apr 19 @ 07:08, Paul Boddie wrote:
> Just van Rossum <just at xs4all.nl> wrote in message news:<just-2DF829.09350419042002 at news1.xs4all.nl>...
> > 
> >     len(o)
> 
> [vs]
> 
> >     o.keys()
> > 
> > This seems quite arbitrary, even to me, after maybe 6 years of working 
> > with Python. If o.__len__() were spelled o.len(), we could easily do 
> > without the len() builtin. (Note that I don't argue we could do without 
> > functions: I wouldn't want to miss them for the world...)
> 
> I suppose that len is considered near-universal, although len(123)
> reveals a notable exception, whereas very few objects bear the notion
> of having "keys". Therefore, near-universal "protocols" (as I believe
> someone once called them) are supported through built-in functions,
> and other "protocols" are supported more or less exclusively through
> methods.
> 
> Of course, providing len as a method on all appropriate objects would
> be more consistent, but as far as Python is concerned right now, it
> seems redundant and potentially confusing: "But I thought len was a
> function!" exclaimed the beginner.

  I think that comes closest to touching on the reason. Of course this
is all philosophical but here's my shot :) Length is something that is
intrisic to object. If we visualize objects as being something in the
real world, then they would have some sort of dimension. __len__ is
an extension of that dimension in some sense and it makes sense that
I have to use an action to obtain that length.  In the case of keys,
keys are a special attribute of dictionaries only and I can think of
the action of retrieving keys as opening up the dict and pulling them
out, a member function.

  Just as you say, these near universal protocols are just ways of
describing how objects behave in the word under certain actions but if
you implements an __add__ function, you still need to invoke the '+'
action to elicit the behavior.

               -- Mike

-- 
Michael Gilfix
mgilfix at eecs.tufts.edu

For my gpg public key:
http://www.eecs.tufts.edu/~mgilfix/contact.html





More information about the Python-list mailing list