使用多个i18n域实现Python应用程序国际化的最佳方法是什么?

时间:2022-07-02 12:28:31

I'm internationalizing a Python application, with two goals in mind:

我正在国际化Python应用程序,有两个目标:

  1. The application loads classes from multiple packages, each with its own i18n domain. So modules in package A are using domain A, modules in package B are using domain B, etc.

    该应用程序从多个包中加载类,每个包都有自己的i18n域。因此,包A中的模块使用域A,包B中的模块使用域B等。

  2. The locale can be changed while the application is running.

    应用程序运行时可以更改区域设置。

Python's gettext module makes internationalizing a single-domain single-language application very easy; you just set the locale, then call gettext.install(), which finds the right Translation and installs its ugettext method in the global namespace as _. But obviously a global value only works for a single domain, and since it loads a single Translation, it only works for that locale.

Python的gettext模块使单域单语言应用程序的国际化变得非常容易;你只需设置语言环境,然后调用gettext.install(),它找到正确的翻译并在全局命名空间中将其ugettext方法安装为_。但显然,全局值仅适用于单个域,并且由于它加载单个转换,因此它仅适用于该语言环境。

I could instead load the Translation at the top of each module, and bind its ugettext method as _. Then each module would be using the _ for its own domain. But this still breaks when the locale is changed, because _ is for the wrong locale.

我可以在每个模块的顶部加载Translation,并将其ugettext方法绑定为_。然后每个模块将使用_作为自己的域。但是当语言环境发生变化时,这仍然会中断,因为_是错误的语言环境。

So I guess I could load the correct ugettext at the top of every function, but that seems awfully cumbersome. An alternative would be to still do it per-module, but instead of binding ugettext, I would substitute my own function, which would check the current locale, get its Translation, and forward the string to it. Does anyone have a cleaner solution?

所以我想我可以在每个函数的顶部加载正确的ugettext,但这看起来非常麻烦。另一种方法是仍然按模块执行,但不是绑定ugettext,而是替换我自己的函数,它将检查当前的语言环境,获取其翻译,并将字符串转发给它。有没有人有更清洁的解决方案?

1 个解决方案

#1


how about you bind _ to a function roughly like this (for each module):

如何将_绑定到一个大致相似的函数(对于每个模块):

def _(message):
    return my_gettext(__name__, message)

This allows you to use gettext while at the same time perform any lookup on a per-module-per-call-base that allows you to switch locale as well.

这允许您使用gettext,同时在每个模块的每个调用基础上执行任何查找,这也允许您切换区域设置。

#1


how about you bind _ to a function roughly like this (for each module):

如何将_绑定到一个大致相似的函数(对于每个模块):

def _(message):
    return my_gettext(__name__, message)

This allows you to use gettext while at the same time perform any lookup on a per-module-per-call-base that allows you to switch locale as well.

这允许您使用gettext,同时在每个模块的每个调用基础上执行任何查找,这也允许您切换区域设置。