diff -r 954b83e0c79a Lib/imghdr.py --- a/Lib/imghdr.py Tue Dec 17 12:45:44 2013 +0200 +++ b/Lib/imghdr.py Tue Dec 17 13:12:25 2013 +0200 @@ -8,14 +8,16 @@ def what(file, h=None): if h is None: - if isinstance(file, str): + try: f = open(file, 'rb') - h = f.read(32) - else: + except TypeError: + # a file stream location = file.tell() h = file.read(32) file.seek(location) f = None + else: + h = f.read(32) else: f = None try: diff -r 954b83e0c79a Lib/test/test_imghdr.py --- a/Lib/test/test_imghdr.py Tue Dec 17 12:45:44 2013 +0200 +++ b/Lib/test/test_imghdr.py Tue Dec 17 13:12:25 2013 +0200 @@ -1,4 +1,6 @@ import unittest +import os +import io from test.support import TESTFN, unlink import imghdr @@ -41,6 +43,18 @@ self.assertEqual(imghdr.what(TESTFN), format) + def test_file_argument(self): + with open(TESTFN, 'wb') as stream: + stream.write(b'eggs') + # will be closed by `imghdr.what` + stream = open(TESTFN, 'rb') + fileno = stream.fileno() + self.assertIsNone(imghdr.what(fileno)) + self.assertIsNone(imghdr.what(TESTFN)) + self.assertIsNone(imghdr.what(os.fsencode(TESTFN))) + with io.BytesIO(b'BMP') as stream: + self.assertEqual(imghdr.what(stream), 'bmp') + def test_register_test(self): def test_jumbo(h, file): if h.startswith(b'eggs'):