[Python-3000] Builtin iterator type

George Sakkis gsakkis at rutgers.edu
Wed Nov 15 17:08:54 CET 2006


Michael Urman <murman at gmail.com> wrote:

> 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

Thank you for your explanation; I'd rather read this in the FAQ rather than a
moot comparison with Java's inconsistent design.

As I wrote in my last reply to Nick though, I question Python's right to perform
such limited forms of design-by-contract-like assertions ("why not add
a precondition
on __add__(self,other) to enforce isinstance(other, self.__class__)
?") when it refuses to formalize interfaces for sequences, iterators
et al.

George


More information about the Python-3000 mailing list