I am trying to achieve something similar to
from tempfile import TemporaryFile
def open_head(file_path):
with open(file_path, 'r') as f,
TemporaryFile() as tf:
for i in range(0,10):
tf.write(f.read_line())
return tf
such that the caller gets ownership of the temporary file.
In particular, I don't want the with statement to close the TemporaryFile. But if anything goes wrong before the return, I still want the TemporaryFile be closed by the with statement.
Ideally, I would then want to write the caller as
with open_head(file_path):
# more code here
Is this possible somehow? E.g. by writing return do_not_close(tf) or some other utility functionality?
Or am I approaching this completely wrong and there is a more Pythonic way to return a TemporaryFiles or other resources, between functions while guaranteeing exception safety?