Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit b1a91d2

Browse files
authored
gh-104783: locale.getencoding() fallback uses FS encoding (#105381)
The locale.getencoding() function now uses sys.getfilesystemencoding() if _locale.getencoding() is missing, instead of calling locale.getdefaultlocale().
1 parent 3a975b5 commit b1a91d2

File tree

2 files changed

+16
-9
lines changed

2 files changed

+16
-9
lines changed

Lib/locale.py

Lines changed: 5 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -616,16 +616,12 @@ def setlocale(category, locale=None):
616616
try:
617617
from _locale import getencoding
618618
except ImportError:
619+
# When _locale.getencoding() is missing, locale.getencoding() uses the
620+
# Python filesystem encoding.
621+
_encoding = sys.getfilesystemencoding()
619622
def getencoding():
620-
if hasattr(sys, 'getandroidapilevel'):
621-
# On Android langinfo.h and CODESET are missing, and UTF-8 is
622-
# always used in mbstowcs() and wcstombs().
623-
return 'utf-8'
624-
encoding = _getdefaultlocale()[1]
625-
if encoding is None:
626-
# LANG not set, default to UTF-8
627-
encoding = 'utf-8'
628-
return encoding
623+
return _encoding
624+
629625

630626
try:
631627
CODESET

Lib/test/test_locale.py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
from decimal import Decimal
22
from test.support import verbose, is_android, is_emscripten, is_wasi
33
from test.support.warnings_helper import check_warnings
4+
from test.support.import_helper import import_fresh_module
5+
from unittest import mock
46
import unittest
57
import locale
68
import sys
@@ -523,6 +525,15 @@ def test_getencoding(self):
523525
# make sure it is valid
524526
codecs.lookup(enc)
525527

528+
def test_getencoding_fallback(self):
529+
# When _locale.getencoding() is missing, locale.getencoding() uses
530+
# the Python filesystem
531+
encoding = 'FALLBACK_ENCODING'
532+
with mock.patch.object(sys, 'getfilesystemencoding',
533+
return_value=encoding):
534+
locale_fallback = import_fresh_module('locale', blocked=['_locale'])
535+
self.assertEqual(locale_fallback.getencoding(), encoding)
536+
526537
def test_getpreferredencoding(self):
527538
# Invoke getpreferredencoding to make sure it does not cause exceptions.
528539
enc = locale.getpreferredencoding()

0 commit comments

Comments
 (0)