访问字典 VS 访问书架
目前,我有一个字典,其中一个数字作为键,一个类作为值。我可以像这样访问该类的属性:
dictionary[str(instantiated_class_id_number)].attribute1
由于内存问题,我想使用 shelve
模块。我想知道这样做是否合理。搁置词典的作用与标准词典完全相同吗?如果不是,有什么不同?
Currently, I have a dictionary that has a number as the key and a Class as a value. I can access the attributes of that Class like so:
dictionary[str(instantiated_class_id_number)].attribute1
Due to memory issues, I want to use the shelve
module. I am wondering if doing so is plausible. Does a shelve dictionary act the exact same as a standard dictionary? If not, how does it differ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
Shelve 的行为与字典不完全相同,尤其是在修改字典中已有的对象时。
不同之处在于,当您将类添加到字典时,会存储引用,但搁置会保留对象的腌制(序列化)副本。如果您随后修改该对象,您将
修改内存中的副本,但不修改 pickled 版本。这可以(大部分)通过 shelf.sync() 和 shelf.close() 透明地处理,
写出条目。使所有这些工作确实需要跟踪所有尚未写回的检索对象,因此您必须调用 shelf.sync() 来清除缓存。
shelf.sync()
清除缓存的问题是您可以保留对该对象的引用并再次修改它。此代码不能按预期使用架子,但可以使用字典:
同步刷新缓存,因此修改后的“p”对象将从缓存中丢失,因此不会写回。
Shelve doesn't act extactly the same as dictionary, notably when modifying objects that are already in the dictionary.
The difference is that when you add a class to a dictionary a reference is stored, but shelve keeps a pickled (serialized) copy of the object. If you then modify the object you will
modify the in-memory copy, but not the pickled version. That can be handled (mostly) transparently by
shelf.sync()
andshelf.close()
,which write out entries. Making all that work does require tracking all retrieved objects which haven't been written back yet so you do have to call shelf.sync() to clear the cache.
The problem with
shelf.sync()
clearing the cache is that you can keep a reference to the object and modify it again.This code doesn't work as expected with a shelf, but will work with a dictionary:
Sync flushes the cache so the modified 'p' object is lost from the cache so it isn't written back.
是的,这是貌似合理的:
您需要经常调用
shelf.sync()
来清除缓存。编辑
小心,它不完全是一个
dict
。参见劳里恩的回答。哦,你只能有
str
键。Yes, it is plausible:
You need to call
shelf.sync()
every so often to clear the cache.EDIT
Take care, it's not exactly a
dict
. See e.g. Laurion's answer.Oh, and you can only have
str
keys.