All jobs

Fix "ModuleNotFoundError: No module named 'imghdr'" on Python 3.13

Yes. An agent replaces the removed imghdr module with a header check or a small library, and tests it on the image formats your code handles.

Run this on RushOpens the console with this prompt ready to send, in a Project that has your repository.

What the agent does

Python 3.13 removed imghdr, the standard-library module that guessed an image's format from its first bytes. Programs that import it stop at startup. ostrolucky/Bulk-Bing-Image-downloader is a compact example. Its script, bbid/bbid.py, has import imghdr on line 4, so on 3.13 even bbid.py --help ends in the traceback from the title. On 3.12 the same command works and prints DeprecationWarning: 'imghdr' is deprecated and slated for removal in Python 3.13. The module is used once, on line 68, as imghdr.what(BytesIO(image), image) right after a download.

The agent reads what the result is for before choosing a replacement, because imghdr.what did two jobs in this script. A falsy result means the bytes are not an image, and the download is skipped with SKIP: Invalid image. A truthy result becomes the file extension, through ext = 'jpg' if imgtype == 'jpeg' else imgtype. Any replacement has to return nothing for an HTML error page and has to produce a name that mapping still handles. It also checks the packaging: setup.py declares install_requires=[] and python_requires='>=3', so this is a script with no third-party dependencies at all.

That last fact drives the choice. Python's documentation points to libraries such as filetype and puremagic, and they are not interchangeable with the old call. filetype reports a JPEG as jpg, not jpeg, and returns nothing for HTML. puremagic answers with a dotted extension, such as .jfif for a JPEG, and it also identifies non-images, returning .html for a web page, which would defeat the validity check if swapped in blindly. For a zero-dependency script the agent writes a short local function that checks the signatures of the formats a web image search returns: JPEG, PNG, GIF, BMP, WebP and TIFF. It keeps the return values imghdr used, so line 68 changes and the lines after it do not.

Then it tests the edges. The old JPEG check only accepted files with a JFIF or Exif marker or one specific four-byte prefix, so a JPEG that begins with an ICC profile segment came back as None and the script discarded a valid picture. A check on the three-byte JPEG signature accepts it. The agent writes a table-driven test with header samples for each format, that ICC case, an HTML page and empty input, runs it on 3.12 against both the old module and the new function to show where they differ, and runs it again on 3.13.

Start it with one API call

POST https://api.phoenix.so/o/{org}/sessions with this body:

{
  "agent": "claude",
  "input": "This project fails on Python 3.13 with \"ModuleNotFoundError: No module named 'imghdr'\". Reproduce it on a clean Python 3.13 and record the traceback. Find every import and call of imghdr (and sndhdr, removed in the same release). For each call, describe what the result is used for: validation, choosing a file extension or content type, or branching on a format. List which formats matter to this code. Then choose a replacement and justify it. If the project already depends on Pillow, python-magic, filetype or puremagic, use that. If it has no third-party dependencies and needs only common formats, write a small local function that checks file signatures and returns the same names imghdr returned, so callers do not change. Do not add a dependency to a dependency-free project without saying so in the pull request. Whatever you choose, preserve the two behaviours callers rely on: a falsy result for data that is not an image, and the same format names. Write a table-driven test with header bytes for each supported format, a JPEG that starts with an ICC profile segment, an HTML document and empty input. Run it on Python 3.12, comparing the new code with imghdr itself and listing every difference, and on 3.13. List the formats imghdr recognised that the replacement does not. Open a pull request.",
  "resources": [
    {
      "url": "https://github.com/your-org/your-app"
    }
  ]
}
  1. Get an API key. In the console, open Settings, then API keys, and create a key for your org. Send it in the Authorization header as a Bearer token.
  2. Send the request. POST the body in request.json to https://api.phoenix.so/o/{org}/sessions, with your repository as the resources URL. The run starts in its own cloud sandbox.
  3. Read what came back. Follow the run on its live stream or wait for the run.completed webhook, then read the result and its trajectory.

What comes back

A pull request that removes one import, adds one short function, changes one call and adds a test file. The description starts with the 3.13 traceback and the 3.12 deprecation warning, then explains the choice of a local check over a library in one paragraph, citing the empty install_requires.

It includes a comparison table from Python 3.12, one row per sample, with a column for what imghdr.what returned and a column for the new function. Every row matches except the ones the agent calls out, such as the ICC-profile JPEG that the old module rejected. It also lists the formats the old module knew and the new function does not, among them SGI, Sun raster, the PBM family, XBM and OpenEXR, so the reviewer can say if any of them matter.

The reviewer checks two things. First, that a download which returns an HTML page is still skipped, which the test covers with a sample document. Second, that accepting more JPEGs is wanted, since the script will now save files it used to drop. If the project would rather take a dependency, the description names the adjustments each library needs: mapping jpg back to jpeg for one, and stripping the dot and filtering non-image answers for the other.

Run it on every failed workflow run

A removed module fails on the first import, so the first CI job on a new Python is where most teams meet it. Add an automation on the repository's Project with the prompt above and a github trigger on workflow_run.failure. The failed run is added after the prompt as event text. The saved prompt is still the only instruction, so a failure with a different cause gets a short report and no pull request.

Fork pull requests and bot senders never fire the trigger, so outside contributions cannot start runs. Set the automation's max runs per hour low. One push that fails several workflows produces one event per workflow, and events past the cap wait as queued runs, which you can cancel once the first pull request is open.

The use case this job follows, with its automation and trigger: Fix a bug from an alert.

Why run it on Rush?

This is a fix where the replacement can be subtly wrong while every command exits cleanly. A library that calls a JPEG jpg, or that happily identifies a web page, makes the import error go away and changes what the program saves to disk. Seeing that requires running the old module and the candidate side by side on the same bytes, which means two interpreters, since the old module only exists on one of them. The agent sets both up in its sandbox and keeps the comparison in the session.

It also avoids a quiet cost. Adding a package to silence an import error is the fast move, and for a script people install with one pip command it adds a supply-chain entry for a few lines of logic. The agent has to state the trade and show the table. The person merging decides with the evidence in front of them, and the decision is recorded in the pull request for whoever asks later why there is a hand-written signature check in the code.

Frequently asked questions

What does Python recommend instead of imghdr?

The removal notes point to third-party libraries such as filetype, puremagic and python-magic. They detect far more formats than imghdr did, and each returns results in its own shape, so none is a drop-in replacement for code that compares the result with strings like jpeg.

Can I use Pillow for this?

If the project already depends on Pillow, yes: opening the bytes and reading the image's format gives a reliable answer and also proves the file parses. It is a heavy dependency to add only for format detection, and its names are upper case, so callers that expect png need a small mapping.

Why did imghdr reject some valid JPEG files?

Its JPEG test looked for the text JFIF or Exif at a fixed offset, or one particular four-byte start. A JPEG whose first segment is something else, such as an ICC colour profile, matched neither and returned None. Checking the three-byte start-of-image signature covers those files.

Is there a backport I can install to keep the import working?

Packages that republish removed standard-library modules exist, and installing one is a quick way to unblock an application. It keeps the old behaviour, including the JPEG gap, and ties you to a frozen copy of code the language has dropped. The agent mentions the option and prefers a replacement you can test.

More jobs like this: Fix a bug from an alert

Keep reading