[blivet master 3/3] Return all translated strings as unicode (#1144314)

David Shea dshea at redhat.com
Wed Oct 15 15:32:39 UTC 2014


pyudev returns all strings as unicode, which is understandable for them,
since python2 unicode is analogous to python3 str and that way they
don't have to care about non-ascii characters, but annoying for us,
since now we have to care about non-ascii characters.

The automatic str to unicode conversions in python 2 only blow up when
there's non-ascii characters, and the only place we're likely to
enounter non-unicode non-ascii strings in blivet is in the values
returned by gettext. So let's switch to the unicode versions of the
gettext methods.
---
 blivet/i18n.py | 30 +++++++++++++++++++++++++++---
 1 file changed, 27 insertions(+), 3 deletions(-)

diff --git a/blivet/i18n.py b/blivet/i18n.py
index 8aca12e..1f07266 100644
--- a/blivet/i18n.py
+++ b/blivet/i18n.py
@@ -21,8 +21,32 @@
 
 __all__ = ["_", "N_", "P_"]
 
-import gettext
+import gettext, locale
+import six
+
+# Create and cache a translations object for the current LC_MESSAGES value
+_cached_translations = {}
+def _get_translations():
+    # Use setlocale instead of getlocale even though that looks like it makes no sense,
+    # since this way we're just reading environment variables instead of mandating some
+    # sequence of setlocale calls or whatever, since this is also how the gettext functions
+    # behave. This differs from the behavior of gettext.find if $LANGUAGE is being used, but
+    # on the other hand no one uses $LANGUAGE.
+    lc_messages = locale.setlocale(locale.LC_MESSAGES, None)
+    if lc_messages not in _cached_translations:
+        _cached_translations[lc_messages] = gettext.translation("blivet", fallback=True)
+    return _cached_translations[lc_messages]
+
 
-_ = lambda x: gettext.ldgettext("blivet", x)
 N_ = lambda x: x
-P_ = lambda x, y, z: gettext.ldngettext("blivet", x, y, z)
+
+# In Python 2, return the translated strings as unicode objects.
+# yes, pylint, the lambdas are necessary, because I want _get_translations()
+# evaluated on every call.
+# pylint: disable=unnecessary-lambda
+if six.PY2:
+    _ = lambda x: _get_translations().ugettext(x)
+    P_ = lambda x, y, z: _get_translations().ungettext(x, y, z)
+else:
+    _ = lambda x: _get_translations().gettext(x)
+    P_ = lambda x, y, z: _get_translations().ngettext(x, y, z)
-- 
2.1.0



More information about the anaconda-patches mailing list