diff --git a/Lib/mailbox.py b/Lib/mailbox.py --- a/Lib/mailbox.py +++ b/Lib/mailbox.py @@ -1919,9 +1919,10 @@ def close(self): """Close the file.""" - if hasattr(self._file, 'close'): - self._file.close() - del self._file + if hasattr(self, '_file'): + if hasattr(self._file, 'close'): + self._file.close() + del self._file def _read(self, size, read_method): """Read size bytes using read_method.""" @@ -1953,7 +1954,7 @@ @property def closed(self): - return self._file.closed + return not hasattr(self, '_file') or self._file.closed class _PartialFile(_ProxyFile): @@ -1991,7 +1992,8 @@ def close(self): # do *not* close the underlying file object for partial files, # since it's global to the mailbox object - del self._file + if hasattr(self, '_file'): + del self._file def _lock_file(f, dotlock=True): diff --git a/Lib/test/test_mailbox.py b/Lib/test/test_mailbox.py --- a/Lib/test/test_mailbox.py +++ b/Lib/test/test_mailbox.py @@ -297,6 +297,13 @@ self.assertEqual(data1.decode('ascii').replace(os.linesep, '\n'), _sample_message) + def test_get_file_can_be_closed_twice(self): + # Issue 11700 + key = self._box.add(_sample_message) + f = self._box.get_file(key) + f.close() + f.close() + def test_iterkeys(self): # Get keys using iterkeys() self._check_iteration(self._box.keys, do_keys=True, do_values=False) @@ -1835,7 +1842,10 @@ def _test_close(self, proxy): # Close a file proxy.close() - self.assertRaises(AttributeError, lambda: proxy.close()) + self.assertTrue(proxy.closed) + # Issue 11700 subsequent closes should be a no-op. + proxy.close() + self.assertTrue(proxy.closed) class TestProxyFile(TestProxyFileBase):