Skip to content

perf: import optional dependencies lazily - #2762

Draft
ashwanijha04 wants to merge 3 commits into
scverse:mainfrom
ashwanijha04:lazy-optional-imports
Draft

ashwanijha04 wants to merge 3 commits into
scverse:mainfrom
ashwanijha04:lazy-optional-imports

Conversation

@ashwanijha04

@ashwanijha04 ashwanijha04 commented Nov 25, 2026 •

Copy link
Copy Markdown

What

import anndata no longer imports dask, xarray, awkward or zappy. They are imported the first time they are actually needed.

The classes in anndata.compat (DaskArray, XDataset, XDataArray, XVariable, AwkArray, …) are now lazy stand-ins (anndata/compat/_lazy.py). A stand-in behaves like its real class in:

  • isinstance / issubclass / match. These never trigger an import. Until the dependency's module is in sys.modules, the answer is "no", which is always correct because no instance can exist yet.

  • Calls, attribute access (XDataset.from_dataframe) and class Sub(DaskArray) statements. These import the dependency.

  • singledispatch. anndata's internal dispatchers use a thin wrapper, anndata.compat.singledispatch. It registers the real class as soon as its module is imported, so dispatch resolves exactly as it did with eager imports.

    I first tried registering the stand-in as a virtual ABC, as suggested in the issue thread. That breaks dispatch because a virtual base loses to real ABC bases: xarray.Dataset is a real Mapping, so it was dispatched to the Mapping handler. A regression test covers this.

  • Type-keyed lookups. The IO registry (register_write, get_write, has_write, get_spec) and writeable_elems go through canonical_type(), which maps a real class to its stand-in. Writers registered for either the real class or the stand-in are therefore found.

DaskArrayView and AwkwardArrayView are built on first use. anndata.experimental.backed loads its xarray-backed array classes on first attribute access.

cupy is left eager. Importing it registers dask chunk types as a side effect, and it only affects GPU installs. zarr is still imported eagerly (~60 ms), which could be a follow-up.

Why

On a machine with dask, xarray and awkward installed, python -c "import anndata" (median of 10 runs):

main this PR
import anndata 494 ms 315 ms (−36 %)
optional deps imported dask, xarray, awkward none
end-to-end dask workflow (build dask AnnData → subset → copy → write zarr → read_lazy) 550 ms 529 ms

The last row checks that the cost is not just moved to first use.

Compatibility

  • type(x) is anndata.compat.DaskArray, and other exact-type checks against a stand-in, are now False, because the stand-in is not the real class. Use isinstance, or canonical_type(type(x)) is DaskArray. The one test in this repo that did this is updated.
    • On GitHub, I only found this pattern in copies of anndata's own test suite.
    • anndata.compat is private API.
  • Downstream code using plain functools.singledispatch with anndata.compat types keeps working: it gets the virtual-base behaviour.
  • Downstream IO registrations (e.g. _REGISTRY.register_write(zarr.Group, DaskArrayView, …)) keep working, whether made with the stand-in or the real class.

Testing

  • tests/test_lazy_imports.py:
    • A subprocess test asserts that import anndata, anndata.experimental loads none of the optional dependencies.
    • Unit tests cover the stand-in semantics, singledispatch before and after import (including the Mapping priority case), register_write with a real class, and subclassing a stand-in.
    • Each test was checked to fail when the behaviour it guards is reverted.
  • Full anndata suite: 8041 passed, 0 failed (main: 8033 passed; the difference is the new tests).
  • scanpy 1.13.0's test suite (excluding plotting) against this branch: 3422 passed. The 5 failures also fail against main in the same environment: 4 need scikit-misc, which isn't installed, and 1 is a local image comparison.
  • mypy (hatch run hatch-check-types:check configuration, Python 3.14) and ruff: clean.

🤖 Generated with Claude Code

ashwanijha04 and others added 3 commits November 25, 2026 15:10
`import anndata` imported dask, xarray and awkward whenever they were
installed, to register their classes with `singledispatch` and the IO
registry. That cost ~180ms, more than a third of the import time.

anndata.compat now exposes stand-ins (`LazyType`) for those classes that
answer `isinstance`/`issubclass` without importing anything: an object
can only be an instance of a class whose module was imported. A
`singledispatch` wrapper registers the real class once its module is in
`sys.modules`, so dispatch resolves exactly as with eager imports. The IO
registry maps real classes back to their stand-ins via `canonical_type`.

Closes scverse#1122

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- canonicalize src_type in register_write, so writers registered for
  e.g. dask.array.Array (not the stand-in) are still found
- a class statement subclassing a stand-in imports and subclasses the
  real class instead of producing a broken stand-in

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@codecov

codecov Bot commented Nov 25, 2026

Copy link
Copy Markdown

❌ 1 Tests Failed:

Tests completed Failed Passed Skipped
6 1 5 2
View the top 1 failed test(s) by shortest run time
::src.anndata.experimental.backed._lazy_arrays
Stack Traces | 0s run time
#x1B[31mImportError while importing test module '.../experimental/backed/_lazy_arrays.py'.
Hint: make sure your test modules/packages have valid Python names.
Traceback:
#x1B[1m#x1B[.../experimental/backed/_lazy_arrays.py#x1B[0m:10: in <module>
    #x1B[0m#x1B[94mfrom#x1B[39;49;00m#x1B[90m #x1B[39;49;00m#x1B[04m#x1B[96mxarray#x1B[39;49;00m#x1B[04m#x1B[96m.#x1B[39;49;00m#x1B[04m#x1B[96mbackends#x1B[39;49;00m#x1B[90m #x1B[39;49;00m#x1B[94mimport#x1B[39;49;00m BackendArray #x1B[94mas#x1B[39;49;00m XBackendArray#x1B[90m#x1B[39;49;00m
#x1B[1m#x1B[31mE   ModuleNotFoundError: No module named 'xarray'#x1B[0m#x1B[0m

To view more test analytics, go to the Test Analytics Dashboard
📋 Got 3 mins? Take this short survey to help us improve Test Analytics.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Lazy imports for optional dependencies

1 participant