diff -r cb612c5f30cb Lib/aifc.py --- a/Lib/aifc.py Thu Nov 15 18:22:23 2012 +0000 +++ b/Lib/aifc.py Fri Nov 16 14:37:40 2012 +0200 @@ -553,6 +553,12 @@ def __del__(self): self.close() + def __enter__(self): + return self + + def __exit__(self, *args): + self.close() + # # User visible methods. # @@ -692,7 +698,9 @@ self._patchheader() def close(self): - if self._file: + if self._file is None: + return + try: self._ensure_header_written(0) if self._datawritten & 1: # quick pad to even size @@ -700,13 +708,15 @@ self._datawritten = self._datawritten + 1 self._writemarkers() if self._nframeswritten != self._nframes or \ - self._datalength != self._datawritten or \ - self._marklength: + self._datalength != self._datawritten or \ + self._marklength: self._patchheader() + finally: # Prevent ref cycles self._convert = None - self._file.close() + f = self._file self._file = None + f.close() # # Internal methods. diff -r cb612c5f30cb Lib/test/test_aifc.py --- a/Lib/test/test_aifc.py Thu Nov 15 18:22:23 2012 +0000 +++ b/Lib/test/test_aifc.py Fri Nov 16 14:37:40 2012 +0200 @@ -43,6 +43,13 @@ (2, 2, 48000, 14400, b'NONE', b'not compressed'), ) + def test_close(self): + fout = aifc.open(TESTFN, 'wb') + with self.assertRaises(aifc.Error): + fout.close() + self.assertIsNone(fout.getfp()) + fout.close() # do nothing + def test_read(self): f = self.f = aifc.open(self.sndfilepath) self.assertEqual(f.readframes(0), b'') @@ -286,11 +293,13 @@ def test_write_header_raises(self): fout = aifc.open(io.BytesIO(), 'wb') self.assertRaises(aifc.Error, fout.close) + fout = aifc.open(io.BytesIO(), 'wb') fout.setnchannels(1) self.assertRaises(aifc.Error, fout.close) + fout = aifc.open(io.BytesIO(), 'wb') + fout.setnchannels(1) fout.setsampwidth(1) self.assertRaises(aifc.Error, fout.close) - fout.initfp(None) def test_write_header_comptype_raises(self): for comptype in (b'ULAW', b'ulaw', b'ALAW', b'alaw', b'G722'):