Dynamic Python Mixins

I was pretty surprised to find out how straightforward it is to create mixin factories and templates in Python. I had a bunch of classes with attributes that needed special getter and setter methods with JSON serialization logic inside of them.

class Model:
    parameter = None

    def get_parameter(self):
        return json.loads(self.parameter)

    def set_parameter(self, value)
        return self.parameter = json.dumps(value)

With several such classes, each containing different amount of attributes that need JSON setters and getters I was aiming to keep it DRY with mixins, but since the number of attributes and their names differ between classes, I’d need a template mixin, a mixin factory that generates mixins dyanmically.

Continue reading