pickle 的 `persistent_id` 的替代品?
我一直在使用Python的 pickle 用于实现基于文件的薄持久层的模块。这 持久层(较大库的一部分)严重依赖pickle的 persist_id 功能 将指定类的对象保存为单独的文件。
这种方法的唯一问题是 pickle 文件不是人类的 可编辑,而且我更愿意以以下格式保存对象 人类可以使用文本编辑器读取和编辑(例如,YAML 或 JSON)。
您是否知道任何使用人工可编辑格式的库和 提供与pickle 的persistent_id
类似的功能吗?或者, 您对在 YAML 或 YAML 之上实现它们有什么建议吗? 基于 JSON 的序列化库,无需重写大部分子集 泡菜?
I have been using Python's pickle
module for implementing a thin file-based persistence layer. The
persistence layer (part of a larger library) relies heavily on pickle's persistent_id feature
to save objects of specified classes as separate files.
The only issue with this approach is that pickle files are not human
editable, and I'd much rather have objects saved in a format that is
human readable and editable with a text editor (e.g., YAML or JSON).
Do you know of any library that uses a human-editable format and
offers features similar to pickle's persistent_id
? Alternatively,
do you have suggestions for implementing them on top of a YAML- or
JSON-based serialization library, without rewriting a large subset of
pickle?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我自己还没有尝试过,但我认为您应该能够使用 PyYAML 优雅地完成此操作他们称之为“代表者”和“解析器”。
编辑
在与发布者广泛交换意见后,这里是一种使用 PyYAML 实现所需行为的方法。
重要提示:如果
Persistable
实例具有另一个此类实例作为属性,或者以某种方式包含在其属性之一内,则所包含的Persistable
实例不会保存到另一个单独的文件中,而是会内联保存在与父Persistable
实例相同的文件中。据我所知,这种限制也存在于 OP 基于 pickle 的系统中,并且对于他/她的用例来说可能是可以接受的。我还没有找到一个不涉及黑客yaml.representer.BaseRepresenter
的优雅解决方案。从现在开始,当您想要将
Persistable
类的实例保存到单独的文件时,请使用my_yaml_dump
而不是yaml.dump
。但是不要在persistable_representer
和persistable_constructor
内部使用它!不需要特殊的加载函数,只需使用yaml.load
即可。唷,这需要一些工作......我希望这会有所帮助!
I haven't tried this yet myself, but I think you should be able to do this elegantly with PyYAML using what they call "representers" and "resolvers".
EDIT
After an extensive exchange of comments with the poster, here is a method to achieve the required behavior with PyYAML.
Important Note: If a
Persistable
instance has another such instance as an attribute, or contained somehow inside one of its attributes, then the containedPersistable
instance will not be saved to yet another separate file, rather it will be saved inline in the same file as the parentPersistable
instance. To the best of my understanding, this limitation also existed in the OP's pickle-based system, and may be acceptable for his/her use cases. I haven't found an elegant solution for this which doesn't involve hackingyaml.representer.BaseRepresenter
.From now on use
my_yaml_dump
instead ofyaml.dump
when you want to save instances of thePersistable
class to separate files. But don't use it insidepersistable_representer
andpersistable_constructor
! No special loading function is necessary, just useyaml.load
.Phew, that took some work... I hope this helps!