qg_jinn
qg_jinn

Reputation: 101

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).

Upvotes: 4

Views: 382

Answers (2)

Open AI - Opting Out
Open AI - Opting Out

Reputation: 24133

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>

Upvotes: 2

ShadowRanger
ShadowRanger

Reputation: 155418

Sounds like you want to create an abstract base class. Perhaps use the abc module? As long as at least one abstract method on the class has not been overridden, the class cannot be instantiated.

Upvotes: 0

Related Questions