r/programming • • Aug 30 '08

Tour De Babel -- Rant about programming languages (at Amazon)

http://steve.yegge.googlepages.com/tour-de-babel
10 Upvotes

122 comments sorted by

View all comments

Show parent comment

2

u/twotime Aug 31 '08

I agree with you on map/reduce (they utilize a low-level property of objects (iterability)).

But len() is a somewhat different beast: is not it defined as

def len(x): return x.len()

and to support len() a class must define method len()?

So why not require every object to define method len() and get rid of len() builtin?

Is there any benefit to len(x) over x.len()?

(at the very least: x.len() removes an extra level of indirection)

E.g python does not have read() builtin (which just calls read method), instead you simply define a read()method when you need it

1

u/[deleted] Aug 31 '08

Conceptually, it is just calling __len__(), although for sequence-like internal objects there is a different mechanism tried if no explicit length interface is defined. In the case of len(), I would probably prefer that it be an instance method.

Part of the reason for that is that I was wrong about len() taking iterables. If the object doesn't define __len__() and isn't a "sized" type (an internal implementation detail concerning tuples and strings), the operation fails. It doesn't "follow" iterators to count how many things they yield. So unlike map, reduce, filter, et al., it's not a generic high-level utility (even if a simple one) so much as a stub. I imagine that it is around primarily for historical reasons, and now that a __len__() interface exists, it is very hard to get rid of.

One thing I will say in its favor is that it makes sequences easier to work with in C modules since __len__() is much more clearly defined in that context than "some random instance method with a pseudo-standardized name", and the internal version of len(), called PyObject_Size(), returns a C integer instead of a PyObject*. Even if you call len() in Python against a pure-python __len__(), a TypeError is raised if the function doesn't return an integer.