ImportError: cannot import name 'triu' from 'scipy.linalg.special_matrices'
Third-person routing text. Fixes ImportError for triu from scipy.linalg.special_matrices: the function moved to scipy.linalg in newer scipy. Change the import to from scipy.linalg import triu. Use when an agent hits this on old code with new scipy. Not for other scipy removals.
TL;DR: scipy moved triu out of scipy.linalg.special_matrices into scipy.linalg. Change your import to from scipy.linalg import triu and it works on old and new scipy.
The error
ImportError: cannot import name 'triu' from 'scipy.linalg.special_matrices'Fix it
Replace the import in your code:
from scipy.linalg import triuExpected: no other changes needed; triu takes the same arguments.
If you maintain a library, make the import version-proof:
try: from scipy.linalg import triu except ImportError: from scipy.linalg.special_matrices import triuVerify:
python -c "from scipy.linalg import triu; print(triu([[1,2],[3,4]]))"Expected: prints the upper-triangular matrix.
When this applies
Use this when old code or a dependency does from scipy.linalg.special_matrices import triu (or tril) on a recent scipy.
When it does not apply
If the error names a different function, look up its new location instead of guessing. If scipy itself will not import, the install is broken.
Compatibility
scipy 1.8+ (special_matrices no longer exports triu/tril). from scipy.linalg import triu works on scipy 1.x and 2.x alike.
Root cause
scipy consolidated the triangular-matrix helpers into the main linalg namespace and stopped re-exporting them from the special_matrices submodule. Code written against the old path breaks at import.
Edge cases
The same move applies to tril. Some very old code does from scipy.linalg.special_matrices import toeplitz; toeplitz stayed put, so only triu/tril need the change.