Index: Lib/tempfile.py =================================================================== --- Lib/tempfile.py (revision 60593) +++ Lib/tempfile.py (working copy) @@ -413,6 +413,16 @@ def __del__(self): self.close() + def __enter__(self): + if self.close_called: + raise ValueError("Temporary file '%s' is closed" % self.name) + return self + + def __exit__(self, exit, value, exc): + self.close() + + + def NamedTemporaryFile(mode='w+b', bufsize=-1, suffix="", prefix=template, dir=None, delete=True): """Create and return a temporary file. Index: Lib/test/test_tempfile.py =================================================================== --- Lib/test/test_tempfile.py (revision 60593) +++ Lib/test/test_tempfile.py (working copy) @@ -1,5 +1,5 @@ # tempfile.py unit tests. - +from __future__ import with_statement import tempfile import os import sys @@ -629,6 +629,17 @@ except: self.failOnException("close") + def test_context_manager(self): + # A NamedTemporaryFile can be used as a context manager + + with tempfile.NamedTemporaryFile() as f: + self.failUnless(os.path.exists(f.name)) + self.failIf(os.path.exists(f.name)) + def use_closed(): + with f: + pass + self.failUnlessRaises(ValueError, use_closed) + # How to test the mode and bufsize parameters? test_classes.append(test_NamedTemporaryFile)