A Python 3000 Question
duncan.booth at invalid.invalid
Wed Oct 31 14:49:50 CET 2007
Neil Cerutti <horpner at yahoo.com> wrote:
> But if I'm wrong about the performance benefits then I guess I'm
> still in the dark about why len is a builtin. The only compelling
> thing in the linked explation was the signatures of the guys who
> wrote the artible. (Guido does admit he would, "hate to lose it
> as a builtin," but doesn't explain why that should be a bad
With most of the builtin functions there is an advantage since they wrap
a bit of extra logic round the implementation: e.g. getattr hooks to
__getattr__ or __getattribute__.
With len that doesn't really apply, as the only extra logic seems fairly
pointless: sequences and mappings implement length differently so you
could have a type which acts as both and returns different lengths for
each. Also the result returned from __len__ is cast from a Python object
to a C value and back again so you can't return a length which is too
large to convert.
The main benefit that I can think of is that it avoids namespace
pollution: most Python special methods (the ones you aren't supposed to
call directly) have the double-underscores flagging them as separate
from user methods. This is a good thing: you can create a class which
acts like a builtin sequence, but which has any attributes you fancy:
the obvious example being the classic "it's a tuple but all the elements
are also accessible as attributes" returned from time.localtime(),
happen when your attribute names clash with internal attribute names.
So that's my conclusion: it is a builtin function rather than a method
in order to avoid polluting the user attribute space of user-defined
Obviously it isn't an absolute thing: lists and dictionaries do have
other methods in the user namespace, so the decision to keep len out of
that namespace is partly a judgement call, and partly historical (I
think tuples didn't used to have any methods at all).
More information about the Python-list