anndata.register_anndata_namespace

anndata.register_anndata_namespace#

anndata.register_anndata_namespace(name)[source]#

Decorator for registering custom functionality with a AnnData object.

This decorator allows you to extend AnnData objects with custom methods and properties organized under a namespace. The namespace becomes accessible as an attribute on AnnData instances, providing a clean way to you to add domain-specific functionality without modifying the AnnData class itself, or extending the class with additional methods as you see fit in your workflow.

Parameters:
name str

Name under which the accessor should be registered. This will be the attribute name used to access your namespace’s functionality on AnnData objects (e.g., instance.name). Cannot conflict with existing AnnData attributes. The list of reserved attributes includes everything outputted by dir(AnnData).

Return type:

Callable[[type[TypeVar(NameSpT, bound= ExtensionNamespace)]], type[TypeVar(NameSpT, bound= ExtensionNamespace)]]

Returns:

A decorator that registers the decorated class as a custom namespace.

Notes

Implementation requirements:

  1. The decorated class must have an __init__ method that accepts exactly one parameter (besides self) named adata and annotated with type AnnData.

  2. The namespace will be initialized with the AnnData object on first access and then cached on the instance.

  3. If the namespace name conflicts with an existing namespace, a warning is issued.

  4. If the namespace name conflicts with a built-in AnnData attribute, an AttributeError is raised.

Examples

>>> @register_anndata_namespace("do_something")
... class DoSomething:
...     def __init__(self, adata: AnnData):
...         self._obj = adata
...
...     def has_foo(self) -> bool:
...         return hasattr(self._obj, "foo")
>>>
>>> # Create a AnnData object
>>> obj = AnnData()
>>>
>>> # use the registered namespace
>>> obj.do_something.has_foo()
False