Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to know if a translation string exists with gettext?

Tags:

python

gettext

I would like to know if it is possible to check at runtime if a string to translate exists in gettext.

It is for debug purpose only.

Sometime strings to translate are slightly updated and no one think to update the po file. The mistake stays until someone finds it or decides to update the po file for another reason.

If there is a better way to manage this case, I am also interested.

like image 991
djoproject Avatar asked Dec 07 '25 07:12

djoproject


1 Answers

It's a little hacky, but it works? I'm setting the fallback for translation class to a custom one that notifies us when a translation wasn't found. Not sure what your setup is, but some variant of this should work, right?

# translate.py
import gettext
import os.path

missed_translations = set()
class MyFallback(gettext.NullTranslations):
    def gettext(self, msg):
        # do whatever you want to do when no translation found
        # like log a message, or email someone, or raise an exception
        missed_translations.add(msg)
        return msg

class MyTranslations(gettext.GNUTranslations, object):
    def __init__(self, *args, **kwargs):
        super(MyTranslations, self).__init__(*args, **kwargs)
        self.add_fallback(MyFallback())

lang1 = gettext.translation(
    "translate",
    localedir=os.path.expanduser("~/Projects/translate/locale"),
    languages=["es"],
    class_=MyTranslations
)
lang1.install()
print(_("Hello World"))
print(_("Hello world"))
print(_("nope"))

print("Missing translations for: " + ", ".join(missed_translations))

My directory structure in case you want to reproduce:

├── __init__.py
├── locale
│   ├── es
│   │   └── LC_MESSAGES
│   │       └── translate.mo
│   └── messages-es_ES.po
└── translate.py

Running it looks like this:

$> python translate.py
Hola Mundo
Hello world
nope
Missing translations for: nope, Hello world
like image 196
Alejandro Avatar answered Dec 08 '25 19:12

Alejandro