[PATCHv2] Make translation to lowerASCII Python[23]-compatible

Vratislav Podzimek vpodzime at redhat.com
Wed Feb 18 09:34:11 UTC 2015


If we are given a byte string in Python 3 we need to convert it to str (unicode)
first because otherwise we would need another translation table (for the 'bytes'
type) and we would need to convert the result into str (unicode) because that's
what the calling code expects.

Signed-off-by: Vratislav Podzimek <vpodzime at redhat.com>
---
 blivet/size.py | 15 ++++++++++-----
 1 file changed, 10 insertions(+), 5 deletions(-)

diff --git a/blivet/size.py b/blivet/size.py
index da44343..f493012 100644
--- a/blivet/size.py
+++ b/blivet/size.py
@@ -22,6 +22,7 @@
 import re
 import string
 import locale
+import sys
 from collections import namedtuple
 
 from decimal import Decimal
@@ -78,14 +79,18 @@ else:
 def _lowerASCII(s):
     """Convert a string to lowercase using only ASCII character definitions.
 
-       :param str s: string to convert
+       :param s: string instance to convert
+       :type s: str or bytes
        :returns: lower-cased string
        :rtype: str
     """
-    if six.PY2:
-        return string.translate(s, _ASCIIlower_table) # pylint: disable=no-member
-    else:
-        return str.translate(s, _ASCIIlower_table) # pylint: disable=no-member
+
+    # XXX: Python 3 has str.maketrans() and bytes.maketrans() so we should
+    # ideally use one or the other depending on the type of 's'. But it turns
+    # out we expect this function to always return string even if given bytes.
+    if not six.PY2 and isinstance(s, bytes):
+        s = s.decode(sys.getdefaultencoding())
+    return s.translate(_ASCIIlower_table) # pylint: disable=no-member
 
 def _makeSpec(prefix, suffix, xlate, lowercase=True):
     """ Synthesizes a whole word from prefix and suffix.
-- 
2.1.0



More information about the anaconda-patches mailing list