解决:ImportError: cannot import name ‘Sequence‘ from ‘collections‘
背景
在使用之前的代码时,报错:
File “G:\research\code\MicroDE_py\plot_bcic_iv_4_ecog_trial.py”, line 262, in
from skorch.helper import predefined_split
File “C:\Users\Lenovo.conda\envs\braindecode\lib\site-packages\skorch\helper.py”, line 6, in
from collections import Sequence
ImportError: cannot import name ‘Sequence’ from ‘collections’ (C:\Users\Lenovo.conda\envs\braindecode\lib\collections_init_.py)
报错问题
File "G:\research\code\MicroDE_py\plot_bcic_iv_4_ecog_trial.py", line 262, in <module>from skorch.helper import predefined_splitFile "C:\Users\Lenovo\.conda\envs\braindecode\lib\site-packages\skorch\helper.py", line 6, in <module>from collections import Sequence
ImportError: cannot import name 'Sequence' from 'collections' (C:\Users\Lenovo\.conda\envs\braindecode\lib\collections\__init__.py)
报错翻译
主要报错信息内容翻译如下所示:
from collections import Sequence
ImportError: cannot import name 'Sequence' from 'collections'
翻译:
从 collections 导入 Sequence
ImportError:无法从“collections”导入名称“Sequence”
报错原因
经过查阅资料,发现是版本兼容性问题。Python 更新后部分导入方式发生了改变,无法按照原方式导入包,Sequence 导入方式需要更改。
Sequence should be imported from collections.abc instead of collections since Python 3.3. A warning is printed starting with Python 3.7 and in Python 3.9 the new import location will be required.
This PR imports from collections.abc while still falling back to importing from collections for older Python versions.
翻译:
Sequence应该从Python 3.3 开始collections.abc而不是从collections开始导入。从 Python 3.7 开始打印警告,在 Python 3.9 中将需要新的导入位置。
小伙伴们按下面的解决方法即可解决!!!
解决方法
要解决这个错误,需要根据Python的版本进行不同的处理。
旧版本的正确的代码是:
from collections import Sequence
新版本的正确的代码是:
from collections.abc import Sequence