ImportError: cannot import name Mapping from collections after python 3.10 upgrade
Fixes ImportError: cannot import name Mapping from collections after upgrading to Python 3.10, which removed the ABC aliases from the collections module. Use it when migrated code imports Mapping, Sequence, or similar names from collections. Key trigger: the ImportError names an ABC imported from collections.
ImportError: cannot import name Mapping from collections after python 3.10 upgrade
TL;DR: The abstract-base-class aliases were removed from collections in Python 3.10 - they live in collections.abc now. Change the import to from collections.abc import Mapping. It is a one-line fix, then sweep for the other moved names so they do not bite you one at a time.
ImportError: cannot import name Mapping from collections after python 3.10 upgradeSteps
Find every bad import:
grep -rn "from collections import" --include="*.py" .Expected: a list of files importing Mapping (or Sequence, Iterable, and friends) fromcollections.Fix each one: rewrite as
from collections.abc import Mapping, keeping the rest of the import list unchanged. Expected: no remainingfrom collections importlines naming abstract base classes.Re-run the failing command. Expected: imports succeed with no ImportError.
Run the test suite - or at least import every module - to catch the same pattern in rarely-executed code. Expected: no further ImportErrors from other moved names.
Use this when
- The ImportError names Mapping, Sequence, MutableMapping, Iterable, Callable, or similar, imported from
collections. - The code just moved to Python 3.10 or newer.
- The same import worked on 3.9 (with a deprecation warning you may have missed).
Not for this skill when
- The unimportable name was never in
collections- check the spelling and the real home module. - You are on Python 3.9 or older - the aliases still work there.
- A third-party package has the same bug - upgrade the package instead of patching your code around it.
Variant phrasings
- collections Mapping deprecated import error python 3.10
- from collections.abc import Mapping fix
- python 3.10 abstract base classes moved
Why it happens
The ABC aliases in collections were deprecated since Python 3.3 and finally removed in 3.10. Their canonical home has been collections.abc for a decade - the upgrade just deleted the forwarding aliases.
Edge cases
- The same removal hits Sequence, MutableMapping, MutableSequence, Iterable, Iterator, Callable, and more - fix them all in one grep pass.
- Vendored or pinned old dependencies can carry the same import - upgrading them beats patching around them.
- If you must support old and new Pythons, a try/except fallback import (try
collections.abc, fall back tocollections) keeps one codebase working on both.
Provenance
Resolved from the public thread: https://vectle.com/posts/pst_D64wSfN-eXt-94X6YBGadw