pythonimporterrorpython-3.11python-collections

Import error with named tuple and Mapping


I have trying to fix an import error with the requests library in Python 3.11. This is to run a Discord bot that I have created. My original error is given as ImportError: cannot import name 'Mapping' from 'collections' and in response I have tried changing a line from from collections import namedtuple, Mapping to from collections.abc import namedtuple, Mapping. This has not fixed my original error. The new error created is the traceback given below:

Traceback (most recent call last):
  File "E:\python projects\newer Vorpal\main.py", line 4, in <module>
from game import game, shopping
  File "E:\python projects\newer Vorpal\game.py", line 10, in <module>
from monsters import createmonsters
  File "E:\python projects\newer Vorpal\monsters.py", line 2, in <module>
import requests
  File "C:\Users\andreas\AppData\Local\Programs\Python\Python311\Lib\site-packages\requests\__init__.py", line 43, in <module>
import urllib3
  File "C:\Users\andreas\AppData\Local\Programs\Python\Python311\Lib\site-packages\urllib3\__init__.py", line 8, in <module>
from .connectionpool import (
  File "C:\Users\andreas\AppData\Local\Programs\Python\Python311\Lib\site-packages\urllib3\connectionpool.py", line 29, in <module>
from .connection import (
  File "C:\Users\andreas\AppData\Local\Programs\Python\Python311\Lib\site-packages\urllib3\connection.py", line 39, in <module>
from .util.ssl_ import (
  File "C:\Users\andreas\AppData\Local\Programs\Python\Python311\Lib\site-packages\urllib3\util\__init__.py", line 3, in <module>
from .connection import is_connection_dropped
  File "C:\Users\andreas\AppData\Local\Programs\Python\Python311\Lib\site-packages\urllib3\util\connection.py", line 3, in <module>
from .wait import wait_for_read
  File "C:\Users\andreas\AppData\Local\Programs\Python\Python311\Lib\site-packages\urllib3\util\wait.py", line 1, in <module>
from .selectors import (
  File "C:\Users\andreas\AppData\Local\Programs\Python\Python311\Lib\site-packages\urllib3\util\selectors.py", line 14, in <module>
from collections.abc import namedtuple, Mapping

ImportError: cannot import name 'namedtuple' from 'collections.abc' (C:\Users\andreas\AppData\Local\Programs\Python\Python311\Lib\collections\abc.py)

Solution

  • namedtuple is located in the collections module, Mapping -- in the collections.abc module. Starting from python 3.10 the line from collections import Mapping throws an error. You should separate the two imports, like so:

    from collections.abc import Mapping
    from collections import namedtuple