What is the best way to write a __getstate__ method that pickles almost all of an object\'s attributes, but excludes a few?
I have an object wi
__slots__ solution
If you are using slots, you can avoid repeating members to exclude with:
class C(object):
_pickle_slots = ['i']
__slots__ = _pickle_slots + ['j']
def __init__(self, i, j):
self.i = i
self.j = j
def __getstate__(self):
return (None, {k:getattr(self, k) for k in C._pickle_slots })
o = pickle.loads(pickle.dumps(C(1, 2), -1))
# i is there
assert o.i == 1
# j was excluded
try:
o.j
except:
pass
else:
raise
Tested in Python 2.7.6.