Portable locale usage

Laszlo Nagy gandalf at shopzeus.com
Wed Sep 7 10:51:20 EDT 2011


> 1. Is there a way for writing portable Python code dealing with
> locales
>      (as sketched in the beginning)?
I usually do this at the top of my main program, before importing other 
modules:

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


This is absolutely portable. The above snippet works for different 
operating systems with different default encodings. You can always setup 
some environment variable before starting up the program if you really 
have to. And yes, that setting will be OS dependent, but your program 
will still be portable.

I have no access to Croatian Windows, but I bet that the above code 
would set the locale to the correct thing on both Linux and Windows.

It would be a bad idea to set the locale from anywhere else than your 
main program anyway. There are also some notes in the docs about this ( 
http://docs.python.org/library/locale.html#locale.setlocale ):

> setlocale() 
> <http://docs.python.org/library/locale.html#locale.setlocale> is not 
> thread-safe on most systems. Applications typically start with a call of
>
> import  locale
> locale.setlocale(locale.LC_ALL,  '')
>
> This sets the locale for all categories to the user's default setting 
> (typically specified in the *LANG* environment variable). If the 
> locale is not changed thereafter, using multithreading should not 
> cause problems.
>

Why are you trying to force a specific locale to your program anyway?

   L


-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20110907/cac8df7d/attachment.html>


More information about the Python-list mailing list