To me the most idiomatic way of calling tempfile.mkstemp() would be as:
with tempfile.mkstemp() as fd, filename:
pass
however, this obviously(?) raises AttributeError: __exit__
Calling os.close(fd) explicitly using try-finally is an easy way to solve this, but feels like violation of There should be one-- and preferably only one --obvious way to do it.
Is there a way to "fix" this in tempfile or is there a rationale why this has been implemented this way?
In the
tempfilemodule there are other, better suited ways to create a temporary file, such asTemporaryFile()and others.Especially, if you don't want the file to be deleted, use
NamedTemporaryFile(), giving it thedelete=Falseargument.