setlocale() in a module/extension library
"Martin v. Löwis"
martin at v.loewis.de
Tue Aug 23 23:39:35 CEST 2005
Damien Elmes wrote:
> My question is this: it would be nice if every user of my library
> didn't need to add the above two lines to their code. But on the other
> hand, I'm unsure of the implications of modifying the locale from
> within a module, and it doesn't seem very clean. Would calling
> setlocale() from a library be a bad thing? If so, any alternative
> recommendations would be greatly welcome.
Because the locale is a process-wide setting, libraries have typically
abstained from setting it. One of the most prominent problems is that
setlocale is not thread-safe, so you need to do it before any threads
are started. Another issue, of course, is that applications might break
if the locale changes "in the middle" of some computation, as a side
effect of using some library.
Therefore, the C tradition is to indeed require applications to the
the locale explicitly. Python follows that convention, and again exposes
just the API, with no automatic setting of the locale (actually, there
is some such setting during startup, but that is reverted before
__main__ starts executing).
IOW: feel free to invoke setlocale in your library. It will likely
work in many cases, but may break in some. So you should atleast
document that this is what your library does.
More information about the Python-list