diff --git a/src/monty/io.py b/src/monty/io.py index f7f6fbcd..c20028ea 100644 --- a/src/monty/io.py +++ b/src/monty/io.py @@ -76,11 +76,12 @@ def zopen( stacklevel=2, ) - # Warn against default `encoding` in text mode if `PYTHONWARNDEFAULTENCODING` is set + # Warn against default `encoding` in text mode if + # `PYTHONWARNDEFAULTENCODING` is set (PEP 597) if ( - os.getenv("PYTHONWARNDEFAULTENCODING", False) - and "t" in mode + "t" in mode and kwargs.get("encoding", None) is None + and os.getenv("PYTHONWARNDEFAULTENCODING", False) ): warnings.warn( "We strongly encourage explicit `encoding`, " diff --git a/tests/test_io.py b/tests/test_io.py index 5f3f78c1..5617e847 100644 --- a/tests/test_io.py +++ b/tests/test_io.py @@ -426,16 +426,19 @@ def test_lzw_files(self): # Cannot decompress a real LZW file with ( pytest.raises(gzip.BadGzipFile, match="Not a gzipped file"), + pytest.warns(FutureWarning, match="compress LZW-compressed files"), zopen(f"{TEST_DIR}/real_lzw_file.txt.Z", "rt", encoding="utf-8") as f, ): f.read() @pytest.mark.parametrize("extension", [".txt", ".bz2", ".gz", ".xz", ".lzma"]) - def test_warnings(self, extension): + def test_warnings(self, extension, monkeypatch): filename = f"test_warning{extension}" content = "Test warning" with ScratchDir("."): + monkeypatch.setenv("PYTHONWARNDEFAULTENCODING", "1") + # Default `encoding` warning with ( pytest.warns(EncodingWarning, match="use UTF-8 by default"), @@ -443,6 +446,19 @@ def test_warnings(self, extension): ): f.write(content) + # No encoding warning if `PYTHONWARNDEFAULTENCODING` not set + monkeypatch.delenv("PYTHONWARNDEFAULTENCODING", raising=False) + + with warnings.catch_warnings(): + warnings.filterwarnings( + "error", + "We strongly encourage explicit `encoding`", + EncodingWarning, + ) + + with zopen(filename, "wt") as f: + f.write(content) + # Implicit text/binary `mode` warning warnings.filterwarnings( "ignore", category=EncodingWarning, message="argument not specified"