Need to pass a class instance to a gettext fallback

Peter Otten __peter__ at web.de
Fri Sep 8 02:15:14 EDT 2017


Josef Meile wrote:

> Hi
> 
> I'm working with gettext and need to define a language Fallback. I got
> this working, but with a global variable. I don't really like this and I
> would like to pass this variable to the gettext Fallback's contructor, but
> I don't know how. For simplicity, I won't put the whole code here, just
> the important parts.
> 
> Before you look at it, I want to ask you: how can I pass the variable:
> "my_plugin" to the constructor of the "MissingTranslationsFallback" class?
> If you see, an instance of this class will be created automatically by
> gettext. I don't create it. When calling the " add_fallback" method of the
> gettext.GNUTranslations class, you have to pass a class and not an
> instance.

Provided the class_ argument to gettext.translation() accepts an arbitrary 
callable the following may work:

import functools

> #Defining a global dict, which is ugly, I know
> MY_GLOBALS = {}
> 
> class TranslationService(object):
>   """...__init__ and other methods are defined here"""
> 
>   def install(self):
>     """...some code goes here..."""
 
     current_catalog = gettext.translation(
         plugin_name, 
         localedir=locale_folder,
         class_=functools.partial(
             MissingTranslationsFallback, 
             py_plugin=self._py_plugin
         ), 
         languages=[current_language]
      )
>     current_catalog.install()
> 
> class MissingTranslationsFallback(gettext.GNUTranslations, object):
>   def __init__(self, *args, **kwargs):

      py_plugin = kwargs.pop("py_plugin")

>     super(MissingTranslationsFallback, self).__init__(*args, **kwargs)

>     i18n_service = py_plugin.get_i18n_service()
>     #Adds an instance to the class that will handle the missing
>     #translations
>     
self.add_fallback(MissingTranslationsLogger(i18n_service.get_language()))





More information about the Python-list mailing list