Search code examples
pythondjangoposixinternationalizationlocale

Python: Access Posix' locale database without setlocale()


The setup is a Django based website on an Ubuntu server system with lots of useful information in /usr/share/i18n/locales.

The question: Can I access this pool of wisdom without using Python's locale.setlocale() afore?

The reason: The docs say, that it is

  1. very expensive to call setlocale(), and

  2. affects the whole application.

But in my case I have a, say, French site (Django handles setting the locale automatically), and I just want to display the name of January in the de_AT locale, or format a number like they do in Russia.


Solution

  • The magic library to achieve this is called Babel. Does what I want:

    Before

    import locale
    setlocale(LC_ALL, 'de')
    x = locale.format('%.2f', 123)
    setlocale(LC_ALL, '')
    

    After

    from babel.numbers import format_decimal
    x = format_decimal(123, format='#0.00', locale='de')
    

    ...and has a good Djang integration gratis.