Bug in Localisation library?

Hi @shaun
I am using your excellent Localisation library in our WGACA project, I found it a very elegant solution to localisation problem.
Doing so I found maybe a couple of small bugs I fixed myself but I share so you could update the officially shared library.
I had a KeyError: IT whenever trying to translate a component’s text not present in the translations dictionary.
Debugging that I found the error was the lookup in TRANSLATIONS_LOWER in the function:

def translate(original):
  """Translate a given string."""
  if LOCALE in TRANSLATIONS: 
    if original in TRANSLATIONS[LOCALE] or original.lower() in TRANSLATIONS_LOWER[LOCALE]:
      return TRANSLATIONS[LOCALE][original]
  return original

Looking at how this dictionary is built in the initialise method:

TRANSLATIONS_LOWER = {}
def initialise(locale=None):
  """Set the library up - construct a lower-case dictionary so we can fall back to case-insensitive comparisons."""
  for locale, dictionary in TRANSLATIONS.items():
    for original, translated in dictionary.items():
      if locale not in TRANSLATIONS_LOWER:
        TRANSLATIONS_LOWER[locale] = {}
      TRANSLATIONS_LOWER[original.lower()] = translated.lower() # <===== THIS LINE
  if locale is not None:
    set_locale(locale)

I think that THIS LINE should be:

      TRANSLATIONS_LOWER[locale][original.lower()] = translated.lower()

otherwise the key lookup in translate function will always raise an error.

Having corrected the code I was keeping getting the KeyError and finally I realised that, in order to setup correctly the library, after having called the two functions as in the Library presentation page:

Translations.register_translation(self.label_language, 'text')
Translations.set_locale('IT')

a third step is needed that is:

Translations.initialise('IT')

otherwise the TRANSLATIONS_LOWER dicitonary never gets built.

However, really a nice solution in ANVIL’s style: brilliant, elegant, easy to use.

Thanks and BR and Happy Holy Easter!

4 Likes

Thank you Aldo - I had the same problem and I did your change and that KeyError is now gone.

Ps. If you have tips how to Translate the items in a dropdown that would be appreciated.

Happy Easter and stay safe !

Thanks @aldo.ercolani, I’ve updated the localisations library for your change.

I’ve also updated the set_dictionary method to call initialise(locale), so you shouldn’t have to do this manually to build the TRANSLATIONS_LOWER dictionary.

5 Likes

Thanks Birdget
you guys are awesome!

2 Likes