Skip to content

Commit f7fabae

Browse files
authored
gh-93099: Fix _pyio to use locale module properly (gh-93136)
1 parent e739ff1 commit f7fabae

File tree

2 files changed

+15
-8
lines changed

2 files changed

+15
-8
lines changed

Lib/_pyio.py

+11-8
Original file line numberDiff line numberDiff line change
@@ -2022,13 +2022,7 @@ def __init__(self, buffer, encoding=None, errors=None, newline=None,
20222022
encoding = text_encoding(encoding)
20232023

20242024
if encoding == "locale":
2025-
try:
2026-
import locale
2027-
except ImportError:
2028-
# Importing locale may fail if Python is being built
2029-
encoding = "utf-8"
2030-
else:
2031-
encoding = locale.getencoding()
2025+
encoding = self._get_locale_encoding()
20322026

20332027
if not isinstance(encoding, str):
20342028
raise ValueError("invalid encoding: %r" % encoding)
@@ -2162,7 +2156,7 @@ def reconfigure(self, *,
21622156
if not isinstance(encoding, str):
21632157
raise TypeError("invalid encoding: %r" % encoding)
21642158
if encoding == "locale":
2165-
encoding = locale.getencoding()
2159+
encoding = self._get_locale_encoding()
21662160

21672161
if newline is Ellipsis:
21682162
newline = self._readnl
@@ -2267,6 +2261,15 @@ def _get_decoded_chars(self, n=None):
22672261
self._decoded_chars_used += len(chars)
22682262
return chars
22692263

2264+
def _get_locale_encoding(self):
2265+
try:
2266+
import locale
2267+
except ImportError:
2268+
# Importing locale may fail if Python is being built
2269+
return "utf-8"
2270+
else:
2271+
return locale.getencoding()
2272+
22702273
def _rewind_decoded_chars(self, n):
22712274
"""Rewind the _decoded_chars buffer."""
22722275
if self._decoded_chars_used < n:

Lib/test/test_io.py

+4
Original file line numberDiff line numberDiff line change
@@ -3570,6 +3570,10 @@ def seekable(self): return True
35703570
F.tell = lambda x: 0
35713571
t = self.TextIOWrapper(F(), encoding='utf-8')
35723572

3573+
def test_reconfigure_locale(self):
3574+
wrapper = io.TextIOWrapper(io.BytesIO(b"test"))
3575+
wrapper.reconfigure(encoding="locale")
3576+
35733577
def test_reconfigure_encoding_read(self):
35743578
# latin1 -> utf8
35753579
# (latin1 can decode utf-8 encoded string)

0 commit comments

Comments
 (0)