I have a project where I need to create temp files.
I have a class that accepts a file path. and as needed it reads the data from the file. However, sometimes I have the data and I want to create the same object so I use tempfile. But I want the file to be deleted as the object garbage-collected.
This is my implementation which is wrong.
from pickle import load
import tempfile
class A:
def __init__(self, file_path):
self.file_path = file_path
@property
def data(self):
with open(self.file_path, "rb") as f2r:
return load(f2r)
@classmethod
def from_data(cls, data):
with tempfile.NamedTemporaryFile() as tmp:
tmp.write(data)
return cls(tmp.name)
The from_data method creates the temp file and returns an object but the file will be deleted as soon as from_data returns the object. But I want the file to live until the object itself is garbage-collected.
__del__so that it closes the tempfile when it is garbage collected? See also stackoverflow.com/questions/1481488/…