Skip to content

Commit ef223a1

Browse files
committed
Issue #28228: imghdr now supports pathlib
1 parent 6c63f19 commit ef223a1

4 files changed

Lines changed: 15 additions & 1 deletion

File tree

Doc/library/imghdr.rst

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,9 @@ The :mod:`imghdr` module defines the following function:
2020
string describing the image type. If optional *h* is provided, the *filename*
2121
is ignored and *h* is assumed to contain the byte stream to test.
2222

23+
.. versionchanged:: 3.6
24+
Accepts a :term:`path-like object`.
25+
2326
The following image types are recognized, as listed below with the return value
2427
from :func:`what`:
2528

Lib/imghdr.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
"""Recognize image file formats based on their first few bytes."""
22

3+
from os import PathLike
4+
35
__all__ = ["what"]
46

57
#-------------------------#
@@ -10,7 +12,7 @@ def what(file, h=None):
1012
f = None
1113
try:
1214
if h is None:
13-
if isinstance(file, str):
15+
if isinstance(file, (str, PathLike)):
1416
f = open(file, 'rb')
1517
h = f.read(32)
1618
else:

Lib/test/test_imghdr.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import imghdr
22
import io
33
import os
4+
import pathlib
45
import unittest
56
import warnings
67
from test.support import findfile, TESTFN, unlink
@@ -49,6 +50,12 @@ def test_data(self):
4950
self.assertEqual(imghdr.what(None, data), expected)
5051
self.assertEqual(imghdr.what(None, bytearray(data)), expected)
5152

53+
def test_pathlike_filename(self):
54+
for filename, expected in TEST_FILES:
55+
with self.subTest(filename=filename):
56+
filename = findfile(filename, subdir='imghdrdata')
57+
self.assertEqual(imghdr.what(pathlib.Path(filename)), expected)
58+
5259
def test_register_test(self):
5360
def test_jumbo(h, file):
5461
if h.startswith(b'eggs'):

Misc/NEWS

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,8 @@ Core and Builtins
4646
Library
4747
-------
4848

49+
- Issue #28228: imghdr now supports pathlib.
50+
4951
- Issue #28226: compileall now supports pathlib.
5052

5153
- Issue #28314: Fix function declaration (C flags) for the getiterator() method

0 commit comments

Comments
 (0)