Search code examples
pythongdal

ImportError: cannot import name '_gdal_array' from 'osgeo'


I create a fresh environment, install numpy, then install GDAL. GDAL imports successfully and I can open images using gdal.Open(, but I get the ImportError: cannot import name '_gdal_array' from 'osgeo' error when trying to use ReadAsRaster.

pip list returns:

GDAL       3.6.2
numpy      1.24.2
pip        23.0
setuptools 65.6.3
wheel      0.38.4

Completely stumped, has anyone come across this? Google tells me that installing numpy first is the solution (but that doesn't help). Help would be much appreciated.


Solution

  • Pip is most likely caching and reinstalling your bad version of GDAL over and over, even though you installed numpy. Here's what fixed it for me:

    pip3 install --no-cache-dir --force-reinstall 'GDAL[numpy]==3.6.2'

    Installing without --no-cache-dir causes pip to reuse the compiled wheel:

    % pip3 install --force-reinstall 'GDAL[numpy]==3.6.2'
    Collecting GDAL[numpy]==3.6.2
      Using cached GDAL-3.6.2-cp311-cp311-macosx_13_0_x86_64.whl
    Collecting numpy>1.0.0
      Using cached numpy-1.24.2-cp311-cp311-macosx_10_9_x86_64.whl (19.8 MB)
    Installing collected packages: numpy, GDAL
      Attempting uninstall: numpy
        Found existing installation: numpy 1.24.2
        Uninstalling numpy-1.24.2:
          Successfully uninstalled numpy-1.24.2
      Attempting uninstall: GDAL
        Found existing installation: GDAL 3.6.2
        Uninstalling GDAL-3.6.2:
          Successfully uninstalled GDAL-3.6.2
    Successfully installed GDAL-3.6.2 numpy-1.24.2
    

    For others still encountering this issue, make sure wheel and setuptools are installed. Pip will think setuptools>=48 is enough, but it's wrong, as you'll need at least setuptools 67.`

    Pip will download wheel and/or setuptools as part of the building process, but it will not work (as of March 2024) and instead blame numpy:

    Building wheels for collected packages: GDAL
      Running command Building wheel for GDAL (pyproject.toml)
      WARNING: numpy not available!  Array support will not be enabled
    

    The only indication that it's a wheel or setuptools problem shows up when building without build isolation (--no-build-isolation):

      error: invalid command 'bdist_wheel'
      error: subprocess-exited-with-error
      
      × Preparing metadata (pyproject.toml) did not run successfully.
      │ exit code: 1
      ╰─> See above for output.
    
    Preparing metadata (pyproject.toml) ... done
    ERROR: Exception:
    Traceback (most recent call last):
    ...
    ModuleNotFoundError: No module named 'setuptools'
    

    To fix these errors, make sure wheel and setuptools are installed with pip3 install wheel 'setuptools>=67'