]> granicus.if.org Git - python/commitdiff
Issue #16486: Make aifc files work with 'with' as context managers.
authorSerhiy Storchaka <storchaka@gmail.com>
Sat, 29 Dec 2012 20:54:49 +0000 (22:54 +0200)
committerSerhiy Storchaka <storchaka@gmail.com>
Sat, 29 Dec 2012 20:54:49 +0000 (22:54 +0200)
Doc/library/aifc.rst
Lib/aifc.py
Lib/test/test_aifc.py
Misc/NEWS

index 999bad83ca8a59ce09c0969487659f7c8ff73eb9..f8a6ab7ef84bb3860d6296e0b8f182cb2de41478 100644 (file)
@@ -51,6 +51,10 @@ Module :mod:`aifc` defines the following function:
    used for writing, the file object should be seekable, unless you know ahead of
    time how many samples you are going to write in total and use
    :meth:`writeframesraw` and :meth:`setnframes`.
+   Objects returned by :func:`.open` also supports the :keyword:`with` statement.
+
+.. versionchanged:: 3.4
+   Support for the :keyword:`with` statement was added.
 
 Objects returned by :func:`.open` when a file is opened for reading have the
 following methods:
index a19b38f4aa455478caba5355276ef39bc693725f..67ea5dadc0bf1819d1b68ca508e148332ad4d2b6 100644 (file)
@@ -334,6 +334,12 @@ class Aifc_read:
         # else, assume it is an open file object already
         self.initfp(f)
 
+    def __enter__(self):
+        return self
+
+    def __exit__(self, *args):
+        self.close()
+
     #
     # User visible methods.
     #
@@ -553,6 +559,12 @@ class Aifc_write:
     def __del__(self):
         self.close()
 
+    def __enter__(self):
+        return self
+
+    def __exit__(self, *args):
+        self.close()
+
     #
     # User visible methods.
     #
index 9c0e7b96ce98ebb9b4c669b7e06cda44bdac4ba9..34589f24c181331956eeafe43c4530bd4430cc53 100644 (file)
@@ -43,6 +43,18 @@ class AIFCTest(unittest.TestCase):
             (2, 2, 48000, 14400, b'NONE', b'not compressed'),
             )
 
+    def test_context_manager(self):
+        with open(self.sndfilepath, 'rb') as testfile:
+            with aifc.open(testfile) as f:
+                pass
+            self.assertEqual(testfile.closed, True)
+        with open(TESTFN, 'wb') as testfile:
+            with self.assertRaises(aifc.Error):
+                with aifc.open(testfile, 'wb') as fout:
+                    pass
+            self.assertEqual(testfile.closed, True)
+            fout.close() # do nothing
+
     def test_read(self):
         f = self.f = aifc.open(self.sndfilepath)
         self.assertEqual(f.readframes(0), b'')
index 4f7f85622ec6e0ba142867b0ce22d20a2f304f6a..d4aa0dda7605f70e3f930ca818aa7635b43be3fb 100644 (file)
--- a/Misc/NEWS
+++ b/Misc/NEWS
@@ -200,6 +200,8 @@ Core and Builtins
 Library
 -------
 
+- Issue #16486: Make aifc files work with 'with' as context managers.
+
 - Issue #16485: Fix file descriptor not being closed if file header patching
   fails on closing of aifc file.