diff --git a/Lib/imghdr.py b/Lib/imghdr.py --- a/Lib/imghdr.py +++ b/Lib/imghdr.py @@ -1,23 +1,25 @@ """Recognize image file formats based on their first few bytes.""" __all__ = ["what"] +from os import PathLike + #-------------------------# # Recognize image headers # #-------------------------# def what(file, h=None): f = None try: if h is None: - if isinstance(file, str): + if isinstance(file, (str, PathLike)): f = open(file, 'rb') h = f.read(32) else: location = file.tell() h = file.read(32) file.seek(location) for tf in tests: res = tf(h, f) if res: return res diff --git a/Lib/test/test_imghdr.py b/Lib/test/test_imghdr.py --- a/Lib/test/test_imghdr.py +++ b/Lib/test/test_imghdr.py @@ -1,13 +1,14 @@ import imghdr import io import os +import pathlib import unittest import warnings from test.support import findfile, TESTFN, unlink TEST_FILES = ( ('python.png', 'png'), ('python.gif', 'gif'), ('python.bmp', 'bmp'), ('python.ppm', 'ppm'), ('python.pgm', 'pgm'), @@ -42,20 +43,31 @@ class TestImghdr(unittest.TestCase): for filename, expected in TEST_FILES: filename = findfile(filename, subdir='imghdrdata') self.assertEqual(imghdr.what(filename), expected) with open(filename, 'rb') as stream: self.assertEqual(imghdr.what(stream), expected) with open(filename, 'rb') as stream: data = stream.read() self.assertEqual(imghdr.what(None, data), expected) self.assertEqual(imghdr.what(None, bytearray(data)), expected) + def test_pathlike_filename(self): + for filename, expected in TEST_FILES: + filename = findfile(filename, subdir='imghdrdata') + self.assertEqual(imghdr.what(pathlib.Path(filename)), expected) + with open(filename, 'rb') as stream: + self.assertEqual(imghdr.what(stream), expected) + with open(filename, 'rb') as stream: + data = stream.read() + self.assertEqual(imghdr.what(None, data), expected) + self.assertEqual(imghdr.what(None, bytearray(data)), expected) + def test_register_test(self): def test_jumbo(h, file): if h.startswith(b'eggs'): return 'ham' imghdr.tests.append(test_jumbo) self.addCleanup(imghdr.tests.pop) self.assertEqual(imghdr.what(None, b'eggs'), 'ham') def test_file_pos(self): with open(TESTFN, 'wb') as stream: