8000 bpo-18378: Recognize "UTF-8" as a valid name in locale._parse_localen… · python/cpython@e471a54 · GitHub
[go: up one dir, main page]

Skip to content

Commit e471a54

Browse files
bpo-18378: Recognize "UTF-8" as a valid name in locale._parse_localename (GH-14736)
(cherry picked from commit b0caf32) Co-authored-by: Ronald Oussoren <ronaldoussoren@mac.com>
1 parent bd127b1 commit e471a54

File tree

3 files changed

+41
-0
lines changed

3 files changed

+41
-0
lines changed

Lib/locale.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -492,6 +492,10 @@ def _parse_localename(localename):
492492
return tuple(code.split('.')[:2])
493493
elif code == 'C':
494494
return None, None
495+
elif code == 'UTF-8':
496+
# On macOS "LC_CTYPE=UTF-8" is a valid locale setting
497+
# for getting UTF-8 handling for text.
498+
return None, 'UTF-8'
495499
raise ValueError('unknown locale: %s' % localename)
496500

497501
def _build_localename(localetuple):

Lib/test/test_locale.py

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -493,6 +493,42 @@ def test_japanese(self):
493493

494494

495495
class TestMiscellaneous(unittest.TestCase):
496+
def test_defaults_UTF8(self):
497+
# Issue #18378: on (at least) macOS setting LC_CTYPE to "UTF-8" is
498+
# valid. Futhermore LC_CTYPE=UTF is used by the UTF-8 locale coercing
499+
# during interpreter startup (on macOS).
500+
import _locale
501+
import os
502+
503+
self.assertEqual(locale._parse_localename('UTF-8'), (None, 'UTF-8'))
504+
505+
if hasattr(_locale, '_getdefaultlocale'):
506+
orig_getlocale = _locale._getdefaultlocale
507+
del _locale._getdefaultlocale
508+
else:
509+
orig_getlocale = None
510+
511+
orig_env = {}
512+
try:
513+
for key in ('LC_ALL', 'LC_CTYPE', 'LANG', 'LANGUAGE'):
514+
if key in os.environ:
515+
orig_env[key] = os.environ[key]
516+
del os.environ[key]
517+
518+
os.environ['LC_CTYPE'] = 'UTF-8'
519+
520+
self.assertEqual(locale.getdefaultlocale(), (None, 'UTF-8'))
521+
522+
finally:
523+
for k in orig_env:
524+
os.environ[k] = orig_env[k]
525+
526+
if 'LC_CTYPE' not in orig_env:
527+
del os.environ['LC_CTYPE']
528+
529+
if orig_getlocale is not None:
530+
_locale._getdefaultlocale = orig_getlocale
531+
496532
def test_getpreferredencoding(self):
497533
# Invoke getpreferredencoding to make sure it does not cause exceptions.
498534
enc = locale.getpreferredencoding()
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Recognize "UTF-8" as a valid value for LC_CTYPE in locale._parse_localename.

0 commit comments

Comments
 (0)
0