有没有办法在磁盘上获取对象的字符串表示而不将对象加载到内存中?我想在对象上调用repr()
返回的文件对象上调用open()
但返回文件对象per documentation的类/模式。
import os
import pickle
import tempfile
import datetime
from copy import copy
class Model:
def __init__(self, identifier):
self.identifier = identifier
self.creation_date = datetime.datetime.now()
def __repr__(self):
return '{0} created on {1}'.format(self.identifier, self.creation_date)
identifier = 'identifier'
model1 = Model(identifier)
model2 = copy(model1)
with tempfile.TemporaryDirectory() as directory:
with open(os.path.join(directory, identifier), 'wb') as f:
# persist model and delete from RAM
pickle.dump(model2, f)
del model2
with open(os.path.join(directory, identifier), 'rb') as f:
print('is model stale: {}'.format(repr(model1) != repr(f)))
print('Disk model: {}'.format(repr(f)))
print('RAM model: {}'.format(repr(model1)))
我想返回model2
(即identifier created on <creation_date>
)的字符串表示,而不实际将model2
加载到内存中。
请分享您可能已用于实现类似目的的另一种解决方法。
谢谢。
如果将对象序列化为JSON而不是二进制.pickle,则可以直接操作或过滤文本而不对其进行反序列化。有关一些不错的示例,请参阅How to make a class JSON serializable(特别是jsonpickle和.toJSON答案)。
多年前我写了一个懒惰的泡菜装载机here。你可以腌制一个((id, creation_date), model)
,然后只是反序列化第一个元组。