ImportError: missing libgfortran.5.dylib on macOS
Install GCC runtime libraries via Homebrew (brew install gcc) or reinstall NumPy from pre-built binary wheels using pip install --force-reinstall numpy.
Root Cause Analysis
This error occurs when Python tries to load NumPy or SciPy C/Fortran shared libraries on macOS, but the dynamic linker (dyld) cannot find the libgfortran.5.dylib shared library in the system library search paths.
1. Missing Fortran Runtime Libraries on macOS
Unlike Linux distributions that often include GNU Fortran runtime libraries by default, macOS does not ship with libgfortran. When packages compiled against GCC/gfortran run on a clean macOS installation, dynamic loading fails.
2. Architecture Mismatches (Intel x86_64 vs Apple Silicon arm64)
On Apple Silicon (M1/M2/M3/M4) Macs, running Python under Rosetta 2 (x86_64) while Homebrew libraries are installed in /opt/homebrew (arm64) causes the linker to reject the library due to architecture mismatch.
3. Manually Compiled Source Wheels
Installing NumPy from source without vendored dynamic libraries prevents delocate from bundling libgfortran into the wheel.
4. Broken Conda or Homebrew Environment Paths
Missing or corrupted DYLD_LIBRARY_PATH variables can prevent Python from discovering libraries installed in non-standard prefixes.
Reproduction Code (MCVE)
# **Note de reproductibilité :** Spécifique à macOS et aux environnements sans toolchain Fortran.
raise ImportError('dlopen(/usr/local/lib/python3.12/site-packages/numpy/core/_multiarray_umath.cpython-312-darwin.so, 0x0002): Library not loaded: @rpath/libgfortran.5.dylib')
Solution 1: Install Fortran Toolchain via Homebrew
Install GCC which provides libgfortran.5.dylib in standard Homebrew library search locations.
import sys
print(f'Platform: {sys.platform}')
print('Execute in terminal:')
print('brew install gcc')
print('# Or install OpenBLAS:')
print('brew install openblas')
Solution 2: Force Reinstall Official Pre-Compiled Wheel
Official PyPI binary wheels for macOS bundle their own vendored dynamic libraries and do not require external compiler runtimes.
import sys
print('Reinstall NumPy with pre-bundled shared libraries:')
print('pip install --force-reinstall --no-cache-dir numpy')
A common pitfall is setting DYLD_LIBRARY_PATH globally in ~/.zshrc. On macOS, System Integrity Protection (SIP) strips DYLD_LIBRARY_PATH from sub-processes, rendering global environment variables ineffective. Always rely on official wheels or Homebrew package links. Edge cases occur when mixing conda environments and system Python: always activate the appropriate conda environment before running scripts. Contrast this error with ImportError: DLL load failed on Windows, which is the equivalent dynamic linker failure for Windows DLLs.