Pickle linked objects

后端 未结 3 975
情歌与酒
情歌与酒 2021-01-02 01:51

I want to pickle an object and a second object that references the first. When I naively pickle/unpickle the two objects, the reference becomes a copy. How do I preserve t

3条回答
  •  囚心锁ツ
    2021-01-02 02:15

    If you pickle them together, the pickle module keeps track of references and only pickles the foo variable once. Can you pickle both foo and bar together, like this?

    import pickle
    
    class Foo(object):
        pass
    
    foo = Foo()
    bar = Foo()
    bar.foo_ref = foo
    
    with open('tmp.pkl', 'wb') as f:
        pickle.dump((foo, bar), f)
    with open('tmp.pkl', 'rb') as f:
        foo2, bar2 = pickle.load(f)
    
    print id(foo) == id(bar.foo_ref) # True
    print id(foo2) == id(bar2.foo_ref) # True
    

提交回复
热议问题