What is the best way to internationalize a Python app with multiple i18n domains?
I'm internationalizing a Python application, with two goals in mind:
The application loads classes from multiple packages, each with its own i18n domain. So modules in package A are using domain A, modules in package B are using domain B, etc.
The locale can be changed while the application is running.
Python's gettext
module makes internationalizing a single-domain single-language application very easy; you just set the locale, then call gettext.install()
, which finds the right Translation
and installs its ugettext
method in the global namespace as _
. But obviously a global value only works for a single domain, and since it loads a single Translation
, it only works for that locale.
I could instead load the Translation
at the top of each module, and bind its ugettext method as _
. Then each module would be using the _
for its own domain. But this still breaks when the locale is changed, because _
is for the wrong locale.
So I guess I could load the correct ugettext
at the top of every function, but that seems awfully cumbersome. An alternative would be to still do it per-module, but instead of binding ugettext
, I would substitute my own function, which would check the current locale, get its Translation
, and forward the string to it. Does anyone have a cleaner solution?
Asked by: Rebecca732 | Posted: 06-12-2021
Answer 1
how about you bind _ to a function roughly like this (for each module):
def _(message):
return my_gettext(__name__, message)
This allows you to use gettext while at the same time perform any lookup on a per-module-per-call-base that allows you to switch locale as well.
Answered by: Fenton981 | Posted: 07-01-2022Similar questions
python - Internationalize units system
I am gonna internationalize an application written in Python with GTK+. There is a need to internationalize units system, mostly volumes from "fl. oz" to "litres", ounces to grams etc.. I am looking for a tool, library that can be helpful. Python has gettext module by default, but I'm not sure if it will be helpful.
In best case, I would like to have a tool, that reads unit, automaticaly gets locale and returns loc...
python - django rest framework how to internationalize fields
I have followed the Django documentation for setting up internationalization.
I require to return a translation of various choices fields depending on the language requested.
For example I have the following choices fields;
CHOICE_TYPES = (('short', _('Short Term')),('long', _('Long Term')), ('mixed', _('Mixed')),)
I have setup my Locale and .po files as per the documenta...
Still can't find your answer? Check out these communities...
PySlackers | Full Stack Python | NHS Python | Pythonist Cafe | Hacker Earth | Discord Python