Replace deprecated getdefaultlocale

... because getdefautlocale was deprecated in Python 3.11 .

Also add context manager for locale override to make sure it is reset
to the original values even when something goes wrong during sort.

Change-Id: Ifeda733a8ea5b867615308318397fbe295313e2d
This commit is contained in:
Takashi Kajinami
2025-06-16 23:15:03 +09:00
parent 2861e46a2b
commit fef5459b94
2 changed files with 16 additions and 8 deletions

View File

@ -95,8 +95,13 @@ class Collector:
# Now sort specifically by C locale
def locale_aware_by_first_item(data):
return locale.strxfrm(data[0])
save_locale = locale.getdefaultlocale()
locale.setlocale(locale.LC_ALL, 'C')
sorted_content = sorted(final_content, key=locale_aware_by_first_item)
locale.setlocale(locale.LC_ALL, save_locale)
save_locale = locale.getlocale()
try:
locale.setlocale(locale.LC_ALL, 'C')
sorted_content = sorted(
final_content, key=locale_aware_by_first_item)
finally:
locale.setlocale(locale.LC_ALL, save_locale)
return sorted_content

View File

@ -114,11 +114,14 @@ class TestLocal(testtools.TestCase):
def wrong_sort_listdir(path):
ret = unpatched_listdir(path)
save_locale = locale.getdefaultlocale()
locale.setlocale(locale.LC_ALL, 'C')
bad_sort = sorted(ret, reverse=True)
locale.setlocale(locale.LC_ALL, save_locale)
save_locale = locale.getlocale()
try:
locale.setlocale(locale.LC_ALL, 'C')
bad_sort = sorted(ret, reverse=True)
finally:
locale.setlocale(locale.LC_ALL, save_locale)
return bad_sort
self.useFixture(fixtures.MonkeyPatch('os.listdir', wrong_sort_listdir))
local_md = self._call_collect()