Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Enable pickling on Python classes that uses __slots__
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
@crazyhouse33

This comment has been minimized.

Copy link

crazyhouse33 commented Jul 31, 2019

If you try to pickle a SampleB object, wont you loose the 'my_a' attribute? I thinks so

@guyarad

This comment has been minimized.

Copy link
Owner Author

guyarad commented Aug 4, 2019

@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
You can’t perform that action at this time.