Created
March 25, 2021 12:23
-
-
Save kheaactua/26bf6a983395fd03f5a5794ae85c87ea to your computer and use it in GitHub Desktop.
Simple pickling example with a dispatchtable
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
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