ActiveState Code

Recipe 496997: module mixins


Module mixins allow you to inherit from modules. This is how ruby achieves multiple inheritance, and I just wanted to show it's possible in python as well.

Python
1
2
def mixin(mod):
    return type("mixin(%s)" % (mod.__name__,), (object,), mod.__dict__)

Discussion

see http://sebulba.wikispaces.com/recipe+module+mixins for more info and examples.

Comments

  1. 1. At 3 a.m. on 30 aug 2006, Ori Peleg said:

    Cool. What about accessing 'self'?

  2. 2. At 3:04 a.m. on 30 aug 2006, Ori Peleg said:

    Okay, saw it in the wiki page.

  3. 3. At 2:58 p.m. on 30 aug 2006, bearophile - said:

    Maybe the mixin function can do the include too, so this:

    import testmixin

    class Bar(mixin(testmixin)):

    Can be replaced with this:

    class Bar(mixin("testmixin")):

Sign in to comment