Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Python 3, how to prevent direct creation of a mixin class?

In Python 3, I want to write a class that should only be used as a mixin. Is there any way to prevent direct creation of it?

Here's a simple concrete example:

class EqMixin:
    def __eq__(self, other):
        return type(self) == type(other) and self.__dict__ == other.__dict__
    def __hash__(self):
        return hash(tuple(sorted(self.__dict__.items())))

However, I want to allow

class Bar(EqMixin):
    ...

without allowing

foo = EqMixin()

How to do that?

Note: I can't just raise an exception in the __init__ of EqMixin, because the __init__ might be called by Bar's __init__.

Note: I don't want an abstract base class (or at least, I don't want to put any abstract methods into my mixin).

like image 753
qg_jinn Avatar asked Sep 13 '25 00:09

qg_jinn


1 Answers

Maybe this would do:

>>> class MustBeMixed(object):
...     def __init__(self):
...         if self.__class__ == MustBeMixed:
...             raise TypeError

>>> MustBeMixed()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 4, in __init__
TypeError

Usage:

>>> class Defuse(MustBeMixed):
...     def __init__(self):
...         super().__init__()
<__main__.Defuse object at 0x1099f8990>
like image 110
Peter Wood Avatar answered Sep 15 '25 14:09

Peter Wood