[Tutor] 'Right' way to implement mixins in Python?

Alan Gauld alan.gauld at btinternet.com
Thu May 29 00:30:53 CEST 2008


"chombee" <chombee at nerdshack.com> wrote

> I'm writing an event-driven GUI framework. I have several 
> independent
> units of functionality such as Draggable, Highlightable, etc. 
> Although
> these units of functionality are independent of each other, they do 
> all
> depend on a certain base implementation that they work with.

That's a bad thing in a mixin. Mixins should be as independant
as possible from any other classes. Unfortunately thats not
always possible so you should try to create an abstract
superclass/interface and use that in your mixins. You can then
subclass the mixin and replace the abstract class with the local
concrete manifestation. It means one extra level of inheritance 
because
you wind up with an abstract mixin plus the localised mixin.

> widget objects to be able to select different combinations of these
> capabilities at will. So mixins seemed like the way to go.

Sounds a fair approach. So long as you are aware of the extra
coomplexities asociated with maintaining very wide  multi-inheritance
heirarchies.

> It seemed to me that the most natural way to implement mixins in 
> Python
> is to use multiple inheritance with new-style classes. But I 
> certainly
> confused myself a lot trying to do it.

Mixins are normally done using MI. I''m interested in your 
experiences.
Did new style classes specifically add problems(I've only done mixins
in old style classes in Python, I've mainly used mixins in Lisp)

> The lessons I learned are that, when implementing mixins using 
> multiple
> inheritance:
>
> * Mixin classes should not derive from any base class (except 
> object)
> * But they may assume that the classes they will be mixed in with do
> derive from a certain base class, so they may assume the base class 
> is
> there.

Yes to both, regardless of language. As I said above you can make the
mixins slightly more generally reusable by creating abstact mixins
with explicit dependancy on an abstact interface. But better still is 
to
avoid dependencies as much as possible where mixins are concerned.
Instead build a protocol in the class framework outside the mixins
and let them coerce the dependencies to suit the mixin interfaces.

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld 




More information about the Tutor mailing list