Search code examples
pythonimporterrorpython-3.10python-collections

ImportError: cannot import name '...' from 'collections' using Python 3.10


I am trying to run my program which uses various dependencies, but since upgrading to Python 3.10 this does not work anymore. When I run "python3" in the terminal and from there import my dependencies I get an error:

ImportError: cannot import name 'Mapping' from 'collections' (/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/collections/__init__.py)

This seems to be a general problem, but here is the traceback of my specific case:

Traceback (most recent call last):
 File "/Users/mk/Flasktut/app.py", line 2, in <module>
  from flask import Flask, render_template
 File "/Users/mk/Flasktut/env/lib/python3.10/site-packages/flask/__init__.py", line 14, in <module>
  from jinja2 import escape
 File "/Users/mk/Flasktut/env/lib/python3.10/site-packages/jinja2/__init__.py", line 33, in <module>
  from jinja2.environment import Environment, Template
 File "/Users/mk/Flasktut/env/lib/python3.10/site-packages/jinja2/environment.py", line 16, in <module>
  from jinja2.defaults import BLOCK_START_STRING, \
 File "/Users/mk/Flasktut/env/lib/python3.10/site-packages/jinja2/defaults.py", line 32, in <module>
  from jinja2.tests import TESTS as DEFAULT_TESTS
 File "/Users/mk/Flasktut/env/lib/python3.10/site-packages/jinja2/tests.py", line 13, in <module>
  from collections import Mapping
ImportError: cannot import name 'Mapping' from 'collections' (/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/collections/__init__.py)

Solution

  • Change:

    from collections import Mapping
    

    to

    from collections.abc import Mapping