Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

in VS Code ImportError: cannot import name 'Mapping' from 'collections'

I am trying to connect to Postgress and create a folder test.db via Flask. When I run "python3" in the terminal and from there when I run "from app import db" I get an import error:

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

I have tried all the troubleshooting but none of them worked. Please advise. Here is the full stack: full stack error

like image 436
Mitra Avatar asked Sep 29 '21 17:09

Mitra


Video Answer


4 Answers

As Mitra said above, change:

from collections import Mapping

to

from collections.abc import Mapping
like image 91
Geremia Avatar answered Nov 15 '22 08:11

Geremia


As stated by others, this is caused by a change in the collections interface starting with Python 3.10. As far as I can see there are three options to mitigate this issue so far:

  • Revert to Python 3.9.

  • If the error occurs in a third-party library, try to update this library first (pip install <package> --upgrade).

  • Patch the code manually.

    For patching the ImportError, see https://stackoverflow.com/a/69727802/13994294.

like image 22
Christoph Thiede Avatar answered Nov 15 '22 09:11

Christoph Thiede


As rightly pointed out, you need to import from the new abc module inside of collections for later versions of Python.

If you need to make your code backwards compatible with older versions of Python, you can use this:

try:
    from collections.abc import Mapping
except ImportError:
    from collections import Mapping
like image 20
Chris Redford Avatar answered Nov 15 '22 07:11

Chris Redford


Use older version of python (eg 3.8)

like image 31
Pavel Glac Avatar answered Nov 15 '22 08:11

Pavel Glac