[Python-3000] Builtin iterator type
Michael Urman
murman at gmail.com
Wed Nov 15 15:48:33 CET 2006
On 11/15/06, George Sakkis <george.sakkis at gmail.com> wrote:
> Why not require len() as a method instead and forget about __len__ ?
> Does len() (the function) do anything smarter behind the scenes than
> just passing the ball to __len__ ? That could justify its role but
> AFAIK it doesn't.
It most certainly does. It not only unifies the name, it makes an
interface guarantee you couldn't make on a custom method: return an
integer or raise an exception.
>>> class Len(object):
... def __len__(self): return 'length'
...
>>> obj = Len()
>>> obj.__len__()
'length'
>>> len(obj)
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: an integer is required
And, if you don't like this interface, it gives you a single point to
override it. (Shoving it into your builtins left as an exercise for
the interested.)
>>> def len(thing):
... try: return int(thing.__len__())
... except (ValueError, TypeError, AttributeError): return 0
...
>>> len(obj)
0
--
Michael Urman http://www.tortall.net/mu/blog
More information about the Python-3000
mailing list