Last active
August 4, 2019 12:39
-
-
Save guyarad/a95474daf0542b3344e30c534afe6450 to your computer and use it in GitHub Desktop.
Enable pickling on Python classes that uses __slots__
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class SlotsPicklingMixin(object): | |
# otherwise, subclasses will still have `__dict__` | |
__slots__ = () | |
def __init__(self): | |
assert hasattr(self, '__slots__') | |
def __getstate__(self): | |
all_slots = itertools.chain.from_iterable( | |
getattr(t, '__slots__', ()) for t in type(self).__mro__) | |
state = {attr: getattr(self, attr) for attr in all_slots | |
if hasattr(self, attr)} | |
return state | |
def __setstate__(self, state): | |
print "Setting", self.__class__.__name__ | |
for k, v in state.iteritems(): | |
setattr(self, k, v) | |
class SampleA(SlotsPicklingMixin): | |
__slots__ = ('my_a',) | |
def __init__(self, my_a): | |
super(SampleA, self).__init__() | |
self.my_a = my_a | |
class SampleB(SampleA): | |
__slots__ = ('my_b',) | |
def __init__(self, my_b, *args, **kwargs): | |
super(SampleB, self).__init__(*args, **kwargs) | |
self.my_b = my_b |
@huitredelombre you are right! not sure how it happened :) fixed!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
If you try to pickle a SampleB object, wont you loose the 'my_a' attribute? I thinks so