from marshmallow import pre_dump class SkipEmptyDataMixin: """Schema mixin which allows to skip empty values in output dumped data.""" _EMPTY_VALUE = None def __init__(self, skip_empty=True, *args, **kwargs): self._skip_empty = skip_empty super().__init__(*args, **kwargs) @pre_dump def skip_empty_value(self, data, *args, **kwargs): if not self._skip_empty: return data return {key: value for key, value in data.items() if value != self._EMPTY_VALUE}