buhtz
buhtz

Reputation: 12172

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.

Upvotes: 2

Views: 2219

Answers (2)

Serge Ballesta
Serge Ballesta

Reputation: 148965

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.

Upvotes: 2

Nordle
Nordle

Reputation: 2981

From the docs;

If you use this API you will affect the translation of your entire application globally. Often this is what you want if your application is monolingual, with the choice of language dependent on the locale of your user. If you are localizing a Python module, or if your application needs to switch languages on the fly, you probably want to use the class-based API instead.

So you would probably be better using the Class-based API to do this. Good luck!

Upvotes: 2

Related Questions