Skip to content

Commit b166698

Browse files
committed
Return str rather than bytes for the description strings on python3.
Assumes utf-8 encoding from magic return values, which I hope is always the case.
1 parent f82dc97 commit b166698

2 files changed

Lines changed: 13 additions & 8 deletions

File tree

magic.py

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -72,7 +72,7 @@ def from_buffer(self, buf):
7272
"""
7373
with self.lock:
7474
try:
75-
return magic_buffer(self.cookie, buf)
75+
return maybe_decode(magic_buffer(self.cookie, buf))
7676
except MagicException as e:
7777
return self._handle509Bug(e)
7878

@@ -82,7 +82,7 @@ def from_file(self, filename):
8282
pass
8383
with self.lock:
8484
try:
85-
return magic_file(self.cookie, filename)
85+
return maybe_decode(magic_file(self.cookie, filename))
8686
except MagicException as e:
8787
return self._handle509Bug(e)
8888

@@ -189,6 +189,14 @@ def errorcheck_negative_one(result, func, args):
189189
return result
190190

191191

192+
# return str on python3. Don't want to unconditionally
193+
# decode because that results in unicode on python2
194+
def maybe_decode(s):
195+
if str == bytes:
196+
return s
197+
else:
198+
return s.decode('utf-8')
199+
192200
def coerce_filename(filename):
193201
if filename is None:
194202
return None

test/test.py

Lines changed: 3 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -22,13 +22,11 @@ def assert_values(self, m, expected_values):
2222
expected_value = (expected_value,)
2323

2424
for i in expected_value:
25-
expected_value_bytes = i.encode('utf-8')
26-
2725
with open(filename, 'rb') as f:
2826
buf_value = m.from_buffer(f.read())
2927

3028
file_value = m.from_file(filename)
31-
if buf_value == expected_value_bytes and file_value == expected_value_bytes:
29+
if buf_value == i and file_value == i:
3230
break
3331
else:
3432
self.assertTrue(False, "no match for " + repr(expected_value))
@@ -86,11 +84,10 @@ def test_keep_going(self):
8684
filename = os.path.join(self.TESTDATA_DIR, 'keep-going.jpg')
8785

8886
m = magic.Magic(mime=True)
89-
self.assertEqual(m.from_file(filename),
90-
'image/jpeg'.encode('utf-8'))
87+
self.assertEqual(m.from_file(filename), 'image/jpeg')
9188

9289
m = magic.Magic(mime=True, keep_going=True)
93-
self.assertEqual(m.from_file(filename), 'image/jpeg'.encode('utf-8'))
90+
self.assertEqual(m.from_file(filename), 'image/jpeg')
9491

9592

9693
def test_rethrow(self):

0 commit comments

Comments
 (0)