[Python-3000] Builtin iterator type
George Sakkis
george.sakkis at gmail.com
Wed Nov 15 16:26:48 CET 2006
On 11/15/06, Nick Coghlan <ncoghlan at gmail.com> wrote:
> George Sakkis wrote:
> > Fredrik Lundh <fredrik at pythonware.com> wrote:
> >
> >> George Sakkis wrote:
> >>
> >>> 1) why having a "generic operation" len() that ends up looking for an
> >>> ugly special *method* called __len__() makes sense, while calling
> >>> directly a method len() doesn't
> >> for the very reason Mike explained: keeping implementation interfaces
> >> separate from public interfaces has allowed Python to avoid a certain
> >> category of design fragmentation that other languages suffer from.
> >
> > Fredrik, I am not arguing for the argument's sake, I just don't get
> > it: Python requires my class to define __len__, otherwise len() fails.
> > 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.
>
> The benefit of the magic method approach is that it leaves control of the
> public namespace of the class instance in the hands of the class developer.
> For a given class, it may make sense for the class API to expose its length
> under a different name like "size()" or "count()" (e.g. exposing an existing
> Java or C++ class to Python).
>
> However, regardless of what the class API itself looks like, it can be mapped
> behind the scenes into the standard Python idiom by doing "__len__ = size" (or
> whatever). If the Python idioms for these protocols were based on public API
> methods instead of the magic methods then it would greatly interfere with the
> developer's control over their own class interface.
On the one hand this makes sense, but on the other it goes back to
Bill's reply on that Python should formalize some widely used
interfaces (iterators, sequence, mappings, etc.), exactly for
extending the "one obvious way to do it" rule to interfaces and
prevent anyone who misses Java too much to use getIndex() for his
container instead of __getitem__.
George
More information about the Python-3000
mailing list