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

Veek. M vek.m1234 at gmail.com
Fri Jul 1 10:24:51 EDT 2016


I had posted this on StackOverflow - it's an excellent example of why SO 
sucks (don't want that happening here so please read carefully):

http://stackoverflow.com/questions/38145818/super-and-mix-in-class-how-exactly-is-the-search-order-altered?noredirect=1#comment63722336_38145818


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?

He says very clearly "not alter the source code for LoggingDict" so 
clearly he means that somehow, magically - the search order for 
super().__setitem__ in

class LoggingDict(dict):
    def __setitem__(self, key, value):
        logging.info('Settingto %r' % (key, value))
        super().__setitem__(key, value)

is being altered/influenced, but how? Could someone clarify what exactly 
is going on here? Far as I can make of it, the tree looks like this: 
http://i.stack.imgur.com/3foOB.jpg

Here's the code:
import collections

class LoggingDict(dict):
    def __setitem__(self, key, value):
        logging.info('Settingto %r' % (key, value))
        super().__setitem__(key, value)

class LoggingOD(LoggingDict, collections.OrderedDict):
    pass

x = LoggingDict()
print LoggingDict.__mro__
print LoggingOD.__mro__

as you can see.. 

selfstudy at deathstar:~$ python 29.mro.py 
(<class '__main__.LoggingDict'>, <type 'dict'>, <type 'object'>)
(<class '__main__.LoggingOD'>, <class '__main__.LoggingDict'>, <class 
'collections.OrderedDict'>, <type 'dict'>, <type 'object'>)
selfstudy at deathstar:~$ 




More information about the Python-list mailing list