The gettext.install() function installs a builtin _() function which
translates a string in the translation domain supplied to the install()
function. If gettext.install() is called multiple times, it's the last
call to the function which wins and the last supplied translation domain
which is used e.g.
>>> import os
>>> os.environ['LANG'] = 'ja.UTF-8'
>>> import gettext
>>> gettext.install('keystone', unicode=1, localedir='/opt/stack/keystone/keystone/locale')
>>> print _('Invalid syslog facility')
無効な syslog ファシリティ
>>> gettext.install('nova', unicode=1, localedir='/opt/stack/nova/nova/locale')
>>> print _('Invalid syslog facility')
Invalid syslog facility
Usually this function is called early on in a toplevel script and we
assume that no other code will call it and override the installed _().
However, in Nova, we have taken a shortcut to avoid having to call it
explicitly from each script and instead call it from nova/__init__.py.
This shortcut would be perfectly fine if we were absolutely sure that
nova modules would never be imported from another program. It's probably
quite incorrect for a program to use nova code (indeed, if we wanted to
support this, Nova code shouldn't use the default _() function) but
nevertheless there are some corner cases where it happens. For example,
the keystoneclient auth_token middleware tries to import cfg from
nova.openstack.common and this in turn causes gettext.install('nova')
in other projects like glance or quantum.
To avoid any doubt here, let's just rip out the shortcut and always
call gettext.install() from the top-level script.
Change-Id: If4125d6bcbde63df95de129ac5c83b4a6d6f130a
1.2 KiB
Internationalization
nova uses gettext so that user-facing strings such as log messages appear in the appropriate language in different locales.
To use gettext, make sure that the strings passed to the logger are
wrapped in a _() function call. For example:
LOG.debug(_("block_device_mapping %s"), block_device_mapping)
If you have multiple arguments, the convention is to use named
parameters. It's common to use the locals() dict (which
contains the names and values of the local variables in the current
scope) to do the string interpolation. For example:
label = ...
sr_ref = ...
LOG.debug(_('Introduced %(label)s as %(sr_ref)s.') % locals())
If you do not follow the project conventions, your code may cause the LocalizationTestCase.test_multiple_positional_format_placeholders test to fail in nova/tests/test_localization.py.
The _() function is brought into the global scope by
doing:
import gettext
gettext.install("nova", unicode=1)
These lines are needed in any toplevel script before any nova modules are imported. If this code is missing, it may result in an error that looks like:
NameError: name '_' is not defined