[gettext] How to change language at run-time

Peter Otten __peter__ at web.de
Thu Jun 15 09:22:41 EDT 2017


pozz wrote:

> I know I can load multiple gettext.translation:
> 
>    it = gettext.translation('test', localedir="locale", languages=["it"])
>    es = gettext.translation('test', localedir="locale", languages=["es"])
> 
> and install one translation at run-time when I want at a later time
> (when the user selects a new language):
> 
>    it.install()
> or
>    es.install()
> 
> 
> However the problem is that strings already translated are not
> translated again when a new translation is installed.  So they stay at
> the language selected during start-up and don't change after a new
> install().
> 
> One solution is to restart the application, but I think there's a better
> and more elegant solution.

You need a way to defer the translation until the string is actually used.
The documentation has a few ideas

https://docs.python.org/dev/library/gettext.html#deferred-translations

and here's another one -- perform the translation in the __str__ method of
a custom class:

import gettext

class DeferredTranslation:
    def __init__(self, message):
        self.message = message
    def __str__(self):
        translate = _
        if translate is DeferredTranslation:
            return self.message
        return translate(self.message)
    @classmethod
    def install(class_):
        import builtins
        builtins._ = class_

DeferredTranslation.install()

message = _("Hello, world!")
print(message)

it = gettext.translation("test", localedir="locale", languages=["it"])
es = gettext.translation("test", localedir="locale", languages=["es"]) 

for language in [it, es]:
    language.install()
    print(message)





More information about the Python-list mailing list