我正在尝试运行使用各种依赖项的程序,但自从升级到 Python 3.10 后,这不再起作用。 当我在终端中运行“python3”并从那里导入我的依赖项时,出现错误:
ImportError: cannot import name 'Mapping' from 'collections' (/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/collections/__init__.py)
这似乎是一个普遍问题,但这是我的具体案例的回溯:
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)
改变:
from collections import Mapping
到
from collections.abc import Mapping
这是由 Python 3.10 开始的
collections
接口的更改引起的。据我所知,到目前为止有三种选择可以缓解这个问题:
如果错误发生在第三方库中,请先尝试更新此库(
pip install <package> --upgrade
)。
恢复到Python 3.9。
手动修补代码。
有关修补
ImportError
,请参阅 https://stackoverflow.com/a/69727802/13994294。
对于更高版本的 Python,您需要从
abc
内部的新 collections
模块导入。
如果你需要使你的代码向后兼容旧版本的Python,你可以使用这个:
try:
from collections.abc import Mapping
except ImportError:
from collections import Mapping
如果您尝试在 Python 3.9.x 中导入,就会清楚:
Python 3.9.10 (main, Jan 15 2022, 11:40:53)
[Clang 13.0.0 (clang-1300.0.29.3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> from collections import Mapping
<stdin>:1: DeprecationWarning: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated since Python 3.3, and in 3.10 it will stop working
它明确提到在3.10中它将停止工作。因此使用时请将版本更改为Python 3.9或以下。 如果您使用 pipenv 来管理您的虚拟环境,那么步骤可能如下:
$ pipenv --rm # to remove the virtual env
$ exit # to exit the virtual env
$ vim Pipfile # here change the version to '3.9' by replacing '3.10'
$ pipenv shell # this will create a virtual env with 3.9
$ pipenv install # to install the requirements
我们刚刚从 Python 3.10 切换到 Python 3.9,目前支持该代码。
使用旧版本的python(例如3.8)
我添加了
from collections.abc import Mapping
from collections.abc import MutableMapping
from collections.abc import Sequence
在
“C:\用户 atha\AppData\Local\Programs\Python\Python311\Li