Skip to content

Instantly share code, notes, and snippets.

@guyarad
Last active August 4, 2019 12:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save guyarad/a95474daf0542b3344e30c534afe6450 to your computer and use it in GitHub Desktop.
Save guyarad/a95474daf0542b3344e30c534afe6450 to your computer and use it in GitHub Desktop.
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
Copy link

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

@guyarad
Copy link
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