bpo-27671: Update FAQ about why len is function (GH-8432) · python/cpython@dc9039d

@@ -226,24 +226,25 @@ Python file objects support the iterator protocol, so you can now write simply::

226226

Why does Python use methods for some functionality (e.g. list.index()) but functions for other (e.g. len(list))?

227227

----------------------------------------------------------------------------------------------------------------

228228229-

The major reason is history. Functions were used for those operations that were

230-

generic for a group of types and which were intended to work even for objects

231-

that didn't have methods at all (e.g. tuples). It is also convenient to have a

232-

function that can readily be applied to an amorphous collection of objects when

233-

you use the functional features of Python (``map()``, ``zip()`` et al).

234-235-

In fact, implementing ``len()``, ``max()``, ``min()`` as a built-in function is

236-

actually less code than implementing them as methods for each type. One can

237-

quibble about individual cases but it's a part of Python, and it's too late to

238-

make such fundamental changes now. The functions have to remain to avoid massive

239-

code breakage.

240-241-

.. XXX talk about protocols?

242-243-

.. note::

244-245-

For string operations, Python has moved from external functions (the

246-

``string`` module) to methods. However, ``len()`` is still a function.

229+

As Guido said:

230+231+

(a) For some operations, prefix notation just reads better than

232+

postfix -- prefix (and infix!) operations have a long tradition in

233+

mathematics which likes notations where the visuals help the

234+

mathematician thinking about a problem. Compare the easy with which we

235+

rewrite a formula like x*(a+b) into x*a + x*b to the clumsiness of

236+

doing the same thing using a raw OO notation.

237+238+

(b) When I read code that says len(x) I *know* that it is asking for

239+

the length of something. This tells me two things: the result is an

240+

integer, and the argument is some kind of container. To the contrary,

241+

when I read x.len(), I have to already know that x is some kind of

242+

container implementing an interface or inheriting from a class that

243+

has a standard len(). Witness the confusion we occasionally have when

244+

a class that is not implementing a mapping has a get() or keys()

245+

method, or something that isn't a file has a write() method.

246+247+

-- https://mail.python.org/pipermail/python-3000/2006-November/004643.html

247248248249249250

Why is join() a string method instead of a list or tuple method?