What are the elegant ways to do MixIns in Python?

Posted by Slava Vishnyakov on Stack Overflow See other posts from Stack Overflow or by Slava Vishnyakov
Published on 2010-05-03T10:23:21Z Indexed on 2010/05/03 10:28 UTC
Read the original article Hit count: 245

Filed under:
|

I need to find an elegant way to do 2 kinds of MixIns.

First:

class A(object):
    def method1(self):
        do_something()

Now, a MixInClass should make method1 do this: do_other() -> A.method1() -> do_smth_else() - i.e. basically "wrap" the older function. I'm pretty sure there must exist a good solution to this.

Second:

class B(object):
    def method1(self):
        do_something()
        do_more()

In this case, I want MixInClass2 to be able to inject itself between do_something() and do_more(), i.e.: do_something() -> MixIn.method1 -> do_more(). I understand that probably this would require modifying class B - that's ok, just looking for simplest ways to achieve this.

These are pretty trivial problems and I actually solved them, but my solution is tainted.

Fisrt one by using self._old_method1 = self.method1(); self.method1() = self._new_method1(); and writing _new_method1() that calls to _old_method1().

Problem: multiple MixIns will all rename to _old_method1 and it is inelegant.

Second MixIn one was solved by creating a dummy method call_mixin(self): pass and injecting it between calls and defining self.call_mixin(). Again inelegant and will break on multiple MixIns..

Any ideas?

© Stack Overflow or respective owner

Related posts about mixins

Related posts about python