why no 'length' method in sequences ?

Richard Gruet rjgruet at yahoo.com
Fri Apr 19 19:18:42 EDT 2002


"John Roth" <johnroth at ameritech.net> wrote in message
news:uc14cjalpru3b5 at news.supernews.com...
>
> "Richard Gruet" <rjgruet at yahoo.com> wrote in message
> news:a9nbuq$916$1 at aphrodite.grec.isp.9tel.net...
> > Alex
> >
> > And BTW, people would not to have implement any __len__ method if all
> the
> > sequence types would derive from a common ancestor (sequence), in
> which the
> > (in)famous method would be implemented. Would it be completely
> nonsensical ?
> > I have been told that starting from 2.2, new style classes (including
> most
> > built-in types) all derive from a common base class 'object'.
>
> As far as I know, that's correct. Inserting a .len() method in the
> object class would automatically make it available to all new style
> classes.
>
> As far as I can see, there is one major issue with this: if the
> class in question didn't have a __len__() method, it would
> still have the (inherited) len() method. This could be rigged to
> raise an exception, but it would still be a bit of a trap for the
> unwary.
>
> There's also the question of the inheritance hierarchy, which I don't
pretend to understand.
> It seems to be a case of simple implementation, small benefit, small
downside, no discernable side effects. Write a PEP.
>
> John Roth

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!).
However we could still define a sort of abstract len() method  in a
'sequence' (or 'collection') base class, that has to be implemented in
derived classes (or will raise an exception otherwise).
This is in fact equivalent to implementing the existing __len__ method,
except that the names are different and the purpose of __len__ is mainly to
be called by the built-in function len(), but nothing forbids to call
obj.__len__() directly AFAIK. So ultimately the issue resides solely  in the
name, as an esthetical preference (I'm not personally addicted to
underscores). And since the __xxx__ notation is a Python convention, I'm
afraid there will be no other solution but using the obj.__len__() syntax if
one doesn't want to use len(obj).

Richard





More information about the Python-list mailing list