【问题标题】:Python Error : Cannot import name 'Mapping' from 'collections'Python 错误:无法从 \'collections\' 导入名称 \'Mapping\'
【发布时间】:2022-12-20 07:59:28
【问题描述】:

当我尝试运行我的项目时,出现此错误。我在这里看到很多人遇到这个问题,我已经尝试了他们的代码,但没有用。我正在使用 Python 3.10.6。我应该在哪里修复才能解决它?

错误

ImportError: cannot import name 'Mapping' from 'collections' (/Users/User/.pyenv/versions/3.10.6/lib/python3.10/collections/__init__.py)

在里面.py

import _collections_abc
import sys as _sys

from itertools import chain as _chain
from itertools import repeat as _repeat
from itertools import starmap as _starmap
from keyword import iskeyword as _iskeyword
from operator import eq as _eq
from operator import itemgetter as _itemgetter
from reprlib import recursive_repr as _recursive_repr
from _weakref import proxy as _proxy

try:
    from _collections import deque
except ImportError:
    pass
else:
    _collections_abc.MutableSequence.register(deque)

try:
    from _collections import defaultdict
except ImportError:
    pass

【问题讨论】:

  • 你是说typing.Mapping吗?
  • 哪一行产生该错误?您提供的代码不会尝试导入,另外,为什么要对内置库使用“私有”模块?无论如何,错误是告诉你在collections 中没有Mapping 这样的东西,所以它不能导入它,你应该提供一个minimal reproducible example

标签: python collections python-3.10


【解决方案1】:

我无法在此代码中找到任何错误。此代码定义了一系列导入并尝试从 _collections 模块导入 deque 和 defaultdict 类。它使用 try-except 块来处理潜在的导入错误,并将 deque 类注册到 _collections_abc 模块中的 MutableSequence 类。但是,这段代码不包含任何函数或类定义或其他可执行代码,因此尚不清楚其预期目的是什么。

【讨论】:

    【解决方案2】:

    Python 3.3 中引入了映射类

    尝试升级到更新版本的 Python。

    【讨论】:

    • 他们的 Python 版本好像是 3.10.6
    猜你喜欢
    • 2022-08-21
    • 2022-08-14
    • 2022-08-14
    • 2022-08-04
    • 2022-11-10
    • 2014-01-29
    • 1970-01-01
    • 2020-09-04
    相关资源
    最近更新 更多