[Python-Dev] Proposed Mixins for Wide Interfaces

Guido van Rossum guido@python.org
Tue, 03 Sep 2002 13:50:31 -0400


> How about adding some mixins to simplify the
> implementation of some of the fatter interfaces?

Can you suggest implementations for these, to be absolutely clear what
you mean?

> class CompareMixin:
>     """
>     Given an __eq__ method in a subclass, adds a __ne__ method
>     Given __eq__ and __lt__, adds !=, <=, >, >=.
>     """

What if the "natural" thing to implement is __le__ instead of __lt__?
That's the case for sets.  Or __gt__ (less likely)?

> class MappingMixin:
>     """
>     Given __setitem__, __getitem__,  and keys,
>     implements values, items, update, get, setdefault, len,
>     iterkeys, iteritems, itervalues, has_key, and __contains__.
> 
>     If __delitem__ is also supplied, implements clear, pop,
>     and popitem.
> 
>     Takes advantage of __iter__ if supplied (recommended).

Does that mean that if you have __iter__, you don't use keys()?  In
that case it should implement keys() out of __iter__.  Maybe this
should be required.

>     Takes advantage of __contains__ or has_key if supplied
>     (recommended).
>     """

Let's standardize on __contains__, not has_key().  I guess you could
provide __contains__ as follows:

  def __contains__(self, key):
      try:
          self[key]
      except KeyError:
          return 0
      else:
          return 1

I don't mind if there are some recursions amongst the various
implementations; if you don't supply the minimum, the implementation
will raise "RuntimeError: maximum recursion depth exceeded".

> The idea is to make it easier to implement these interfaces.
> Also, if the interfaces get expanded, the clients automatically
> updated.  

A similar thing for sequences would be useful too, right?

--Guido van Rossum (home page: http://www.python.org/~guido/)