Python › Multiple Inheritance & MRO
How would you design a mixin to be safely combinable with any base class's __init__ signature using **kwargs?
AdvancedAnswer
A well-designed cooperative mixin accepts **kwargs in its __init__, extracts only the arguments it needs, and forwards the rest via super().__init__(**kwargs) -- so it doesn't need to know the concrete base class's exact signature and remains combinable in different hierarchies without argument mismatches.
class TimestampMixin:
def __init__(self, **kwargs):
self.created_at = kwargs.pop('created_at', None)
super().__init__(**kwargs) # forward remaining kwargs up the chain
class Model:
def __init__(self, name):
self.name = name
class User(TimestampMixin, Model):
pass
u = User(name='Alice', created_at='2024-01-01')Real-world example A reusable AuditMixin used across dozens of unrelated model classes accepts and forwards **kwargs so it works regardless of what specific constructor arguments each concrete model class requires.