On 11/15/06, George Sakkis <[EMAIL PROTECTED]> 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 _______________________________________________ Python-3000 mailing list [email protected] http://mail.python.org/mailman/listinfo/python-3000 Unsubscribe: http://mail.python.org/mailman/options/python-3000/archive%40mail-archive.com
