blob: 3273a3b42252ba1cd6a24622e81fe82407f42340 [file] [log] [blame]
Antoine Pitroufd4722c2013-10-12 00:13:50 +02001"""A minimal subset of the locale module used at interpreter startup
2(imported by the _io module), in order to reduce startup time.
3
4Don't import directly from third-party code; use the `locale` module instead!
5"""
6
7import sys
8import _locale
9
10if sys.platform.startswith("win"):
11 def getpreferredencoding(do_setlocale=True):
Victor Stinner91106cd2017-12-13 12:29:09 +010012 if sys.flags.utf8_mode:
13 return 'UTF-8'
Antoine Pitroufd4722c2013-10-12 00:13:50 +020014 return _locale._getdefaultlocale()[1]
15else:
16 try:
17 _locale.CODESET
Antoine Pitrou4aa8f8e2013-10-12 15:00:44 +020018 except AttributeError:
Xavier de Gaye6c9dcda2016-12-17 09:19:11 +010019 if hasattr(sys, 'getandroidapilevel'):
20 # On Android langinfo.h and CODESET are missing, and UTF-8 is
21 # always used in mbstowcs() and wcstombs().
22 def getpreferredencoding(do_setlocale=True):
23 return 'UTF-8'
24 else:
25 def getpreferredencoding(do_setlocale=True):
Victor Stinner91106cd2017-12-13 12:29:09 +010026 if sys.flags.utf8_mode:
27 return 'UTF-8'
Xavier de Gaye6c9dcda2016-12-17 09:19:11 +010028 # This path for legacy systems needs the more complex
29 # getdefaultlocale() function, import the full locale module.
30 import locale
31 return locale.getpreferredencoding(do_setlocale)
Antoine Pitroufd4722c2013-10-12 00:13:50 +020032 else:
33 def getpreferredencoding(do_setlocale=True):
34 assert not do_setlocale
Victor Stinner91106cd2017-12-13 12:29:09 +010035 if sys.flags.utf8_mode:
36 return 'UTF-8'
Antoine Pitroufd4722c2013-10-12 00:13:50 +020037 result = _locale.nl_langinfo(_locale.CODESET)
38 if not result and sys.platform == 'darwin':
39 # nl_langinfo can return an empty string
40 # when the setting has an invalid value.
41 # Default to UTF-8 in that case because
42 # UTF-8 is the default charset on OSX and
43 # returning nothing will crash the
44 # interpreter.
45 result = 'UTF-8'
46 return result