super and mix-in class: how exactly is the search order altered?

dieter dieter at handshake.de
Sat Jul 2 03:30:12 EDT 2016


"Veek. M" <vek.m1234 at gmail.com> writes:
> ...
> I'm reading this article: 
> https://rhettinger.wordpress.com/2011/05/26/super-considered-super/
>
> He's trying to explain the purpose of a 'mix-in class' and he says
>
>     We did not alter the source code for LoggingDict. Instead we built a 
> subclass whose only logic is to compose two existing classes and control 
> their search order.
>
> class LoggingOD(LoggingDict, collections.OrderedDict):
>     pass
>
> My question is this: in the above article context, is he talking about 
> the LoggingDict's search order that is being manipulated? Or he is 
> talking about manipulating the LoggingOD search order?

Likely, his language has been a bit sloppy.

Likely, his setup is as follows:

 * He has an existing class ("collections.OrderDict")
   which the base functionality he needs

 * He has an additional requirement (over that of "collections.OrderDict")
   -- logging modifications

 * He wants to implement his requirements (the base ones and the
   the additional one) without modifying the existing class in any way

 * His idea to implement the additional requirement is to define
   a derived class ("LoggingOD") and lets its modifying methods perform
   the logging and then call the corresponding methods of the
   base class.

 * He recognizes that this logging feature might be interesting
   not only for "collections.OrderDict" but also for other
   dictionary like base classes.
   Therefore, instead of implementing it directly in
   "LoggingOD", he implements it in the mixin class "LoggingDict".

 * Because "LoggingDict" was explicitely designed to be used
   as mixin class to enhance a base class, it knows that
   some methods ("__setitem__") of the base class need to be called
   in its own implementation of the corresponding method.

 * The integrator (the one combining "LoggingDict" with the base
   class) must ensure (by an appropriate inheritance order)
   that the combining class ("LoggingOD" in the example)
   calls the "LoggingDict"'s methods (which know about that of the
   base class) rather than the base class's methods (which do not
   know about the mixin class's methods).

   Therefore, he uses the inheritance order "LoggingDict" followed
   by the base class (and not vice versa).


Python clearly defines in what order attributes of an object
and of the construct "super(<base>,<obj>)" are looked up.

The essential concept is the so called "MRO" ("method resolution order")
(in fact, it is an attribute resolution order).

In simple cases (no common base classes), the MRO of
a definition "class C(B_1, ..., B_n): ..."
is defined by a left to right lookup: i.e. first in "C", then "B_1",
then "B_2", ...

The rules are a bit more complicated when the "B_i" have a (or more)
common base classes.




More information about the Python-list mailing list