Pickle 链接对象
我想腌制一个对象和引用第一个对象的第二个对象。当我天真地腌制/取消腌制这两个对象时,引用就变成了副本。如何保留两个对象 foo
和 bar.foo_ref
之间的链接?
import pickle
class Foo(object):
pass
foo = Foo()
bar = Foo()
bar.foo_ref = foo
with open('tmp.pkl', 'wb') as f:
pickle.dump(foo, f)
pickle.dump(bar, f)
with open('tmp.pkl', 'rb') as f:
foo2 = pickle.load(f)
bar2 = pickle.load(f)
print id(foo) == id(bar.foo_ref) # True
print id(foo2) == id(bar2.foo_ref) # False
# want id(foo2) == id(bar2.foo_ref)
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 the link between the two objects foo
and bar.foo_ref
?
import pickle
class Foo(object):
pass
foo = Foo()
bar = Foo()
bar.foo_ref = foo
with open('tmp.pkl', 'wb') as f:
pickle.dump(foo, f)
pickle.dump(bar, f)
with open('tmp.pkl', 'rb') as f:
foo2 = pickle.load(f)
bar2 = pickle.load(f)
print id(foo) == id(bar.foo_ref) # True
print id(foo2) == id(bar2.foo_ref) # False
# want id(foo2) == id(bar2.foo_ref)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我之前的回答没有抓住你的重点。您的代码的问题是您没有使用
Pickler
和Unpickler
对象。这是一个包含多个转储调用的工作版本:My previous answer was missing your point. The problem with your code is that you're not using the
Pickler
andUnpickler
objects. Here's a working version with multiple dump calls:如果您将它们一起腌制,pickle 模块会跟踪引用并且仅腌制 foo 变量一次。你能像这样同时pickle
foo
和bar
吗?If you pickle them together, the pickle module keeps track of references and only pickles the
foo
variable once. Can you pickle bothfoo
andbar
together, like this?好吧,你可以这样做吗:
让 pickle 为你处理链接。
Well, can you do:
Let pickle handle the link for you.