language design question

Ant antroy at gmail.com
Mon Jul 10 07:54:39 EDT 2006


>    - why is len() not a member function of strings? Instead one says len(w).

Coming from a Java background, I also thought this a weird setup.
However IMHO there is another good reason to have len(obj) as we do in
Python: it helps to enforce some sort of uniformity across code.

If I want to find out the length of some object, then I know to try
len(obj). If it were merely convention that objects had a obj.len()
method, then some objects would be written to conform to this. As
things stand, it is common knowledge that len(obj) returns the length
of an object, and that the way to give you own objects the same
functionality is to give it a __len__() method.

The alternative of having a obj.len() function as a convention is less
compelling to use - if the users are reading your api, why not call the
method size() or magnitude() or just give it a length attribute, and
suddenly objects become less polymorphic as far as writing generic
functions is concerned.

Look at Java's Standard API for examples. An array has a length
attribute. A String has a length() method. Collections have a size()
method. Buffer objects have a capacity() method. One of Python's
strengths is that I can write a generic method:

 def printSize(obj): print "The size of this object is %d" % len(obj)

If we had a Java-like situation we'd have to test for different object
types before deciding on which method/attribute to call:

 def printSize(obj):
     len = None
     if type(obj) == str: len = obj.len()
     elif type(obj) == Buffer: len = obj.capacity()
     ...
     print "The size of this object is %d" % len

Just my view on the matter :-)




More information about the Python-list mailing list