Author ncoghlan
Recipients brian.curtin, dabrahams, eric.araujo, eric.smith, jaraco, ncoghlan, pitrou, r.david.murray, tim.golden
Date 2012-04-10.01:29:27
SpamBayes Score -1.0
Marked as misclassified Yes
Message-id <1334021369.06.0.0708332253761.issue14243@psf.upfronthosting.co.za>
In-reply-to
Content
I agree we need to add something here to better support the idiom where the "close" and "delete" operations on a NamedTemporaryFile are decoupled without the delete becoming a completely independent call to os.unlink().

I agree with RDM's proposal in issue 14514 that the replacement should be "delete on __exit__ but not on close". As with generator context managers, I'd also add in the "last ditch" cleanup behaviour in __del__.

Converting the issue to a feature request for 3.3 - there's no bug here, just an interaction with Windows that makes the existing behavioural options inconvenient.

After all, you can currently get deterministic cleanup (with a __del__ fallback) via:

  @contextmanager
  def named_temp(name):
    f = NamedTemporaryFile(name, delete=False)
    try:
        yield f
    finally:
        try:
            os.unlink(name)
        except OSError:
            pass

You need to be careful to make sure you keep the CM alive (or it will delete the file behind your back), but the idiom RDM described in the other issues handles that for you:

  with named_temp(fname) as f:
     data = "Data\n"
     f.write(data)
     f.close() # Windows compatibility
     with open(fname) as f:
         self.assertEqual(f.read(), data)

As far as the API goes, I'm inclined to make a CM with the above behavour available as a new class method on NamedTemporaryFile:

  with NamedTemporaryFile.delete_after(fname) as f:
      # As per the workaround
History
Date User Action Args
2012-04-10 01:29:29ncoghlansetrecipients: + ncoghlan, jaraco, pitrou, eric.smith, tim.golden, eric.araujo, r.david.murray, brian.curtin, dabrahams
2012-04-10 01:29:29ncoghlansetmessageid: <1334021369.06.0.0708332253761.issue14243@psf.upfronthosting.co.za>
2012-04-10 01:29:28ncoghlanlinkissue14243 messages
2012-04-10 01:29:28ncoghlancreate