1

I have a class, Mixed which needs to mix in the class SomeMixin. But Mixed does not need a base class.

This syntax would seem to make SomeMixin a base class rather than a mixin:

class Mixed(SomeMixin):

But the more intuitive syntax throws an error:

class SomeMixin:
     pass
 
class Mixed(object, SomeMixin):
     def __init__(self):
         pass
Traceback (most recent call last):
  File "<input>", line 1, in <module>
TypeError: Cannot create a consistent method resolution
order (MRO) for bases object, SomeMixin

How can I use a mixin in a class which does not require a base class?

klutt
  • 30,332
  • 17
  • 55
  • 95
crenshaw-dev
  • 7,504
  • 3
  • 45
  • 81
  • 1
    I think it should be `class Mixed(SomeMixin, object)` but feels like it's the same thing as just `class Mized(SomeMixin)`. What specifically do you mean by 'base' class and why is that a problem to have it? How is it different from a mixin for you? – GProst Oct 07 '20 at 13:32
  • 1
    Simply `class Mixed(SomeMixin)` will work. There is no difference between a mixin and a base class in python, other than the mixin being usually incomplete and not meant to work on its own. Also see: https://stackoverflow.com/questions/533631/what-is-a-mixin-and-why-are-they-useful – Wups Oct 07 '20 at 13:38
  • @GProst as far as I can tell, the only difference is the necessity of calling `super().__init__()`... still trying to figure out why that's not necessary for a mixin. Per @Wups, that might be the only difference, and I just shouldn't worry about it. – crenshaw-dev Oct 07 '20 at 13:40
  • @klutt that exact code produces the error for me in Python 3.8.2. – crenshaw-dev Oct 07 '20 at 13:40
  • @MichaelCrenshaw Sorry. It worked in 2.7 – klutt Oct 07 '20 at 13:42
  • @klutt no worries, I should have specified. Also kinda interesting that there's a difference. – crenshaw-dev Oct 07 '20 at 13:42
  • You don't need to call `super().__init__()` if the super class doesn't have an `__init__`, which is not seldom the case for mixins. – deceze Oct 07 '20 at 13:45

0 Answers0