Coverage for physioblocks / registers / load_function_register.py: 100%
21 statements
« prev ^ index » next coverage.py v7.13.1, created at 2026-01-09 16:40 +0100
« prev ^ index » next coverage.py v7.13.1, created at 2026-01-09 16:40 +0100
1# SPDX-FileCopyrightText: Copyright INRIA
2#
3# SPDX-License-Identifier: LGPL-3.0-only
4#
5# Copyright INRIA
6#
7# This file is part of PhysioBlocks, a library mostly developed by the
8# [Ananke project-team](https://team.inria.fr/ananke) at INRIA.
9#
10# Authors:
11# - Colin Drieu
12# - Dominique Chapelle
13# - François Kimmig
14# - Philippe Moireau
15#
16# PhysioBlocks is free software: you can redistribute it and/or modify it under the
17# terms of the GNU Lesser General Public License as published by the Free Software
18# Foundation, version 3 of the License.
19#
20# PhysioBlocks is distributed in the hope that it will be useful, but WITHOUT ANY
21# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
22# PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
23#
24# You should have received a copy of the GNU Lesser General Public License along with
25# PhysioBlocks. If not, see <https://www.gnu.org/licenses/>.
27"""
28Define decorators to register any function as a specific load function
29of a configuration object.
30"""
32from collections.abc import Callable
33from typing import Any, TypeVar
35from physioblocks.base.registers import register
37__load_functions_register: dict[type, Callable[..., Any]] = {}
40T = TypeVar("T")
43def loads(
44 loaded_type: type[T],
45) -> Callable[[Callable[..., T]], Callable[..., T]]:
46 """
47 Decorator to register a method that loads a registered type.
49 :param loaded_type: the loaded type
50 :type loaded_type: str
52 :return: the class decorator
53 :rtype: Callable
54 """
56 def register_decorator(load_function: Callable[..., T]) -> Callable[..., T]:
57 register(__load_functions_register, loaded_type, load_function)
58 return load_function
60 return register_decorator
63def get_load_function(loaded_type: type) -> Callable[..., Any]:
64 """
65 Get a registered load function.
67 :param type_id: the registered type id
68 :type type_id: str
70 :raise KeyError: Raises a key error if the type is not registered.
72 :return: the registered type
73 :rtype: type
74 """
75 key_type = _get_closest_type(loaded_type)
77 if key_type is None:
78 raise KeyError(
79 str.format(
80 "No load function registered for type {0}",
81 loaded_type.__name__,
82 )
83 )
84 return __load_functions_register[key_type]
87def _get_closest_type(searched_type: type | None) -> None | type:
88 if searched_type is None:
89 return None
90 elif searched_type in __load_functions_register:
91 return searched_type
92 else:
93 return _get_closest_type(searched_type.__base__)