Skip to content

Commit ff3c973

Browse files
authored
bpo-43510: PEP 597: Accept encoding="locale" in binary mode (GH-25103)
It make `encoding="locale"` usable everywhere `encoding=None` is allowed.
1 parent 1b4a9c7 commit ff3c973

File tree

3 files changed

+14
-2
lines changed

3 files changed

+14
-2
lines changed

‎Lib/_pyio.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -221,7 +221,7 @@ def open(file, mode="r", buffering=-1, encoding=None, errors=None,
221221
raise ValueError("can't have read/write/append mode at once")
222222
if not (creating or reading or writing or appending):
223223
raise ValueError("must have exactly one of read/write/append mode")
224-
if binary and encoding is not None:
224+
if binary and encoding is not None and encoding != "locale":
225225
raise ValueError("binary mode doesn't take an encoding argument")
226226
if binary and errors is not None:
227227
raise ValueError("binary mode doesn't take an errors argument")

‎Lib/test/test_io.py‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -531,6 +531,17 @@ class UnseekableWriter(self.MockUnseekableIO):
531531
self.assertRaises(OSError, obj.truncate)
532532
self.assertRaises(OSError, obj.truncate, 0)
533533

534+
def test_open_binmode_encoding(self):
535+
"""open() raises ValueError when encoding is specified in bin mode"""
536+
self.assertRaises(ValueError, self.open, os_helper.TESTFN,
537+
"wb", encoding="utf-8")
538+
539+
# encoding=None and encoding="locale" is allowed.
540+
with self.open(os_helper.TESTFN, "wb", encoding=None):
541+
pass
542+
with self.open(os_helper.TESTFN, "wb", encoding="locale"):
543+
pass
544+
534545
def test_open_handles_NUL_chars(self):
535546
fn_with_NUL = 'foo\0bar'
536547
self.assertRaises(ValueError, self.open, fn_with_NUL, 'w')

‎Modules/_io/_iomodule.c‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -346,7 +346,8 @@ _io_open_impl(PyObject *module, PyObject *file, const char *mode,
346346
goto error;
347347
}
348348

349-
if (binary && encoding != NULL) {
349+
if (binary && encoding != NULL
350+
&& strcmp(encoding, "locale") != 0) {
350351
PyErr_SetString(PyExc_ValueError,
351352
"binary mode doesn't take an encoding argument");
352353
goto error;

0 commit comments

Comments
 (0)