datalad-core/datalad_core/services/feature_registry.py
Michael Hanke c36de9392a
All checks were successful
Codespell / Check for spelling errors (push) Successful in 31s
Ruff / Code linting (push) Successful in 38s
Type annotation (project) / check (push) Successful in 50s
Unit tests (Linux) / check (push) Successful in 1m53s
rf(FeatureRegistry): relax return-type constraints for callables
Previously, they had to return an actual `dict`. But in fact, the
implementation works for any mapping. The type annotation has been
relaxed accordingly.
2026-05-26 08:22:15 +02:00

105 lines
3.2 KiB
Python

from collections.abc import (
Callable,
Hashable,
Iterable,
Mapping,
)
from functools import wraps
from types import MappingProxyType
from typing import (
Any,
)
from datalad_core.consts import UnsetValue
class FeatureRegistry:
"""Facility for deferred determination of named properties
Callables that return an arbitrary name-value mapping can be registered in
an instance of this class, The execution of such a callable is deferred
until a corresponding value is first requested by label. Any computed
value is then cached, and subsequent queries to not re-execute the
callable.
This can be useful for centralizing an efficient query of
platform/system/environment features (hence the name), which may be
expensive, but nevertheless necessary to determine.
Any registered callable must not have required arguments. It must return
a mapping from any number of hashable labels to the respective values.
>>> fr = FeatureRegistry()
>>> fr.register(lambda: {'feat1': 42 / 3, 'feat2': 'a' * 1000}, ['feat1', 'feat2'])
>>> list(fr.keys())
['feat1', 'feat2']
>>> 'feat1' in fr
True
>>> 'feat1' in fr.evaluated()
False
>>> fr['feat2'].startswith('aaaa')
True
>>> 'feat1' in fr.evaluated()
True
"""
def __init__(self) -> None:
self._featmap: dict[Hashable, Callable[[], Mapping[Hashable, Any]]] = {}
self._cache: dict[Hashable, Any] = {}
def register(
self,
fx: Callable[[], Mapping[Hashable, Any]],
names: Hashable | Iterable[Hashable],
) -> None:
"""Register a callable for evaluating one or more features
Besides the callable, a one or more feature names/labels must be
specified. Using any of these names in a query will trigger the
execution of the callable.
Any callable must not have required arguments, and must return a
mapping from (hashable) feature names to their respective values.
"""
if not callable(fx):
msg = f'Feature detector must be a callable, got {type(fx)}'
raise TypeError(msg)
if isinstance(names, Hashable):
names = [names]
for name in names:
self._featmap[name] = fx
def evaluated(self) -> MappingProxyType:
"""Return read-only mapping of presently evaluated features
This can be used to inspect the registry without triggering
further feature evaluations.
"""
return MappingProxyType(self._cache)
def __getitem__(self, name: Hashable) -> Any:
val = self._cache.get(name, UnsetValue)
if val != UnsetValue:
return val
try:
fx = self._featmap[name]
except KeyError as e:
# feature not registered
msg = f'{name!r} is not a registered feature'
raise ValueError(msg) from e
features = fx()
for k, v in features.items():
self._cache[k] = v
return features[name]
def __contains__(self, name) -> bool:
return name in self._featmap
@wraps(dict.keys)
def keys(self):
return self._featmap.keys()