Always specify the mode argument for writing.
The *mode* argument can be any of ``'r'``, ``'rb'``, ``'a'``, ``'ab'``, ``'w'``,
``'wb'``, ``'x'``, or ``'xb'``, depending on whether the file will be read or
written. The default is the mode of *fileobj* if discernible; otherwise, the
- default is ``'rb'``.
+ default is ``'rb'``. In future Python releases the mode of *fileobj* will
+ not be used. It is better to always specify *mode* for writing.
Note that the file is always opened in binary mode. To open a compressed file
in text mode, use :func:`.open` (or wrap your :class:`GzipFile` with an
.. versionchanged:: 3.6
Accepts a :term:`path-like object`.
+ .. deprecated:: 3.9
+ Opening :class:`GzipFile` for writing without specifying the *mode*
+ argument is deprecated.
+
.. function:: compress(data, compresslevel=9, *, mtime=None)
the module will restrict its seeds to :const:`None`, :class:`int`,
:class:`float`, :class:`str`, :class:`bytes`, and :class:`bytearray`.
+* Opening the :class:`~gzip.GzipFile` file for writing without specifying
+ the *mode* argument is deprecated. In future Python versions it will always
+ be opened for reading by default. Specify the *mode* argument for opening
+ it for writing and silencing a warning.
+ (Contributed by Serhiy Storchaka in :issue:`28286`.)
+
* Deprecated the ``split()`` method of :class:`_tkinter.TkappType` in
favour of the ``splitlist()`` method which has more consistent and
predicable behavior.
filename = ''
else:
filename = os.fspath(filename)
+ origmode = mode
if mode is None:
mode = getattr(fileobj, 'mode', 'rb')
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,
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):
--- /dev/null
+Deprecate opening :class:`~gzip.GzipFile` for writing implicitly. Always
+specify the *mode* argument for writing.