blob: 0c61b0d3a0fce0890e7b2feb72c277e99b3af1a6 [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):
12 return _locale._getdefaultlocale()[1]
13else:
14 try:
15 _locale.CODESET
Antoine Pitrou4aa8f8e2013-10-12 15:00:44 +020016 except AttributeError:
Xavier de Gaye6c9dcda2016-12-17 09:19:11 +010017 if hasattr(sys, 'getandroidapilevel'):
18 # On Android langinfo.h and CODESET are missing, and UTF-8 is
19 # always used in mbstowcs() and wcstombs().
20 def getpreferredencoding(do_setlocale=True):
21 return 'UTF-8'
22 else:
23 def getpreferredencoding(do_setlocale=True):
24 # This path for legacy systems needs the more complex
25 # getdefaultlocale() function, import the full locale module.
26 import locale
27 return locale.getpreferredencoding(do_setlocale)
Antoine Pitroufd4722c2013-10-12 00:13:50 +020028 else:
29 def getpreferredencoding(do_setlocale=True):
30 assert not do_setlocale
31 result = _locale.nl_langinfo(_locale.CODESET)
32 if not result and sys.platform == 'darwin':
33 # nl_langinfo can return an empty string
34 # when the setting has an invalid value.
35 # Default to UTF-8 in that case because
36 # UTF-8 is the default charset on OSX and
37 # returning nothing will crash the
38 # interpreter.
39 result = 'UTF-8'
40 return result