For example, i have that class structure:
class StreamMixin:
def publish(self, message):
# Stream logic here
pass
def get_message(self, message):
# stream logic here
pass
class SocketMixin:
def publish(self, message):
# Socket logic here
pass
def get_message(self, message):
# Socket logic here
pass
class MyPubSub(StreamMixin, SocketMixin):
...
And by default according to the MRO logic, MyPubSub instance will inherit methods from StreamMixin
. However, I need to specify the class from which to inherit, and I need to do this at the moment of instance creation.
In other words, when u create MyPubSub
instance u pass the use_stream
argument, and depending on this argument, instance will inherit methods from StreamMixin or from SocketMixin.
It might look something like this:
class MyPubSub(StreamMixin, SocketMixin):
def __new__(cls, *args, **kwargs):
use_stream = kwargs.get('use_stream')
if use_stream:
return StreamMixin.__new__(cls)
else:
return SocketMixin.__new__(cls)
Or directly changing mro:
class MyPubSub(StreamMixin, SocketMixin):
def __init__(self, use_stream):
if use_stream:
self.__mro__ = (MyPubSub, StreamMixin)
else:
self.__mro__ = (MyPubSub, SocketMixin)
Obviously it doesn’t work like that.
Maybe in some metaclass way?
Its even possible?
UPD:
Inheritance is not critical, the main goal to create the following behavior for MyPubSub
:
It has a set of methods described in Mixins (Stream or Socket), and depending on the parametr use_stream
it using the Stream methods or Socket methods, but solution must be “beautiful” - without checking a use_stream
flag in every method, or getattribute and etc.
Critical is “Working class” must be MyPubSub
P.S.
- Class structure can’t be changed to “OOP pretty style”
- Please do not suggest
getattribute
solution - Please do not suggest target changing methods like
self.publish = SocketMixin.publish
solution
I need kind of “beautiful” solution.