Terry Reedy: > Partly history and partly practicality. Len is implemented as .__len__ > ;-). The len function is one, __len__ methods are many. If you want to > pass an argument to a function, passing len is easier that passing > operator.attrgetter('__len__'). Passing '__len__' (or 'len') would be > easy, but using len is easier than using getattr(ob,'__len__').
A simple example may help: >>> seq = ["aaaa", "bb", "c", "ddd"] >>> seq2 = [[1,1,1,1], [2,2], [3], [4,4,4]] >>> sorted(seq, key=len) ['c', 'bb', 'ddd', 'aaaa'] >>> sorted(seq2, key=len) [[3], [2, 2], [4, 4, 4], [1, 1, 1, 1]] >>> sorted(seq, key=str.__len__) ['c', 'bb', 'ddd', 'aaaa'] >>> sorted(seq2, key=str.__len__) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: descriptor '__len__' requires a 'str' object but received a 'list' >>> from operator import attrgetter >>> sorted(seq, key=attrgetter("__len__")) ['aaaa', 'bb', 'c', 'ddd'] >>> sorted(seq2, key=attrgetter("__len__")) [[1, 1, 1, 1], [2, 2], [3], [4, 4, 4]] Bye, bearophile -- http://mail.python.org/mailman/listinfo/python-list