[Python-Dev] functions vs methods (was Re: trunc())

Guido van Rossum guido at python.org
Mon Jan 28 23:00:33 CET 2008


On Jan 28, 2008 1:54 PM, "Martin v. Löwis" <martin at v.loewis.de> wrote:
> > This is why len() is not a method:
> >
> >     map(len, list_of_strings)
>
> That's a good use case - but is that the reason?
>
> I would think that the true historical reason is that when len()
> was introduced, there weren't methods in the language. And even
> when support for methods was added, many types supporting len wouldn't
> easily support methods (e.g. the string type).

Well, there were methods, but there were no "special" methods, and the
length of a sequence was intended to be implemented in C. The very
first version of the language (used internally at CWI for a while)
didn't even have classic classes -- the only way to add a new type was
to write a C extension.

> > What I don't know is to what extent this argument still holds in the
> > presence of listcomps and genexps:
> >
> >     [s.len() for s in list_of_strings]
> >
> > However, you still need ``len`` as a function to pass around as a
> > callback in other cases where you need a generic function because the
> > type of your data is not predetermined.
>
> You don't *need* it for that; you could also pass around
> lambda x:x.len()
>
> It's clear that you need functions for a functional programming style.
> However, I would question that typical Python code is inherently
> functional, and instead I believe that it could just as well or better
> be object-oriented - it's just that Python mandates functions at certain
> places.

I think that for certain things (e.g. len()) the functional notation
is just more readable than the method notation, because it provides
more information to the reader: len(x) guarantees to return an int.
x.len() has no such guarantee, it could be an unrelated len method on
an object that has nothing in common with sequences.

> > In any event, I consider dropping len() from builtins to be gratuitous
> > breakage, even in 3.0.
>
> I wouldn't want to propose removal of len(), no. However, I do think
> that adding more builtins (trunc in particular) is bad, especially
> when they make perfect methods.

No, using trunc(x) makes it clear that the argument and return value
are numbers. Using x.trunc() doesn't.

-- 
--Guido van Rossum (home page: http://www.python.org/~guido/)


More information about the Python-Dev mailing list