GNU gettext: Print string translated and untranslated at the same time

Mirko mirkok.lists at googlemail.com
Thu Aug 17 12:19:35 EDT 2023


Am 17.08.23 um 09:10 schrieb c.buhtz--- via Python-list:


>      UnboundLocalError: local variable '_' referenced before assignment

This is a common gotcha:

https://docs.python.org/3/faq/programming.html#why-am-i-getting-an-unboundlocalerror-when-the-variable-has-a-value

You could solve it by defining _() locally like so:


def foobar(translate):
     _ = gettext.gettext
     if not translate:
         # I try to mask the global _() builtins-function
         def _(txt):
             return txt
     return _('minutes')


> The question is if this can be solved somehow or if there is an alternative approach.

However, you might not need this, because the following seems to 
work for me:

def orig_and_trans(msg):
     return (_(msg), msg)

print('The translated string "{}" is originally 
"{}".'.format(*orig_and_trans("hello")))



More information about the Python-list mailing list