i18n in a library
Mathias Waack
mathias-usenet at valpo.de
Wed Apr 23 09:11:42 EDT 2003
"Martin v. Löwis" <martin.vonloewis at hpi.uni-potsdam.de> wrote:
>> I think what you want is gettext.translation, which offers you
>> finer-grained control than gettext.install. I.e., within the
>> modules of library L, you could use
>>
>> import gettext
>> _ = gettext.translation('L').ugettext
>>
>> so that in those modules function _ will look things up in
>> domain 'L', rather than in whatever domain is "installed"
>> globally.
Unfortunatly I need some more code (because of some historical
reasons) to setup the translation. Its very ugly to add these
lines to each source file. I don't like copy'n'paste as
programming style.
> Alternatively, gettext.dgettext is the Python version of the
> equivalent C API, so you could also do
>
> def _(msg):
> return gettext.dgettext('L', msg)
>
> This has the added advantage of returning the string itself if
> no catalog can be found (instead of giving IOError as
> gettext.translation does)
Thus I have no chance to see if the translation fails.
But your advices (and a short view into gettext.py) lead me to
another solution:
class Translation:
def __init__(self, module):
localedir = ... # its a bit special in our environment
language = ... # see above
try:
self.moduleCatalog = \
gettext.translation(module,localedir,[language])
except:
self.moduleCatalog = gettext.NullTranslations()
self.moduleCatalog._catalog = {}
try:
self.libCatalog = \
gettext.translation('library',localedir,[language])
except:
self.libCatalog = gettext.NullTranslations()
self.libCatalog._catalog = {}
import __builtin__
__builtin__.__dict__['_'] = self.gettext
def gettext(self,message):
return self.moduleCatalog._catalog.get(message) \
or self.libCatalog._catalog.get(message,message)
(The c'tor has some overhead which is needed somewhere else)
This looks first into the module's catalog and if it fails into
the libraries catalog. Don't know if its nice, but it works...
Mathias
More information about the Python-list
mailing list