Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

gh-104783: locale.getencoding() fallback uses FS encoding #105381

Merged
merged 1 commit into from
Jun 6, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
14 changes: 5 additions & 9 deletions Lib/locale.py
Original file line number Diff line number Diff line change
Expand Up @@ -616,16 +616,12 @@ def setlocale(category, locale=None):
try:
from _locale import getencoding
except ImportError:
# When _locale.getencoding() is missing, locale.getencoding() uses the
# Python filesystem encoding.
_encoding = sys.getfilesystemencoding()
def getencoding():
if hasattr(sys, 'getandroidapilevel'):
# On Android langinfo.h and CODESET are missing, and UTF-8 is
# always used in mbstowcs() and wcstombs().
return 'utf-8'
encoding = _getdefaultlocale()[1]
if encoding is None:
# LANG not set, default to UTF-8
encoding = 'utf-8'
return encoding
return _encoding
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

return sys.getfilesystemencoding() would be enough.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I created PR #105401 to change this.



try:
CODESET
Expand Down
11 changes: 11 additions & 0 deletions Lib/test/test_locale.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
from decimal import Decimal
from test.support import verbose, is_android, is_emscripten, is_wasi
from test.support.warnings_helper import check_warnings
from test.support.import_helper import import_fresh_module
from unittest import mock
import unittest
import locale
import sys
Expand Down Expand Up @@ -523,6 +525,15 @@ def test_getencoding(self):
# make sure it is valid
codecs.lookup(enc)

def test_getencoding_fallback(self):
# When _locale.getencoding() is missing, locale.getencoding() uses
# the Python filesystem
encoding = 'FALLBACK_ENCODING'
with mock.patch.object(sys, 'getfilesystemencoding',
return_value=encoding):
locale_fallback = import_fresh_module('locale', blocked=['_locale'])
self.assertEqual(locale_fallback.getencoding(), encoding)

def test_getpreferredencoding(self):
# Invoke getpreferredencoding to make sure it does not cause exceptions.
enc = locale.getpreferredencoding()
Expand Down