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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With