From 0729b31a8b9ac35ef9b79fdc5aed22cccec9ba16 Mon Sep 17 00:00:00 2001 From: Inada Naoki Date: Sun, 1 May 2022 10:44:14 +0900 Subject: [PATCH] gh-91952: Make TextIOWrapper.reconfigure() supports "locale" encoding (GH-91982) --- Doc/library/io.rst | 3 +++ Lib/_pyio.py | 2 ++ .../2022-04-27-18-04-24.gh-issue-91952.9A4RXx.rst | 1 + Modules/_io/textio.c | 12 ++++++++++-- 4 files changed, 16 insertions(+), 2 deletions(-) create mode 100644 Misc/NEWS.d/next/Library/2022-04-27-18-04-24.gh-issue-91952.9A4RXx.rst diff --git a/Doc/library/io.rst b/Doc/library/io.rst index ecd8c8043351..d8e7b1621e2e 100644 --- a/Doc/library/io.rst +++ b/Doc/library/io.rst @@ -1038,6 +1038,9 @@ Text I/O .. versionadded:: 3.7 + .. versionchanged:: 3.11 + The method supports ``encoding="locale"`` option. + .. class:: StringIO(initial_value='', newline='\\n') diff --git a/Lib/_pyio.py b/Lib/_pyio.py index 380a7a736c64..0f647eed99d8 100644 --- a/Lib/_pyio.py +++ b/Lib/_pyio.py @@ -2161,6 +2161,8 @@ class TextIOWrapper(TextIOBase): else: if not isinstance(encoding, str): raise TypeError("invalid encoding: %r" % encoding) + if encoding == "locale": + encoding = locale.getencoding() if newline is Ellipsis: newline = self._readnl diff --git a/Misc/NEWS.d/next/Library/2022-04-27-18-04-24.gh-issue-91952.9A4RXx.rst b/Misc/NEWS.d/next/Library/2022-04-27-18-04-24.gh-issue-91952.9A4RXx.rst new file mode 100644 index 000000000000..a0b48d16fe86 --- /dev/null +++ b/Misc/NEWS.d/next/Library/2022-04-27-18-04-24.gh-issue-91952.9A4RXx.rst @@ -0,0 +1 @@ +Add ``encoding="locale"`` support to :meth:`TextIOWrapper.reconfigure`. diff --git a/Modules/_io/textio.c b/Modules/_io/textio.c index f1cd6d01da85..3cbaca3ef460 100644 --- a/Modules/_io/textio.c +++ b/Modules/_io/textio.c @@ -1248,8 +1248,16 @@ textiowrapper_change_encoding(textio *self, PyObject *encoding, errors = self->errors; } } - else if (errors == Py_None) { - errors = &_Py_ID(strict); + else { + if (_PyUnicode_EqualToASCIIString(encoding, "locale")) { + encoding = _Py_GetLocaleEncodingObject(); + if (encoding == NULL) { + return -1; + } + } + if (errors == Py_None) { + errors = &_Py_ID(strict); + } } const char *c_errors = PyUnicode_AsUTF8(errors); -- 2.47.3