简体   繁体   中英

Internationalizing subpackages in a Python application

I have an internationalized application written against Python 2.7. In it I use a few packages I have written. I would like user-visible text in these packages to be translated.

Given that the application installs _ into the __builtin__ namespace with translation.install , how do I get the individual packages to have their text translated with their particular translations which have their own domains? Is it possible to merge two translations, for instance? Then I could just have the application merge the packages translation on import if I put it in a conventional place.

Do I have to define _ and my other gettext helpers at the top of each subpackage? If so, how can they pick up on the application's configured language while remaining loosely coupled?

This feels like it's more complicated than it should be, which leads me to believe I'm not understanding something.

I would recommend not installing _ into builtins, but rather defining it inside your package's __init__ and explicitly importing it in the other modules.

Eg mypackage/__init__.py :

import gettext
translations = gettext.translation('mypackage')
_ = translations.ugettext

and then elsewhere

from mypackage import _

some_string = _("Something that will be translated")

I haven't actually used gettext in a long while, so take this example with a gain of salt (although it was based on the recommendation in gettext's documentation ).

I've been mostly working with Zope-based web applications that cannot do the translation during module import -- we need to delay the actual translation until request rendering time, so we know the user's preferred language. We use zope.i18nmessageid's MessageFactory to mark strings for translation in a very similar way:

# mypackage/__init__.py
from zope.i18nmessageid import MessageFactory
_ = MessageFactory("mypackage")

# mypackage/somemodule.py
from mypackage import _
some_string = _("Something that will be translated later")
# e.g. with print zope.i18n.translate(some_string, request)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM