使用Pip安装numpy等库时出现AttributeError的原因与解决方法
Hey there, let's break down this issue and get those libraries installed smoothly.
This error pops up for two key reasons tied to your environment setup:
- Python 3.9's module restructuring: Starting with Python 3.9, abstract base classes like
Iterablewere moved from the top-levelcollectionsmodule tocollections.abc. Your outdated Pip version (19.3.1) and potentially the older versions of the libraries you're trying to install still referencecollections.Iterable, which no longer exists in that location—hence theAttributeError. - Unstable Python alpha version: You're using Python 3.9.0a2, which is an early pre-release alpha build. These preview versions often lack full compatibility with third-party libraries, since most package maintainers wait for the official stable release to update their code for new Python versions.
Here are the step-by-step fixes, ordered by recommendation:
Upgrade Pip to a Python 3.9-compatible version
First, you need to update Pip itself, as the 19.3.1 version doesn't support Python 3.9's module changes. Open Command Prompt and run:python -m pip install --upgrade pipIf this fails (sometimes old Pip can't handle upgrading itself), use the official get-pip.py script: download it, then run:
python get-pip.pySwitch to a stable Python 3.9 release
Ditch the alpha version (3.9.0a2) for a stable, fully supported release of Python 3.9.x (like 3.9.13, the latest patch for 3.9). Stable versions have far better compatibility with third-party libraries, as maintainers have had time to adapt their code.Install library versions compatible with Python 3.9
After upgrading Pip, try installing the libraries again—Pip will automatically fetch versions that work with your Python setup:pip install numpy cython cymemIf you still run into issues, specify minimum compatible versions explicitly:
pip install numpy>=1.19.0 cython>=0.29.21 cymem>=2.0.3These versions are confirmed to support Python 3.9.
Temporary hack (only if other options fail)
As a last resort, you can add a compatibility alias to thecollectionsmodule. Navigate to your Python installation'sLib/collections/__init__.pyfile, and add this at the end:from collections.abc import Iterable, Iterator, Sequence, Mapping, MutableMapping, MutableSequence __all__ += ['Iterable', 'Iterator', 'Sequence', 'Mapping', 'MutableMapping', 'MutableSequence']Note: This is a quick fix and might cause unexpected issues later, so only use it if you can't upgrade Pip or Python right now.
内容的提问来源于stack exchange,提问作者Saugat Timilsina

