h2non / filetype.py

Small, dependency-free, fast Python package to infer binary file types checking the magic numbers signature
https://h2non.github.io/filetype.py
MIT License
663 stars 113 forks source link

For Python 3.13: A drop-in replacement for `imghdr.what()` #178

Closed cclauss closed 5 months ago

cclauss commented 6 months ago

The Python 3.13 release notes mention filetype.py as one of the alternatives for imghdr which was removed from the Standard Library.

Given the discussion in #175, it might be quite helpful to have a drop-in replacement for imghdr.what(). It would provide a smooth transition to Py3.13 if developers could confidently replace all instances of imghdr.what() with filetype.what() -- same args, same results.

Current pytest results: 49 passed in 0.04s

def what(file: PathLike | str | None, h: bytes | None) -> str:
    """A drop-in replacement for `imghdr.what()` which was removed from the standard
    library in Python 3.13."""

Usage:

# Replace...
from imghdr import what
# with...
from filetype import what

# Or replace...
import imghdr
ext = imghdr.what(...)
# with...
import filetype
ext = filetype.what(...)

imghdr documentation: https://docs.python.org/3.12/library/imghdr.html imghdr source code: https://github.com/python/cpython/blob/3.12/Lib/imghdr.py

cclauss commented 5 months ago

Closing in favor of puremagic.what() because it has better recognition of image file formats.