why no 'length' method in sequences ?

Christopher A. Craig com-nospam at ccraig.org
Fri Apr 19 22:29:36 EDT 2002


"Richard Gruet" <rjgruet at yahoo.com> writes:

> Actually, as Alex pointed out, a single len() method in a
> hypothetical 'sequence' base class would be mythical, simply because
> there is no common implementation of len() for all kinds of
> collection (I just forgot this!).

I have the utmost respect for Alex, so I don't understand why I can't
figure out what he is saying, but why couldn't len(a) be equivalent to
a.len()?

The len() builtin calls PyObject_Size(), which, in turn, tries two things: 
obj->ob_type->tp_as_sequence->sq_length()
then
obj->ob_type->tp_as_mapping->mp_length()

In the case of class instances both are defined to execute the __len__
method.

Also, the type metatype defines __len__ to be PyObject_Size for all of
it's subtypes iff either of those two C functions is defined.  I don't
see why naming it "len" instead of (or even in addition too) "__len__"
wouldn't work.

The main problem I see with this is that it wouldn't have worked
before you got the ability to subtype in Python2.2, so historically it
had to be a method before.  Plus adding it now means you either have a
stub "len" method which may not work, or you have a major backward
incompatibility.  

I personally disagree with adding it now, but not because it can't be
done.

-- 
Christopher A. Craig <com-nospam at ccraig.org>
"Tragedy is when I cut my finger.  Comedy is when you fall in an open
sewer and die."  Mel Brooks.





More information about the Python-list mailing list