len() and PEP 3000

bearophileHUGS at lycos.com bearophileHUGS at lycos.com
Sat Dec 9 14:09:10 EST 2006


Colin J. Williams:
> Why not replace the __len__ method with a len property for strings,
> lists, tuples, dictionaries etc.  __len__ is not very special and the
> property len eliminates the redundant parentheses.

You mean something like:
>>> "ab".len, [1, 2, 3].len
(2, 3)

In the given page Guido says:

>I didn't want these special operations to use ordinary method names, because then pre-existing classes, or classes written by users without an encyclopedic memory for all the special methods, would be liable to accidentally define operations they didn't mean to implement, with possibly disastrous consequences.<

I think it's easy enough to remember a len attribute, you use it all
the time.


>many functions are defined in terms of informal interfaces; for example, reversed works on anything that supports random access to items and has a known length. In practice, implementing things like max, sum, map, any, in and others, as built-in functions and operators is actually less code than implementing them as methods for each and every type that needs to support them.<

I agree, but I think some exceptions can be made for len attribute, and
for .copy(), .deepcopy(), and maybe for few other general methods.

Bye,
bearophile




More information about the Python-list mailing list