> On Aug 17, 2023, at 10:02 AM, c.buhtz--- via Python-list > <python-list@python.org> wrote: > > X-Post: https://stackoverflow.com/q/76913082/4865723 > > I want to display one string in its original source (untranslated) version > and in its translated version site by site without duplicating the string in > the python source code? > It wouldn't be a big deal if it is only one word. > > print('The translated string "{}" is originally "{}".'.format(_('Hello'), > 'Hello')) > > But in my situation it is a multi line string containing multiple paragraphs. > It is a full text. I don't want to duplicate that string. > > # Imagine 'Hello' as a 50x70 characters multi line string. > original = 'Hello' > translated = _('Hello') > print('The translated string "{}" is originally "{}".'.format(translated, > original)) > > I do use the "class based API" of GNU gettext. My current approach, which is > not working, is to somehow (how!?) disable (or mask) the translation function > "_()" temporarily. > But as described in the stackoverflow question (see first line of this mail) > this do not work. > > def foobar(translate): > if not translate: > # I try to mask the global _() builtins-function > def _(txt): > return txt > > return _('Hello') > > if __name__ == '__main__': > > # To ilustrate that _() is part of "builtins" namespace > print(_('No problem.')) > > print('The translated string "{}" is originally "{}".' > .format(foobar(True), foobar(False))) > > This is the output: > > Traceback (most recent call last): > File "/home/user/ownCloud/_transfer/./z.py", line 27, in <module> > .format(foobar(True), foobar(False))) > File "/home/user/ownCloud/_transfer/./z.py", line 19, in foobar > return _('Hello') > UnboundLocalError: local variable '_' referenced before assignment > > The full MWE can be found at stackoverflow > (https://stackoverflow.com/q/76913082/4865723). > > The question is if this can be solved somehow or if there is an alternative > approach. > The "_()" function is installed in the builtins namespace because of gettext > class based API. This is nice. > Maybe I can somehow manipulate that builtins namespace? I tried to import > builtins and played around with it but couldn't find a way to do it. > > Thanks > Christian Buhtz > > PS: This is IMHO not relevant for my question but if someone is interested > the connection to productive code can be found in this issue: > https://github.com/bit-team/backintime/issues/1473 There I describe what I > want to achive and also provide a GUI mockup. > -- > https://mail.python.org/mailman/listinfo/python-list
One thing to remember is that the _() function, which calls gettext doesn’t need a literal string, so you can set a variable to ‘raw’ string, and then translate it to another variable, so you can have both. -- https://mail.python.org/mailman/listinfo/python-list