aboutsummaryrefslogtreecommitdiff
path: root/src/mlia/core/mixins.py
blob: ee03100ea14362e6a3c04a6aa8ef693276f27d6c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
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
# SPDX-FileCopyrightText: Copyright 2022, Arm Limited and/or its affiliates.
# SPDX-License-Identifier: Apache-2.0
"""Mixins module."""
from typing import Any
from typing import Optional

from mlia.core.context import Context


class ContextMixin:
    """Mixin for injecting context object."""

    context: Context

    def set_context(self, context: Context) -> None:
        """Context setter."""
        self.context = context


class ParameterResolverMixin:
    """Mixin for parameter resolving."""

    context: Context

    def get_parameter(
        self,
        section: str,
        name: str,
        expected: bool = True,
        expected_type: Optional[type] = None,
        context: Optional[Context] = None,
    ) -> Any:
        """Get parameter value."""
        ctx = context or self.context

        if ctx.config_parameters is None:
            raise Exception("Configuration parameters are not set")

        section_params = ctx.config_parameters.get(section)
        if section_params is None or not isinstance(section_params, dict):
            raise Exception(
                f"Parameter section {section} has wrong format, "
                "expected to be a dictionary"
            )

        value = section_params.get(name)

        if not value and expected:
            raise Exception(f"Parameter {name} is not set")

        if value and expected_type is not None and not isinstance(value, expected_type):
            raise Exception(f"Parameter {name} expected to have type {expected_type}")

        return value