Search code examples
pythonpython-3.xgettext

Ask gettext about current language and translation source in Python


I initialize gettext very simple like this in python3.

>>> import gettext
>>> gettext.install('i18n-test', 'locales')
>>> print(_('Hello World!'))
Hallo Welt!

Can I ask gettext which current language it uses (must not be the system default LANGUAGE!) and where it opens the .mo file from?

I can not see something like this in the API.


Solution

  • The find function of gettext module is what you need. More exactly, it is internally used by the install function, so it will return what install will use:

    gettext.install(domain, localedir=None, codeset=None, names=None)
    This installs the function _() in Python’s builtins namespace, based on domain, localedir, and codeset which are passed to the function translation()...

    then

    gettext.translation(domain, localedir=None, languages=None, class_=None, fallback=False, codeset=None)
    Return a Translations instance based on the domain, localedir, and languages, which are first passed to find() to get a list of the associated .mo file paths...

    So you should use:

    file = gettext.find('i18n-test', 'locales')
    

    It should return a file name like localedir/language/LC_MESSAGES/domain.mo, where language is the language selected by gettext.