Skip to content

Instantly share code, notes, and snippets.

@kheaactua
Created March 25, 2021 12:23
Show Gist options
  • Save kheaactua/26bf6a983395fd03f5a5794ae85c87ea to your computer and use it in GitHub Desktop.
Save kheaactua/26bf6a983395fd03f5a5794ae85c87ea to your computer and use it in GitHub Desktop.
Simple pickling example with a dispatchtable
import copyreg
import pickle
class Foo(object):
def __init__(self, bars):
self.bars = bars
def __str__(self):
return 'foo(%s)'%', '.join(['%s(%s)'%(type(b).__name__, b) for b in self.bars])
class Bar(object):
def __init__(self, v):
self.v = v
def __str__(self):
return f'{self.v}'
@classmethod
def pickle(cls, b):
return SBar, (f'b{b.v}',)
class SBar(object):
def __init__(self, s):
self.s = s
def __str__(self):
return self.s
foo = Foo([Bar(1), Bar(2)])
with open(r'/tmp/data.pkl', 'wb') as f:
p = pickle.Pickler(f)
p.dispatch_table = copyreg.dispatch_table.copy()
p.dispatch_table[Bar] = Bar.pickle
print("Pickling ", foo)
p.dump(foo)
with open(r'/tmp/data.pkl', 'rb') as f:
data = pickle.load(f)
print("Loaded: ", data)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment