Search code examples
pythongettext

How to un-translate a message translated with gettext?


I need to un-translate a message in python. My source is in English, I translate that string using gettext, say in French. I need to "return" to the original string in English. Is it possible in some way?

Here is why: I show some messages in a user interface, so messages needs to be translated. The same function logs that message in a db (debug intended). I want to store the message in the db in its original form (English).

An example:

alert_please( _("message to be shown and stored") )

and here the definition:

def alert_please(translated_message):
   show_the_message(translated_message)
   store_the_message(translated_message)

Fyi, I wouldn't translate the message in the show_the_message call because doing so I won't be able to look through the code to build the message catalog.


Solution

  • Thanks to @martineau I defined my own new _() function in this way:

    reverse_dict = {}
    def translate(msg_to_translate, get_ori=False):
        global reverse_dict
    
        if get_ori:
            return reverse_dict.get(msg_to_translate, msg_to_translate)
    
        translation = en.gettext(msg_to_translate)
        reverse_dict = {translation: msg_to_translate}
    
        return translation
    
    import builtins
    builtins.__dict__['_'] = translate
    

    This call _(msg) just translate the message, the call _(msg, True) returns the original string. In my case I just store one single message: is enough, I log only the last one. The worst case is the return of the translated msg, not the original one.