views:

1579

answers:

2

I'm attempting to sort a list of strings in a locale-aware manner. I've used the Babel library for other i18n-related tasks, but it doesn't support sorting. Python's locale module provides a strcoll function, but requires the locale of the process to be set to the one I want to work with. Kind of a pain, but I can live with it.

The problem is that I can't seem to actually set the locale. The documentation for the locale module gives this example:

import locale
locale.setlocale(locale.LC_ALL, 'de_DE')

When I run that, I get this:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Python26\Lib\locale.py", line 494, in setlocale
locale.Error: unsupported locale setting

What am I doing wrong?

+12  A: 

It seems you're using Windows. The locale strings are different there. Take a more precise look at the doc:

locale.setlocale(locale.LC_ALL, 'de_DE') # use German locale; name might vary with platform

On Windows, I think it would be something like:

locale.setlocale(locale.LC_ALL, 'deu_deu')

MSDN has a list of language strings and of country/region strings

Schnouki
A: 

You should not pass an explicit locale to setlocale, it is wrong. Let it find out from the environment. You have to pass it an empty string

import locale
locale.setlocale(locale.LC_ALL, '')
kaizer.se
I didn't mention this in the question because it wasn't directly related, but the code I was writing at the time was designed for use on a web server. In other words, the locale might change with each request, and is not necessarily ever the same as the environment's locale.
DNS
DNS: Have you read the docs for locale? It implies it might be dangerous to call setlocale "much", and it is not thread safe. So perhaps something else than setlocale is the solution. Gettext can load different catalogs and switch at runtime for example; but I don't know what you are using the locale for.
kaizer.se
sorry, read the question again, I see that you want to sort.
kaizer.se