Bubble Foundry


Setting Locales in Python

by Peter.

You can use locale to localize things like Python’s datetime module. However, its defaults aren’t always the nicest. For instance, for Dutch is defaults to ISO while I prefer UTF-8:

>>> locale.setlocale(locale.LC_ALL, 'nl_NL')
'nl_NL'
>>> locale.getlocale()
('nl_NL', 'ISO8859-1')
>>> locale.setlocale(locale.LC_ALL, ('nl_NL', 'utf8@euro'))
'nl_NL.UTF-8'
>>> locale.getlocale()
('nl_NL', 'UTF8')

As you can see, for some reason ‘utf8@euro’ is the wonky encoding name that you have to use.

I tried a lot more logical names before I went directly to the source code for the answer:

 
>>> locale.setlocale(locale.LC_ALL, ('nl_NL', 'UTF8'))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/locale.py", line 494, in setlocale
    return _setlocale(category, locale)
locale.Error: unsupported locale setting
>>> locale.setlocale(locale.LC_ALL, ('nl_NL', 'utf_8'))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/locale.py", line 494, in setlocale
    return _setlocale(category, locale)
locale.Error: unsupported locale setting
>>> locale.setlocale(locale.LC_ALL, ('nl_NL', 'UTF-8'))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/locale.py", line 494, in setlocale
    return _setlocale(category, locale)
locale.Error: unsupported locale setting
>>> locale.setlocale(locale.LC_ALL, 'nl_nl.utf8@euro')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/locale.py", line 494, in setlocale
    return _setlocale(category, locale)
locale.Error: unsupported locale setting
>>> locale.setlocale(locale.LC_ALL, ('nl_NL', 'utf8'))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/locale.py", line 494, in setlocale
    return _setlocale(category, locale)
locale.Error: unsupported locale setting

Even worse, the locale returned for the UTF-8 version isn’t a valid locale tuple:

>>> locale.getlocale()
('nl_NL', 'UTF8')
>>> locale.setlocale(locale.LC_ALL, locale.getlocale())
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/locale.py", line 494, in setlocale
    return _setlocale(category, locale)
locale.Error: unsupported locale setting