Ubuntu环境下Jupyter Notebook导入PennyLane报错ImportError: cannot import name 'shape'的问题求助
Let’s dig into why you’re hitting this ImportError: cannot import name 'shape' error with PennyLane, and walk through actionable fixes that should resolve it—since the steps you’ve tried (updating Jupyter, installing v0.25) haven’t done the trick yet.
First, let’s rule out the most common culprits:
- Mismatched Python environments: It’s super common to install packages in one Python environment, but have Jupyter running a different one. If your system Python has PennyLane but Jupyter is using a virtual environment or conda env without it (or with a broken install), you’ll get this error.
- Dependency version conflicts: PennyLane 0.25 relies on specific versions of libraries like NumPy. If your NumPy is too new or too old, it can break the
shapeimport that PennyLane relies on. - Corrupted/cached installation: Sometimes pip’s cache holds onto broken or incomplete package files, leading to wonky installs even when you specify a version.
Step 1: Make sure Jupyter is using the right Python environment
First, confirm which Python Jupyter is using. Open your Jupyter Notebook and run this:
import sys print(sys.executable)
Now open your Ubuntu terminal and run:
which python3
If the paths don’t match, Jupyter is using a different environment than the one where you installed PennyLane. Fix this by:
- Activating the environment where you installed PennyLane (if you’re using virtualenv/venv)
- Installing the Jupyter kernel for that environment:
pip install ipykernel python -m ipykernel install --user --name=my-pennylane-env - Restart Jupyter, then select the new
my-pennylane-envkernel from the dropdown menu.
Step 2: Fix NumPy version compatibility
PennyLane 0.25 works best with NumPy versions between 1.19.0 and 1.23.x. Newer NumPy versions (1.24+) removed some deprecated functions that PennyLane 0.25 still uses. Let’s fix this:
- Uninstall the current broken setup:
pip uninstall -y pennylane numpy - Install compatible versions:
pip install numpy==1.23.5 pennylane==0.25
Step 3: Clear pip cache and do a fresh install
If the above doesn’t work, pip’s cache might be holding onto corrupted files. Clear it and reinstall:
pip cache purge pip install pennylane==0.25 --no-cache-dir
Step 4: Check for conflicting packages
Other libraries like old versions of SciPy or TensorFlow can interfere with NumPy’s imports. List your key dependencies:
pip list | grep -E "numpy|scipy|tensorflow|torch"
If you see SciPy < 1.7.0, update it to a compatible version:
pip install -U scipy==1.9.3
Once you’ve tried these steps, go back to Jupyter and run import pennylane as cents (quick note: most folks use pl as the alias, but whatever works for you!). This should resolve the import error.
内容的提问来源于stack exchange,提问作者MeltedStatementRecognizing

