Is there a way to get the string representation of an object on disk without loading the object into memory? I thought of calling repr()
on the file object returned from calling open()
on the object but that returns the class/mode of the file object 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)))
I'd like to return the string representation of model2
(i.e. identifier created on <creation_date>
) without actually loading model2
into memory.
Do share another workaround you may have used to accomplish a similar purpose.
Thanks.
- MacOS
- Python 3.6.4