Skip to content

medcat.utils.registry

Classes:

Attributes:

P module-attribute

P = TypeVar('P')

logger module-attribute

logger = getLogger(__name__)

MedCATRegistryException

MedCATRegistryException(*args: object)

Bases: Exception

Source code in medcat-v2/medcat/utils/registry.py
211
212
def __init__(self, *args: object) -> None:
    super().__init__(*args)

Registry

Registry(type: Type[P], lazy_defaults: Optional[dict[str, tuple[str, str]]] = None)

Bases: Generic[P]

Methods:

Source code in medcat-v2/medcat/utils/registry.py
12
13
14
15
16
17
def __init__(self, type: Type[P],
             lazy_defaults: Optional[dict[str, tuple[str, str]]] = None
             ) -> None:
    self._components: dict[str, Callable[..., P]] = {}
    self._type = type
    self._lazy_components = lazy_defaults.copy() if lazy_defaults else {}

get_component

get_component(component_name: str) -> Callable[..., P]

Get the component that's registered.

The component generally refers to the class, but may be another method that creates the object needed.

Parameters:

  • component_name

    (str) –

    The name of the component.

Raises:

Returns:

  • Callable[..., P]

    Callable[..., P]: The creator for the registered component.

Source code in medcat-v2/medcat/utils/registry.py
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
def get_component(self, component_name: str
                  ) -> Callable[..., P]:
    """Get the component that's registered.

    The component generally refers to the class, but may
    be another method that creates the object needed.

    Args:
        component_name (str): The name of the component.

    Raises:
        MedCATRegistryException: If no component by requested name
            is registered.

    Returns:
        Callable[..., P]: The creator for the registered component.
    """
    # NOTE: some default implementations may be big imports,
    #       so we only want to import them if/when required.
    if component_name in self._lazy_components:
        self._ensure_lazy_default(component_name)
    if component_name not in self._components:
        raise MedCATRegistryException(
            f"No component registered by name '{component_name}'. "
            f"Available components: {self.list_components()}")
    return self._components[component_name]

list_components

list_components() -> list[tuple[str, str]]

List all available component names and class names.

Returns:

  • list[tuple[str, str]]

    list[tuple[str, str]]: The list of the names and class names for each registered componetn.

Source code in medcat-v2/medcat/utils/registry.py
140
141
142
143
144
145
146
147
148
149
150
151
def list_components(self) -> list[tuple[str, str]]:
    """List all available component names and class names.

    Returns:
        list[tuple[str, str]]: The list of the names and class names
            for each registered componetn.
    """
    comps = [(comp_name, self.translate_name(comp))
             for comp_name, comp in self._components.items()]
    for lazy_def_name, (_, lazy_def_class) in self._lazy_components.items():
        comps.append((lazy_def_name, lazy_def_class))
    return comps

register

register(component_name: str, creator: Callable[..., P])
Source code in medcat-v2/medcat/utils/registry.py
19
20
21
22
23
24
25
def register(self, component_name: str,
             creator: Callable[..., P]):
    if component_name in self._components:
        prev = self._components[component_name]
        raise MedCATRegistryException(
            f"Component '{component_name}' already registered: {prev}")
    self._components[component_name] = creator

register_all_defaults

register_all_defaults() -> None

Register all default (lazily-added) components.

Source code in medcat-v2/medcat/utils/registry.py
108
109
110
111
def register_all_defaults(self) -> None:
    """Register all default (lazily-added) components."""
    for comp_name in list(self._lazy_components):
        self._ensure_lazy_default(comp_name)

register_lazy

register_lazy(component_name: str, module_path: str, creator_name: str) -> None

Register the component lazily.

This allows registration without the need to load component internals. However, we do not do any prior way of checking to make sure that these paths are correct.

For instance if your class MySpecialNER is in the module my_addon.my_module and uses the class method create_new_component to initialise (thus the complete path is my_addon.my_module.MySpecialNER.create_new_component) we would expect the following arguments: component_name="my_special_ner", module_path="my_addon.my_module", creator_name="MySpecialNER.create_new_component"

Parameters:

  • component_name

    (str) –

    The component name.

  • module_path

    (str) –

    The module name.

  • creator_name

    (str) –

    The creator path.

Raises:

Source code in medcat-v2/medcat/utils/registry.py
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
def register_lazy(self, component_name: str, module_path: str,
                  creator_name: str) -> None:
    """Register the component lazily.

    This allows registration without the need to load component internals.
    However, we do not do any prior way of checking to make sure that these
    paths are correct.

    For instance if your class `MySpecialNER` is in the module
    `my_addon.my_module` and uses the class method
    `create_new_component` to initialise (thus the complete path is
    `my_addon.my_module.MySpecialNER.create_new_component`) we
    would expect the following arguments:
        component_name="my_special_ner",
        module_path="my_addon.my_module",
        creator_name="MySpecialNER.create_new_component"

    Args:
        component_name (str): The component name.
        module_path (str): The module name.
        creator_name (str): The creator path.

    Raises:
        MedCATRegistryException: If a component by this name has
            already been registered.
    """
    if component_name in self._components:
        prev = self._components[component_name]
        raise MedCATRegistryException(
            f"Component '{component_name}' already registered: {prev}")
    if component_name in self._lazy_components:
        prev = self._components[component_name]
        raise MedCATRegistryException(
            "Component '{component_name}' already registered (lazily):"
            f" {prev}")
    self._lazy_components[component_name] = (module_path, creator_name)

translate_name classmethod

translate_name(initialiser: Callable[..., P]) -> str

Translate creator / initialiser name.

This method will return the method name. Or this is a bound method, it'll return the class name along with the method name (Class.method)

Parameters:

  • initialiser

    (Callable[..., P]) –

    The initialiser

Returns:

  • str ( str ) –

    The resulting name

Source code in medcat-v2/medcat/utils/registry.py
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
@classmethod
def translate_name(cls, initialiser: Callable[..., P]) -> str:
    """Translate creator / initialiser name.

    This method will return the method name.
    Or this is a bound method, it'll return the class name
    along with the method name (Class.method)

    Args:
        initialiser (Callable[..., P]): The initialiser

    Returns:
        str: The resulting name
    """
    if isinstance(initialiser, type):
        # type / dunder init
        return initialiser.__name__
    try:
        # probably a bound method
        return (
            initialiser.__self__.__name__ +  # type: ignore
            "." + initialiser.__name__)
    except AttributeError as err:
        logger.warning("Could not translate component name: %s",
                       initialiser, exc_info=err)
        return initialiser.__name__

unregister_all_components

unregister_all_components() -> None

Unregister all components.

Source code in medcat-v2/medcat/utils/registry.py
196
197
198
199
def unregister_all_components(self) -> None:
    """Unregister all components."""
    for comp_name in list(self._components):
        self.unregister_component(comp_name)

unregister_component

unregister_component(component_name: str) -> Callable[..., P]

Unregister a component.

Parameters:

  • component_name

    (str) –

    The component name.

Raises:

Returns:

  • Callable[..., P]

    Callable[..., P]: The creator of the component.

Source code in medcat-v2/medcat/utils/registry.py
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
def unregister_component(self, component_name: str
                         ) -> Callable[..., P]:
    """Unregister a component.

    Args:
        component_name (str): The component name.

    Raises:
        MedCATRegistryException: If no component by the name specified
            had been registered.

    Returns:
        Callable[..., P]: The creator of the component.
    """
    if component_name not in self._components:
        raise MedCATRegistryException(
            f"No such component: {component_name}")
    logger.debug("Unregistering %s '%s'", self._type.__name__,
                 component_name)
    return self._components.pop(component_name)

unregister_component_lazy

unregister_component_lazy(component_name: str) -> tuple[str, str]

Unregister a lazy component.

Parameters:

  • component_name

    (str) –

    The component name.

Raises:

Returns:

  • tuple[str, str]

    tuple[str, str]: The component module and init method.

Source code in medcat-v2/medcat/utils/registry.py
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
def unregister_component_lazy(
        self, component_name: str
        ) -> tuple[str, str]:
    """Unregister a lazy component.

    Args:
        component_name (str): The component name.

    Raises:
        MedCATRegistryException: If no component by the name specified
            had been registered.

    Returns:
        tuple[str, str]: The component module and init method.
    """
    if component_name not in self._lazy_components:
        raise MedCATRegistryException(
            f"No such lazy component: {component_name}")
    logger.debug("Unregistering lazy %s '%s'", self._type.__name__,
                 component_name)
    return self._lazy_components.pop(component_name)