Welcome, guest | Sign In | My Account | Store | Cart

This mixin makes it possible to pickle/unpickle objects with __slots__ defined.

Python, 11 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
class SlotPickleMixin(object):
    def __getstate__(self):
        return dict(
            (slot, getattr(self, slot))
            for slot in self.__slots__
            if hasattr(self, slot)
        )

    def __setstate__(self, state):
        for slot, value in state.items():
            setattr(self, slot, value)

In many programs, one or a few classes have a very large number of instances. Adding __slots__ to these classes can dramatically reduce the memory footprint and improve execution speed by eliminating the instance dictionary. Unfortunately, the resulting objects cannot be pickled. This mixin makes such classes pickleable again and even maintains compatibility with pickle files created before adding __slots__.