bpo-28286: Deprecate opening GzipFile for writing implicitly. (GH-16417)
Always specify the mode argument for writing.
diff --git a/Lib/gzip.py b/Lib/gzip.py
index 2968f47..e60d8ad 100644
--- a/Lib/gzip.py
+++ b/Lib/gzip.py
@@ -177,6 +177,7 @@
filename = ''
else:
filename = os.fspath(filename)
+ origmode = mode
if mode is None:
mode = getattr(fileobj, 'mode', 'rb')
@@ -187,6 +188,13 @@
self.name = filename
elif mode.startswith(('w', 'a', 'x')):
+ if origmode is None:
+ import warnings
+ warnings.warn(
+ "GzipFile was opened for writing, but this will "
+ "change in future Python releases. "
+ "Specify the mode argument for opening it for writing.",
+ FutureWarning, 2)
self.mode = WRITE
self._init_write(filename)
self.compress = zlib.compressobj(compresslevel,
diff --git a/Lib/test/test_gzip.py b/Lib/test/test_gzip.py
index 48a36a3..57d851c 100644
--- a/Lib/test/test_gzip.py
+++ b/Lib/test/test_gzip.py
@@ -469,7 +469,9 @@
if "x" in mode:
support.unlink(self.filename)
with open(self.filename, mode) as f:
- with gzip.GzipFile(fileobj=f) as g:
+ with self.assertWarns(FutureWarning):
+ g = gzip.GzipFile(fileobj=f)
+ with g:
self.assertEqual(g.mode, gzip.WRITE)
def test_bytes_filename(self):