[Python-3000] Builtin iterator type

George Sakkis george.sakkis at gmail.com
Wed Nov 15 19:36:33 CET 2006


On 11/15/06, Bill Janssen <janssen at parc.com> 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.
> >
> > George
>
> So you're suggesting something like:
>
>    class Lengthable:
>
>       def len(self):
>          raise NotImplemented
>
> (presumably defined in some "standard" or "builtins" module) be a
> mix-in to every type which it currently makes sense to call "len()"
> on?

No, having an interface for every single method is obviously an
overkill. Unless I am convinced otherwise, I am thinking something
like:

class Container(object):
   def len(self): raise NotImplementedError
   def __iter__(self): raise NotImplementedError
   # other generic container methods

class Sequence(Container):
   def __getitem__(self, index_or_slice): raise NotImplementedError
   # more methods

class Mapping(Container):
   def __getitem__(self, key): raise NotImplementedError
   # more methods

class list(Sequence):
    # blah blah

class tuple(Sequence):
    # blah blah

class MyFancySequence(Sequence):
    # blah blah


Note that this does _not_ disallow duck typing; anyone is perfectly
free to define a method len() in a class that does not extend any of
the above so that a client can call x.len() successfully. If not, a
normal AttributeError will be raised, instead of the TypeError you get
today.

George


More information about the Python-3000 mailing list