# Fix "ImportError: cannot import name 'Mapping' from 'collections'"

Yes. An agent moves the abstract base class imports to collections.abc, checks the oldest Python you support still passes, and opens a PR with both test runs.

[Run this on Rush](https://cloud.getrush.ai/run/fix-collections-abc-import-error/python/). Opens the console with this prompt ready to send, in a Project that has your repository.

## What the agent does

The agent first finds every import of an abstract base class from the top-level `collections` module, since the error names only the first one Python reached. In a small library like Gr1N/pyfrozen there are two: `pyfrozen/frozendict.py` opens with `from collections import Mapping, MutableMapping`, and `pyfrozen/frozenlist.py` with `from collections import MutableSequence`. `FrozenDict` subclasses `MutableMapping` and uses `Mapping` in an `isinstance` check further down; `FrozenList` subclasses `MutableSequence`. Both files fail at import on Python 3.10 and later, so pytest reports two collection errors and runs none of the tests.

It then reads what the project claims to support, because that decides how the fix is written. `pyproject.toml` has `python = "^3.6"` under `[tool.poetry.dependencies]`, `tox.ini` lists `py36` and `py37` test environments, and `.travis.yml` runs the same two interpreters. `collections.abc` has existed for every version in that range, so the fix is a plain change of module in two import lines. No `try` and `except ImportError` fallback is needed, and the agent does not add one.

Next comes proof on both sides of the removal. On an interpreter older than 3.10 the original code still imports and the suite passes, with a `DeprecationWarning` that states the history in one line: importing the ABCs from `collections` is deprecated since Python 3.3 and stops working in 3.10. On a newer interpreter the suite cannot be collected. After the change, the agent runs `tests/test_frozendict.py` and `tests/test_frozenlist.py` on the newest Python in the sandbox and on the oldest one it can install that the project still claims, with warnings turned into errors on the new run so a second deprecated import cannot hide.

It also searches for the lookalikes that the title does not cover: `collections.Callable`, `collections.Iterable`, `collections.Hashable` and attribute access such as `collections.Mapping` after a bare `import collections`. Those raise `AttributeError` at the line that uses them, later than an import error would, so a grep is the reliable way to find them. Finally it updates what advertises support: the tox `envlist`, the CI matrix and, when the project keeps one, a changelog line.

## Start it with one API call

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

```json
{
  "agent": "claude",
  "input": "This project fails on Python 3.10 and later with: ImportError: cannot import name 'Mapping' from 'collections'. Fix it. Read the traceback first and say whether the failing import is in this repository or in an installed dependency; for a dependency, do not edit it, report the package, its installed version and the first release that imports from collections.abc, and propose the upgrade. In this repository, find every import of an abstract base class from the top-level collections module (Mapping, MutableMapping, Sequence, MutableSequence, Set, MutableSet, Iterable, Iterator, Callable, Hashable, Sized, Container and the rest), and every attribute access such as collections.Mapping after import collections. Read the supported Python range from the packaging metadata, tox or nox configuration and CI matrix, and state it. Because collections.abc exists on every Python 3 version in that range, change the imports to collections.abc directly and add no try/except fallback. Run the test suite before the change on the oldest supported Python you can install, with warnings shown, and quote the deprecation warning. Run it after the change on that Python and on the newest available Python, with -W error on the newest, and quote both summaries. Add the newest Python to the test matrix and tox envlist if it is missing, and leave old entries alone. Add a changelog entry if the project has a changelog. 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 whose code change is two import lines in pyfrozen's case, one per module, plus the matrix and changelog edits. The description has three test summaries in order: the old code on an old interpreter with the deprecation warning quoted, the old code on a new interpreter with the collection errors, and the new code on both. That ordering lets a reviewer confirm the warning was the same defect announced years earlier, and that nothing else changed between red and green.

A reviewer checks that the names are unchanged. The classes still subclass `MutableMapping` and `MutableSequence` and the `isinstance` check still tests against `Mapping`, now from the right module. They also check that the pull request did not widen its scope. In this repository the Poetry section uses the older `dev-dependencies` table, `[tool.black]` still sets `py36 = true`, and CI is a `.travis.yml` with no entry newer than 3.7. The agent lists those in the description and leaves them for separate work.

When the traceback ends in an installed package, no code in your repository changes. The result is then a dependency bump with the test run, or a report that no fixed release exists and which pin of that package or of Python keeps the build working in the meantime.

## Run it on every failed CI run on a new Python version

This error usually arrives the day someone adds a newer Python to the test matrix, or the day the CI image's default Python moves. An automation in the repository's Project with a `github` trigger on `workflow_run.failure` or `check_suite.failure` starts a run when CI fails, and the failure event is placed after the saved prompt as third-party data. Write the prompt so the agent reads the failing job's log first and stops with a short note when the failure is something other than a `collections` import, since the trigger fires for every failed run and fills in nothing in the prompt.

The trigger fires only for work by an owner, member or collaborator of the repository; CI runs from forks never start one. The automation's max runs per hour bounds how many start during a bad afternoon, and events past it wait for room in the hour.

## Why run it on Rush?

The edit is small enough to make from memory. What takes time is having two interpreters on either side of 3.10 and running the same suite on both, and most laptops have one Python that happens to be new enough to fail or old enough to pass. The run installs the interpreters it needs in its own sandbox, executes the suite on each, and keeps the commands and their output in the transcript, so the claim that the oldest supported version still passes comes with the run that showed it.

The same message is also produced by old dependencies, where the right answer is an upgrade and the wrong answer is a patch under `site-packages` that the next install erases. A run that reads the traceback and the installed versions before it edits anything can tell the two cases apart, and when many repositories fail the same way after an image update, each gets its own run and its own pull request at once.

## Frequently asked questions

### Which names moved to collections.abc?

The abstract base classes: `Mapping`, `MutableMapping`, `Sequence`, `MutableSequence`, `Set`, `MutableSet`, `Iterable`, `Iterator`, `Callable`, `Hashable`, `Sized`, `Container` and their relatives. The concrete containers stay where they were, so `OrderedDict`, `defaultdict`, `deque`, `Counter` and `namedtuple` are still imported from `collections`.

### Do I need a try/except import for old Python versions?

Only when the code still has to run on Python 2, which has no `collections.abc`. Python's own deprecation warning dates the move to 3.3, so any project whose floor is a Python 3 version can import from `collections.abc` unconditionally. The agent reads the declared floor before deciding and says which case applied.

### Why did this work for years and then stop?

The old import path kept working as an alias and printed a `DeprecationWarning`, which Python does not show by default for code inside imported modules. Python 3.10 removed the alias. Projects that never ran their tests with warnings visible saw nothing until the import failed outright.

### The error is inside a package I installed. Can the agent still help?

Yes, by changing versions instead of code. It identifies the package from the traceback, finds the first release that uses `collections.abc`, bumps the requirement and runs your tests against it. When the package is abandoned it reports that, along with the maintained fork or replacement it found, and leaves the choice to you.

## More Python jobs

- [Fix a Failing CI Build in a Python Project](https://getrush.ai/run/fix-failing-ci/python/)
- [Fix "RuntimeError: generator raised StopIteration" in Python 3.7 and Later](https://getrush.ai/run/fix-generator-raised-stopiteration/python/)
- [Fix "SyntaxWarning: invalid escape sequence" on Python 3.12](https://getrush.ai/run/fix-invalid-escape-sequence-syntax-warning/python/)

## More jobs like this: Fix a bug from an alert

- [Fix "ArgumentError: Column expression, FROM clause, or other columns clause element expected" on SQLAlchemy 2](https://getrush.ai/run/fix-column-expression-or-from-clause-expected/sqlalchemy/)
- [Fix "Compatibility with CMake < 3.5 Has Been Removed from CMake" After a CMake 4 Upgrade](https://getrush.ai/run/fix-compatibility-with-cmake-3-5-has-been-removed/cmake/)
- [Fix "the attribute `version` is obsolete" in a Docker Compose File](https://getrush.ai/run/fix-compose-version-obsolete-warning/docker-compose/)

## 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/)
