Use bytes instead of str where appropriate

Under Python 2, "str" and "bytes" are synonyms.

Reviewed-By: Petr Viktorin <pviktori@redhat.com>
This commit is contained in:
Jan Cholasta
2015-09-11 14:02:13 +02:00
parent 23507e6124
commit ba5201979d
6 changed files with 33 additions and 33 deletions

View File

@@ -141,7 +141,7 @@ class textui(backend.Backend):
""" """
Decode text from stdin. Decode text from stdin.
""" """
if type(value) is str: if type(value) is bytes:
encoding = self.__get_encoding(sys.stdin) encoding = self.__get_encoding(sys.stdin)
return value.decode(encoding) return value.decode(encoding)
elif type(value) in (list, tuple): elif type(value) in (list, tuple):
@@ -166,7 +166,7 @@ class textui(backend.Backend):
Convert a binary value to base64. We know a value is binary Convert a binary value to base64. We know a value is binary
if it is a python str type, otherwise it is a plain string. if it is a python str type, otherwise it is a plain string.
""" """
if type(value) is str: if type(value) is bytes:
return base64.b64encode(value) return base64.b64encode(value)
elif type(value) is datetime.datetime: elif type(value) is datetime.datetime:
return value.strftime(LDAP_GENERALIZED_TIME_FORMAT) return value.strftime(LDAP_GENERALIZED_TIME_FORMAT)

View File

@@ -1333,7 +1333,7 @@ class Bytes(Data):
Also see the `Str` parameter. Also see the `Str` parameter.
""" """
type = str type = bytes
type_error = _('must be binary data') type_error = _('must be binary data')
def __init__(self, name, *rules, **kw): def __init__(self, name, *rules, **kw):
@@ -1348,7 +1348,7 @@ class Bytes(Data):
""" """
Check minlength constraint. Check minlength constraint.
""" """
assert type(value) is str assert type(value) is bytes
if len(value) < self.minlength: if len(value) < self.minlength:
return _('must be at least %(minlength)d bytes') % dict( return _('must be at least %(minlength)d bytes') % dict(
minlength=self.minlength, minlength=self.minlength,
@@ -1358,7 +1358,7 @@ class Bytes(Data):
""" """
Check maxlength constraint. Check maxlength constraint.
""" """
assert type(value) is str assert type(value) is bytes
if len(value) > self.maxlength: if len(value) > self.maxlength:
return _('can be at most %(maxlength)d bytes') % dict( return _('can be at most %(maxlength)d bytes') % dict(
maxlength=self.maxlength, maxlength=self.maxlength,
@@ -1368,7 +1368,7 @@ class Bytes(Data):
""" """
Check length constraint. Check length constraint.
""" """
assert type(value) is str assert type(value) is bytes
if len(value) != self.length: if len(value) != self.length:
return _('must be exactly %(length)d bytes') % dict( return _('must be exactly %(length)d bytes') % dict(
length=self.length, length=self.length,

View File

@@ -248,7 +248,7 @@ def entry_to_dict(entry, **options):
for attr in entry: for attr in entry:
if attr.lower() == 'attributelevelrights': if attr.lower() == 'attributelevelrights':
value = entry[attr] value = entry[attr]
elif entry.conn.get_attribute_type(attr) is str: elif entry.conn.get_attribute_type(attr) is bytes:
value = entry.raw[attr] value = entry.raw[attr]
else: else:
value = list(entry.raw[attr]) value = list(entry.raw[attr])
@@ -1082,7 +1082,7 @@ last, after all sets and adds."""),
try: try:
entry_attrs[attr].remove(delval) entry_attrs[attr].remove(delval)
except ValueError: except ValueError:
if isinstance(delval, str): if isinstance(delval, bytes):
# This is a Binary value, base64 encode it # This is a Binary value, base64 encode it
delval = unicode(base64.b64encode(delval)) delval = unicode(base64.b64encode(delval))
raise errors.AttrValueNotFound(attr=attr, value=delval) raise errors.AttrValueNotFound(attr=attr, value=delval)

View File

@@ -164,7 +164,7 @@ def xml_wrap(value, version):
return dict( return dict(
(k, xml_wrap(v, version)) for (k, v) in value.items() (k, xml_wrap(v, version)) for (k, v) in value.items()
) )
if type(value) is str: if type(value) is bytes:
return Binary(value) return Binary(value)
if type(value) is Decimal: if type(value) is Decimal:
# transfer Decimal as a string # transfer Decimal as a string
@@ -221,7 +221,7 @@ def xml_unwrap(value, encoding='UTF-8'):
if type(value) is str: if type(value) is str:
return value.decode(encoding) return value.decode(encoding)
if isinstance(value, Binary): if isinstance(value, Binary):
assert type(value.data) is str assert type(value.data) is bytes
return value.data return value.data
if isinstance(value, DateTime): if isinstance(value, DateTime):
# xmlprc DateTime is converted to string of %Y%m%dT%H:%M:%S format # xmlprc DateTime is converted to string of %Y%m%dT%H:%M:%S format
@@ -290,7 +290,7 @@ def json_encode_binary(val, version):
elif isinstance(val, (list, tuple)): elif isinstance(val, (list, tuple)):
new_list = [json_encode_binary(v, version) for v in val] new_list = [json_encode_binary(v, version) for v in val]
return new_list return new_list
elif isinstance(val, str): elif isinstance(val, bytes):
return {'__base64__': base64.b64encode(val)} return {'__base64__': base64.b64encode(val)}
elif isinstance(val, Decimal): elif isinstance(val, Decimal):
return {'__base64__': base64.b64encode(str(val))} return {'__base64__': base64.b64encode(str(val))}

View File

@@ -339,7 +339,7 @@ class LDAPEntry(collections.MutableMapping):
"attribute name must be unicode or str, got %s object %r" % ( "attribute name must be unicode or str, got %s object %r" % (
name.__class__.__name__, name)) name.__class__.__name__, name))
if isinstance(name, str): if isinstance(name, bytes):
name = name.decode('utf-8') name = name.decode('utf-8')
return name return name
@@ -393,7 +393,7 @@ class LDAPEntry(collections.MutableMapping):
raise TypeError("%s value must be list, got %s object %r" % ( raise TypeError("%s value must be list, got %s object %r" % (
name, value.__class__.__name__, value)) name, value.__class__.__name__, value))
for (i, item) in enumerate(value): for (i, item) in enumerate(value):
if not isinstance(item, str): if not isinstance(item, bytes):
raise TypeError("%s[%d] value must be str, got %s object %r" % ( raise TypeError("%s[%d] value must be str, got %s object %r" % (
name, i, item.__class__.__name__, item)) name, i, item.__class__.__name__, item))
@@ -619,19 +619,19 @@ class LDAPClient(object):
SCOPE_SUBTREE = ldap.SCOPE_SUBTREE SCOPE_SUBTREE = ldap.SCOPE_SUBTREE
_SYNTAX_MAPPING = { _SYNTAX_MAPPING = {
'1.3.6.1.4.1.1466.115.121.1.1' : str, # ACI item '1.3.6.1.4.1.1466.115.121.1.1' : bytes, # ACI item
'1.3.6.1.4.1.1466.115.121.1.4' : str, # Audio '1.3.6.1.4.1.1466.115.121.1.4' : bytes, # Audio
'1.3.6.1.4.1.1466.115.121.1.5' : str, # Binary '1.3.6.1.4.1.1466.115.121.1.5' : bytes, # Binary
'1.3.6.1.4.1.1466.115.121.1.8' : str, # Certificate '1.3.6.1.4.1.1466.115.121.1.8' : bytes, # Certificate
'1.3.6.1.4.1.1466.115.121.1.9' : str, # Certificate List '1.3.6.1.4.1.1466.115.121.1.9' : bytes, # Certificate List
'1.3.6.1.4.1.1466.115.121.1.10' : str, # Certificate Pair '1.3.6.1.4.1.1466.115.121.1.10' : bytes, # Certificate Pair
'1.3.6.1.4.1.1466.115.121.1.12' : DN, # Distinguished Name '1.3.6.1.4.1.1466.115.121.1.12' : DN, # Distinguished Name
'1.3.6.1.4.1.1466.115.121.1.23' : str, # Fax '1.3.6.1.4.1.1466.115.121.1.23' : bytes, # Fax
'1.3.6.1.4.1.1466.115.121.1.24' : datetime.datetime, '1.3.6.1.4.1.1466.115.121.1.24' : datetime.datetime,
'1.3.6.1.4.1.1466.115.121.1.28' : str, # JPEG '1.3.6.1.4.1.1466.115.121.1.28' : bytes, # JPEG
'1.3.6.1.4.1.1466.115.121.1.40' : str, # OctetString (same as Binary) '1.3.6.1.4.1.1466.115.121.1.40' : bytes, # OctetString (same as Binary)
'1.3.6.1.4.1.1466.115.121.1.49' : str, # Supported Algorithm '1.3.6.1.4.1.1466.115.121.1.49' : bytes, # Supported Algorithm
'1.3.6.1.4.1.1466.115.121.1.51' : str, # Teletext Terminal Identifier '1.3.6.1.4.1.1466.115.121.1.51' : bytes, # Teletext Terminal Identifier
'2.16.840.1.113730.3.8.3.3' : DN, # enrolledBy '2.16.840.1.113730.3.8.3.3' : DN, # enrolledBy
'2.16.840.1.113730.3.8.3.18' : DN, # managedBy '2.16.840.1.113730.3.8.3.18' : DN, # managedBy
@@ -772,7 +772,7 @@ class LDAPClient(object):
def get_attribute_type(self, name_or_oid): def get_attribute_type(self, name_or_oid):
if not self._decode_attrs: if not self._decode_attrs:
return str return bytes
if isinstance(name_or_oid, unicode): if isinstance(name_or_oid, unicode):
name_or_oid = name_or_oid.encode('utf-8') name_or_oid = name_or_oid.encode('utf-8')
@@ -837,7 +837,7 @@ class LDAPClient(object):
return value_to_utf8(val) return value_to_utf8(val)
elif isinstance(val, DNSName): elif isinstance(val, DNSName):
return val.to_text() return val.to_text()
elif isinstance(val, str): elif isinstance(val, bytes):
return val return val
elif isinstance(val, list): elif isinstance(val, list):
return [self.encode(m) for m in val] return [self.encode(m) for m in val]
@@ -857,10 +857,10 @@ class LDAPClient(object):
""" """
Decode attribute value from LDAP representation (str). Decode attribute value from LDAP representation (str).
""" """
if isinstance(val, str): if isinstance(val, bytes):
target_type = self.get_attribute_type(attr) target_type = self.get_attribute_type(attr)
try: try:
if target_type is str: if target_type is bytes:
return val return val
elif target_type is unicode: elif target_type is unicode:
return val.decode('utf-8') return val.decode('utf-8')

View File

@@ -67,8 +67,8 @@ def test_round_trip():
assert_equal(dump_n_load(unicode_str), unicode_str) assert_equal(dump_n_load(unicode_str), unicode_str)
assert_equal(dump_n_load(Binary(binary_bytes)).data, binary_bytes) assert_equal(dump_n_load(Binary(binary_bytes)).data, binary_bytes)
assert isinstance(dump_n_load(Binary(binary_bytes)), Binary) assert isinstance(dump_n_load(Binary(binary_bytes)), Binary)
assert type(dump_n_load('hello')) is str assert type(dump_n_load('hello')) is bytes
assert type(dump_n_load(u'hello')) is str assert type(dump_n_load(u'hello')) is bytes
assert_equal(dump_n_load(''), '') assert_equal(dump_n_load(''), '')
assert_equal(dump_n_load(u''), '') assert_equal(dump_n_load(u''), '')
assert dump_n_load(None) is None assert dump_n_load(None) is None
@@ -81,7 +81,7 @@ def test_round_trip():
assert_equal(round_trip(utf8_bytes), utf8_bytes) assert_equal(round_trip(utf8_bytes), utf8_bytes)
assert_equal(round_trip(unicode_str), unicode_str) assert_equal(round_trip(unicode_str), unicode_str)
assert_equal(round_trip(binary_bytes), binary_bytes) assert_equal(round_trip(binary_bytes), binary_bytes)
assert type(round_trip('hello')) is str assert type(round_trip('hello')) is bytes
assert type(round_trip(u'hello')) is unicode assert type(round_trip(u'hello')) is unicode
assert_equal(round_trip(''), '') assert_equal(round_trip(''), '')
assert_equal(round_trip(u''), u'') assert_equal(round_trip(u''), u'')
@@ -116,13 +116,13 @@ def test_xml_unwrap():
assert f([]) == tuple() assert f([]) == tuple()
assert f({}) == dict() assert f({}) == dict()
value = f(Binary(utf8_bytes)) value = f(Binary(utf8_bytes))
assert type(value) is str assert type(value) is bytes
assert value == utf8_bytes assert value == utf8_bytes
assert f(utf8_bytes) == unicode_str assert f(utf8_bytes) == unicode_str
assert f(unicode_str) == unicode_str assert f(unicode_str) == unicode_str
value = f([True, Binary('hello'), dict(one=1, two=utf8_bytes, three=None)]) value = f([True, Binary('hello'), dict(one=1, two=utf8_bytes, three=None)])
assert value == (True, 'hello', dict(one=1, two=unicode_str, three=None)) assert value == (True, 'hello', dict(one=1, two=unicode_str, three=None))
assert type(value[1]) is str assert type(value[1]) is bytes
assert type(value[2]['two']) is unicode assert type(value[2]['two']) is unicode