# HG changeset patch # Parent ffb58df8f9eac67c675e15463cc4f2843d8d9d74 diff --git a/Lib/gzip.py b/Lib/gzip.py --- a/Lib/gzip.py +++ b/Lib/gzip.py @@ -144,8 +144,10 @@ if fileobj is None: fileobj = self.myfileobj = builtins.open(filename, mode or 'rb') if filename is None: - if hasattr(fileobj, 'name'): filename = fileobj.name - else: filename = '' + if hasattr(fileobj, 'name') and isinstance(fileobj.name, str): + filename = fileobj.name + else: + filename = '' if mode is None: if hasattr(fileobj, 'mode'): mode = fileobj.mode else: mode = 'rb' diff --git a/Lib/test/test_gzip.py b/Lib/test/test_gzip.py --- a/Lib/test/test_gzip.py +++ b/Lib/test/test_gzip.py @@ -346,6 +346,14 @@ with io.TextIOWrapper(f, encoding="ascii") as t: self.assertEqual(t.readlines(), lines) + def test_fileobj_from_fdopen(self): + # Issue #13781: Opening a GzipFile for writing fails when using a + # fileobj created with os.fdopen(). + fd = os.open(self.filename, os.O_WRONLY | os.O_CREAT) + with os.fdopen(fd, "wb") as f: + with gzip.GzipFile(fileobj=f, mode="w") as g: + pass + # Testing compress/decompress shortcut functions def test_compress(self):