diff --git a/Lib/imghdr.py b/Lib/imghdr.py --- a/Lib/imghdr.py +++ b/Lib/imghdr.py @@ -1,21 +1,23 @@ """Recognize image file formats based on their first few bytes.""" +from os import PathLike + __all__ = ["what"] #-------------------------# # 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) 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,11 +1,12 @@ 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'), @@ -44,16 +45,22 @@ class TestImghdr(unittest.TestCase): 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: + with self.subTest(filename=filename): + filename = findfile(filename, subdir='imghdrdata') + self.assertEqual(imghdr.what(pathlib.Path(filename)), 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')