Skip to content

Move shapely to an optional [vector] extra so it isn't loaded on import #2496

@brendancol

Description

@brendancol

Reason or Problem

shapely is in install_requires, so a plain pip install xarray-spatial
installs it (a compiled package built on GEOS) and loads it on every
import xrspatial. But most of the library never touches shapely. It is only
used by the vector-to-raster paths: rasterize and polygonize. Users who run
terrain, focal, hydrology, or multispectral functions still pay for shapely on
import.

The eager load happens because xrspatial/rasterize.py imports shapely at
module top level (line 19) and xrspatial/__init__.py imports rasterize and
polygonize at top level. polygonize already imports shapely lazily inside
its functions; rasterize is the one module pulling it in at import time.

Proposal

Move shapely out of install_requires into an optional vector extra, and make
rasterize.py import it lazily. Then import xrspatial no longer loads shapely,
and pip install xarray-spatial[vector] enables the rasterize/polygonize paths.

Design:

  • Remove shapely>=2.0 from [options] install_requires in setup.cfg.
  • Add a vector = shapely>=2.0 entry under [options.extras_require].
  • Replace the top-level import shapely in rasterize.py with a
    _require_shapely() helper that returns the module or raises a clear
    ImportError pointing at pip install xarray-spatial[vector]. Call it at the
    entry points that use shapely.
  • Keep shapely in the tests extra so CI still exercises rasterize/polygonize.

Usage: pip install xarray-spatial for everything except the vector paths;
pip install xarray-spatial[vector] to use rasterize and polygonize.

Value: shapely (and GEOS) no longer load on import xrspatial, and they drop
off the default install for users who don't rasterize vector geometry.

Drawbacks

This changes behavior. Code that relied on shapely arriving with xarray-spatial
will need the [vector] extra. rasterize and polygonize raise a clear error
instead of working out of the box.

Alternatives

Keep shapely required. Rejected for the same reason as the matplotlib change
(#2494): it forces a compiled dependency on users who never call the paths that
need it.

This follows the pattern set by #2494 (matplotlib moved to a plot extra).
urllib3 is intentionally left as a hard dependency of the geotiff module and is
out of scope here.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions