[gettext] How to change language at run-time
Peter Otten
__peter__ at web.de
Thu Jun 15 12:40:38 EDT 2017
pozz wrote:
> Il 15/06/2017 15:22, Peter Otten ha scritto:
>> 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:
> > [...]
>
>
> It's a nice trick. However you will have a string that isn't a string,
> but a class. I think you can't use the class everywhere you can use a
> string. For example, len() can't be called.
len() could be implemented as
class DeferredTranslation:
...
def __len__(self):
return len(str(self))
and usually I would expect that you only need a small subset of the str
methods for localized text. However, when you switch languages between the
len() and str() calls you will certainly make a mess...
More information about the Python-list
mailing list