ahupp / python-magic

A python wrapper for libmagic
Other
2.59k stars 280 forks source link

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

Closed cclauss closed 2 months ago

cclauss commented 3 months ago

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

Given the discussion in #317, 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 magic.what() -- same args, same results.

Current pytest results: 45 passed in 0.05s

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 magic import what

# Or replace...
import imghdr
ext = imghdr.what(...)
# with...
import magic
ext = magic.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 2 months ago

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