# Fix "No module named 'pkg_resources'" by Migrating to importlib.resources

Yes. An agent replaces pkg_resources calls with importlib.resources and importlib.metadata, proves the package imports without setuptools, and opens a pull request.

[Run this on Rush](https://cloud.getrush.ai/run/migrate-pkg-resources-to-importlib-resources/setuptools/). Opens the console with this prompt ready to send, in a Project that has your repository.

## What the agent does

`ModuleNotFoundError: No module named 'pkg_resources'` has two causes, and the agent finds out which one applies. A virtual environment on Python 3.12 or later does not include setuptools, so the module was never installed. And setuptools itself dropped it: `pkg_resources` is present in setuptools 81.0.0 and absent from 82.0.0, so installing setuptools no longer brings it back. In a library like duo-labs/parliament, `parliament/__init__.py` runs `import pkg_resources` at import time and calls `pkg_resources.resource_filename` twice, for `iam_definition.json` and `config.yaml`. `setup.py` does not list setuptools in `install_requires`. The package worked only as long as some other tool happened to install an old enough setuptools beside it.

The agent reproduces each state in a clean environment. With no setuptools, `import parliament` fails on line 13. With the newest setuptools it fails the same way. With setuptools below 81 it imports, and prints the warning that announced all this: `pkg_resources is deprecated as an API`, with the advice to pin `Setuptools<81`. It runs the test suite in that last state to get a baseline before changing code. For parliament that is `pytest tests/unit`, the command in `tests/scripts/unit_tests.sh`, and it gives 65 passed and one failed. The failure, `test_expand_action_with_casing`, compares the number of matches for an IAM action and has nothing to do with resource loading, so the agent records it as existing before the change.

The replacement depends on what each call wanted. Both calls here ask for a file path only to open the file on the next line, so the agent replaces them with `importlib.resources.files(__name__).joinpath("config.yaml").read_text()` and parses the text directly. That also keeps working when the package is imported from a zip archive, which matters because `setup.py` sets `zip_safe=True`. Code that needs a real path on disk gets `importlib.resources.as_file` in a `with` block. Other `pkg_resources` uses map to other modules: `get_distribution(name).version` becomes `importlib.metadata.version(name)`, `iter_entry_points` becomes `importlib.metadata.entry_points`, and `parse_version` becomes `packaging.version.Version`, which adds `packaging` as a declared dependency.

Two side effects go in the report. The rewrite removes the module-level names `iam_definition_path` and `config_path`; the agent searches the repository for other uses, finds none, and says that code outside the repository could still read them. And `importlib.resources.files` exists from Python 3.9, while `setup.py` declares `python_requires=">=3.6"` and `.travis.yml` tests 3.7 and 3.8. On Python 3.8 the import of `files` fails. The agent raises `python_requires` to 3.9 and updates the classifiers, or, if the request says older versions must stay, uses the `importlib_resources` backport under a version check. It then uninstalls setuptools from the environment and runs the tests again: the same 65 pass and the same one fails.

## Start it with one API call

`POST https://api.phoenix.so/o/{org}/sessions`

```json
{
  "agent": "claude",
  "input": "This Python project fails with \"ModuleNotFoundError: No module named 'pkg_resources'\" or depends on pkg_resources and will. Remove the dependency on pkg_resources. Find every use in the code, in setup.py and in build or test scripts, including namespace package declarations, and list them by kind: resource_filename, resource_string, resource_stream, get_distribution, require, iter_entry_points, parse_version, working_set, declare_namespace. In clean virtual environments, show what happens on import with no setuptools, with the newest setuptools, and with the last setuptools release that still ships pkg_resources, and quote the errors and warnings. Run the test suite in the working state as a baseline and record any failures. Replace each use: importlib.resources.files with read_text or read_bytes where the code only reads the file, importlib.resources.as_file where it needs a path on disk, importlib.metadata for versions and entry points, packaging.version for version parsing (declare packaging as a dependency if you add it). If a replaced call defined a module-level name, search for other uses and say that the name is removed. Check the minimum Python version the project declares against what the replacements need; raise python_requires and classifiers to match and say so, unless that drops a version CI still tests, in which case use the importlib_resources or importlib_metadata backport under a version check and declare it. Then uninstall setuptools from the environment and run the import and the test suite again; compare with the baseline and report any test whose result changed. Build a wheel, install it into a clean environment with no setuptools, and confirm from outside the source tree that the package imports and finds its data files. List deprecated setup.py options you noticed, such as setup_requires and tests_require, without changing them. 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, for parliament, changes about a dozen lines of `parliament/__init__.py` and the `python_requires` and classifier lines of `setup.py`. The description has a small matrix of three environments by two versions of the code, showing import failing in two of three before and succeeding in all three after, and the test totals for the baseline and the final run side by side. The one failing test is named in both columns so nobody attributes it to this change.

A reviewer checks that the data files still ship: `package_data` in `setup.py` must keep listing `iam_definition.json` and `config.yaml`, because `importlib.resources` reads from the installed package and not from the source tree. Building a wheel and importing from it, in an environment with no setuptools, is the check that matters, and the agent's transcript includes it. They also decide whether dropping Python below 3.9 is acceptable, which is a policy question the description raises and does not settle for them.

## Run it on every failed workflow run that mentions pkg_resources

This failure arrives with no commit: a runner image or a build dependency moves to a newer setuptools and the next workflow run breaks. Create an automation in the Project that holds the repository, with this prompt and a `github` trigger on `workflow_run.failure`. Workflows fail for many reasons, so put a condition at the top of the saved prompt: read the failed run's log, and unless it contains `No module named 'pkg_resources'`, answer in one line that the failure has another cause and change nothing.

The trigger places the event after the prompt and fills in nothing else. It fires for runs caused by an owner, member or collaborator of the repository, not for runs from forks or from bot accounts. Keep the automation's max runs per hour at 1 or 2: every workflow run after the first fails the same way until the fix merges, and one pull request is enough.

## Why run it on Rush?

The bug is about what is installed, so it has to be tested where nothing extra is installed. A developer's environment nearly always has setuptools somewhere, which is why this error shows up in CI or on a user's machine first. The run builds clean virtual environments in its own sandbox, with no setuptools, with the newest, and with an old one, and the output of each import attempt is kept in the session transcript.

It also gives the baseline its due. A suite with one test already failing makes people distrust any change that touches import-time code. Running the tests before and after in controlled environments, and showing the same test failing for the same reason in both, lets the reviewer approve the migration on its own merits.

## Frequently asked questions

### Can I fix it by installing or pinning setuptools?

For now, with a pin below 82, since that release no longer ships `pkg_resources`. Add the pin to your install requirements, not only to a developer's machine. It is a stopgap: you are holding back a build tool for every user of your package to keep one import working, and the standard library replacements need no dependency at all.

### What replaces pkg_resources.resource_filename?

`importlib.resources.files(package).joinpath(name)`. If the code only reads the file, call `read_text()` or `read_bytes()` on the result. If it must hand a path to something else, wrap it in `importlib.resources.as_file(...)` as a context manager, which gives a real path even when the package lives inside a zip file.

### What replaces pkg_resources.get_distribution('x').version?

`importlib.metadata.version('x')`, available from Python 3.8. It raises `importlib.metadata.PackageNotFoundError` when the distribution is not installed, where the old call raised `pkg_resources.DistributionNotFound`, so update any `except` clause that names the old exception.

### Which Python version do the replacements need?

`importlib.metadata` arrived in Python 3.8 and `importlib.resources.files` in 3.9. For older interpreters the `importlib_metadata` and `importlib_resources` packages on PyPI provide the same functions. The agent compares these floors with the project's declared `python_requires` and reports the mismatch if there is one.

### A dependency of mine imports pkg_resources. What then?

Your own code can be clean and the import still fails inside a library. The agent reports which installed package triggers it, with the traceback, and checks whether a newer release of that package has dropped the import. If none has, the options are a setuptools pin recorded as temporary, or a different library.

## More setuptools jobs

- [Fix "SetuptoolsDeprecationWarning: License classifiers are deprecated" and "project.license as a TOML table is deprecated"](https://getrush.ai/run/fix-license-classifiers-are-deprecated/setuptools/)
- [Fix "ModuleNotFoundError: No module named 'pkg_resources'" after a setuptools upgrade](https://getrush.ai/run/fix-no-module-named-pkg-resources/setuptools/)
- [Fix "Support for the test command was removed in Setuptools 72"](https://getrush.ai/run/fix-setup-py-test-command-removed/setuptools/)

## More jobs like this: Upgrade dependencies weekly

- [Migrate a Flask App From psycopg2 to Psycopg 3](https://getrush.ai/run/migrate-psycopg2-to-psycopg3/psycopg2/)
- [Migrate From PyPDF2 to pypdf and Fix "PdfFileReader is deprecated and was removed"](https://getrush.ai/run/migrate-pypdf2-to-pypdf/pypdf2/)
- [Migrate From python-jose to PyJWT in a FastAPI App](https://getrush.ai/run/migrate-python-jose-to-pyjwt/python-jose/)

## Keep reading

- [How a Rush run works on your repository, from request to pull request](https://getrush.ai/cloud/)
- [Compare cloud agents, agent sandboxes and AI code review](https://getrush.ai/compare/)
- [Rush pricing: Free, Pro and Max](https://getrush.ai/pricing/)
