Repository navigation
perf: import optional dependencies lazily - #2762
Draft
ashwanijha04 wants to merge 3 commits into
Draft
ashwanijha04 wants to merge 3 commits into
ashwanijha04 wants to merge 3 commits into
Conversation
`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>
❌ 1 Tests Failed:
View the top 1 failed test(s) by shortest run time
To view more test analytics, go to the Test Analytics Dashboard |
This branch has not been deployed
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
docs/release-notes/2762.perf.md)What
import anndatano 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 insys.modules, the answer is "no", which is always correct because no instance can exist yet.Calls, attribute access (
XDataset.from_dataframe) andclass 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.Datasetis a realMapping, so it was dispatched to theMappinghandler. A regression test covers this.Type-keyed lookups. The IO registry (
register_write,get_write,has_write,get_spec) andwriteable_elemsgo throughcanonical_type(), which maps a real class to its stand-in. Writers registered for either the real class or the stand-in are therefore found.DaskArrayViewandAwkwardArrayVieware built on first use.anndata.experimental.backedloads 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):import anndataread_lazy)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 nowFalse, because the stand-in is not the real class. Useisinstance, orcanonical_type(type(x)) is DaskArray. The one test in this repo that did this is updated.anndata.compatis private API.functools.singledispatchwithanndata.compattypes keeps working: it gets the virtual-base behaviour._REGISTRY.register_write(zarr.Group, DaskArrayView, …)) keep working, whether made with the stand-in or the real class.Testing
tests/test_lazy_imports.py:import anndata, anndata.experimentalloads none of the optional dependencies.singledispatchbefore and after import (including theMappingpriority case),register_writewith a real class, and subclassing a stand-in.scikit-misc, which isn't installed, and 1 is a local image comparison.hatch run hatch-check-types:checkconfiguration, Python 3.14) and ruff: clean.🤖 Generated with Claude Code