Skip to content

class_set_parameter.py

Contains a class in order to contain parameters for the YamlParser class.

SetParameter

To create a parameter.

Attributes

self.__value : any
The value linked to the parameter.

self.__error : dict
Errors to check if the parameter is well set.

self.__typing : list | any
The typing of the parameter value.

self.__path : str
Where to find the parameter value in the .yaml file.

self.__category : str
The parameter category.

Source code in src/smiffer/parse_yaml/class_set_parameter.py
 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
 55
 56
 57
 58
 59
 60
 61
 62
 63
 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
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
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
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
class SetParameter:
    """To create a parameter.

    Attributes
    ----------
    self.__value : `any`
        The value linked to the parameter.

    self.__error : `dict`
        Errors to check if the parameter is well set.

    self.__typing : `list | any`
        The typing of the parameter value.

    self.__path : `str`
        Where to find the parameter value in the `.yaml` file.

    self.__category : `str`
        The parameter category.
    """

    # pylint: disable=too-many-arguments
    # Object needs these 5 parameters to be correctly set up.
    def __init__(
        self,
        default_value: any,
        typing: "list | any",
        path: str,
        category: str,
        error: dict = None
    ):
        """Initialize a SetParameter object.

        Parameters
        ----------
        default_value : `any`
            A default value if the user does not specify one.

        typing : `list | any`
            The expected type of the value.

        path : `str`
            The "path" to follow in the `.yml` file. If the yml file is:

            ```yml
            box:
                extra_size: 5
            ```

            The path to `extra_size` is "box:extra_size".

        category : `str`
            The category to include this parameter in.

        error : `dict`, optional
            A dictionary with error to verify. Key can be:
            - "inferior": The user's value must be superior or equal to this
                          given value (user_value ≥ this_value).
            - "set": The user's value must be included in the given list.
            - "length": The user's value length must be the same as is the
                        typing parameter. If `typing = [int, int]`, the
                        expected length is 2.If `typing = [[int, int]]`, the
                        expected length is 1 then 2.

            By default, set to None.
        """
        self.__value: any = default_value
        self.__error: dict = error
        self.__typing: "list | any" = typing
        self.__path: str = path
        self.__category: str = category

    # pylint: enable=too-many-arguments

    def check_error(self):
        """Check, in function of what is indicated in `self.__error`, if
        everything is correct for the user's given value.

        Raises
        ------
        ValueError
            A value have a type, a length or does not checked a given
            condition.
        """
        # Convert the "none" string into a None (NoneType).
        if isinstance(self.__value, str):
            if self.__value.strip().lower() == "none":
                self.__value = None

        if None not in [self.__error, self.__value]:
            # Checking that the user's value is inferior to a threshold.
            if "inferior" in self.__error:
                if self.__value < self.__error["inferior"]:
                    raise ValueError(f"[Err##] Parameter \"{self.__path}\""
                                     " cannot be inferior to "
                                     f"{self.__error['inferior']}.")

            # Checking if the user's value is included in a given finish set.
            if "set" in self.__error:
                if self.__value not in self.__error["set"]:
                    raise ValueError(f"[Err##] Parameter \"{self.__path}\" "
                                     "has to be included in "
                                     f"{self.__error['set']}.")

            # Check if the user's value, which should be a list, have the
            # correct length.
            if "length" in self.__error:
                if not self.__length_good(self.__value, self.__typing):
                    raise ValueError("[Err##] Parameter "
                                     f"\"{self.__path}\" have a length "
                                     "problem. Please check that the list "
                                     "respects the next format: "
                                     f"\"{self.__typing}\".")

        # Check if the user's value type is correct.
        if isinstance(self.__typing, list):
            if not self.__type_good(self.__value, self.__typing):
                raise TypeError(f"[Err##] Parameter \"{self.__path}\" "
                                f"has to be of type: \"{self.__typing}\"")
        else:
            if not isinstance(self.__value, self.__typing):
                raise TypeError(f"[Err##] Parameter \"{self.__path}\" "
                                f"has to be of type: \"{self.__typing}\"")

    def __length_good(
        self,
        value: "list | any",
        expect_len: "list | any"
    ) -> bool:
        """Check if the expect length is good in `value`.

        Parameters
        ----------
        value : `list | any`
            The list to check the length of.

        expect_len : `list | any`
            The list of the expected length.

        Returns
        -------
        `bool`
            `True` if the length is good, `False` otherwise.
        """
        # We check that we still have a list.
        if isinstance(expect_len, list):
            # We check that value is a list.
            if isinstance(value, list):
                # Returning False when the length does not match.
                if len(value) != len(expect_len):
                    return False
            # value should be a lst and is not, returning False.
            else:
                return False
        # No more list = ending.
        else:
            return True

        for i, err_i in enumerate(expect_len):
            # Checking each sub-list and sub-sub-list and […].
            if not self.__length_good(value[i], err_i):
                return False

        # All lengths were checked and are good.
        return True

    def __type_good(self, value: "list | any", typing: "list | type") -> bool:
        """Recursing through to see if the type in `value` is the same as
        define in `typing`.

        Parameters
        ----------
        value : `list | any`
            A list or a value to check.

        typing : `list | type`
            A list or the type to compare.

        Returns
        -------
        bool
            `True` if the type is good, `False` otherwise.
        """
        # We have no more list, checking if the type matches.
        if not isinstance(typing, list):
            return isinstance(value, typing)

        # Value should be a list and is not, returning False.
        if not isinstance(value, list):
            return False

        for i, type_i in enumerate(typing):
            # Checking each sub-list and sub-sub-list and […].
            if not self.__type_good(value[i], type_i):
                return False

        # Everything was checked all is good.
        return True

    def value(self, setter: any = None) -> any:
        """Getter or setter of attributes `__value`.

        Parameters
        ----------
        setter : `any`, optional
            If a value is given, the method is not any more a getter. It become
            a setter of `self.__value`. By default None, so is a getter.

        Returns
        -------
        `any`
            `__value`'s value.
        """
        # If None, is a getter. Else, is a setter.
        if setter is None:
            return self.__value

        # Setter.
        self.__value = setter

        # No value to return.
        return None

    def path(self) -> any:
        """Getter of attributes `__path`.

        Returns
        -------
        `any`
            `__path`'s value.
        """
        return self.__path

    def category(self) -> any:
        """Getter of attributes `__category`.

        Returns
        -------
        `any`
            `__category`'s value.
        """
        return self.__category

    def __str__(self) -> str:
        """Redefine the `print()` comportment of this class.

        Returns
        -------
        `str`
            The message to print.
        """
        to_print = f"Parameter \"{self.__path}\" is set to {self.__value}."
        return to_print

__init__(default_value, typing, path, category, error=None)

Initialize a SetParameter object.

Parameters

default_value : any
A default value if the user does not specify one.

list | any

The expected type of the value.

str

The "path" to follow in the .yml file. If the yml file is:

box:
    extra_size: 5

The path to extra_size is "box:extra_size".

str

The category to include this parameter in.

dict, optional

A dictionary with error to verify. Key can be:
- "inferior": The user's value must be superior or equal to this
given value (user_value ≥ this_value).
- "set": The user's value must be included in the given list.
- "length": The user's value length must be the same as is the
typing parameter. If typing = [int, int], the
expected length is 2.If typing = [[int, int]], the
expected length is 1 then 2.

By default, set to None.

Source code in src/smiffer/parse_yaml/class_set_parameter.py
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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
def __init__(
    self,
    default_value: any,
    typing: "list | any",
    path: str,
    category: str,
    error: dict = None
):
    """Initialize a SetParameter object.

    Parameters
    ----------
    default_value : `any`
        A default value if the user does not specify one.

    typing : `list | any`
        The expected type of the value.

    path : `str`
        The "path" to follow in the `.yml` file. If the yml file is:

        ```yml
        box:
            extra_size: 5
        ```

        The path to `extra_size` is "box:extra_size".

    category : `str`
        The category to include this parameter in.

    error : `dict`, optional
        A dictionary with error to verify. Key can be:
        - "inferior": The user's value must be superior or equal to this
                      given value (user_value ≥ this_value).
        - "set": The user's value must be included in the given list.
        - "length": The user's value length must be the same as is the
                    typing parameter. If `typing = [int, int]`, the
                    expected length is 2.If `typing = [[int, int]]`, the
                    expected length is 1 then 2.

        By default, set to None.
    """
    self.__value: any = default_value
    self.__error: dict = error
    self.__typing: "list | any" = typing
    self.__path: str = path
    self.__category: str = category

__length_good(value, expect_len)

Check if the expect length is good in value.

Parameters

value : list | any
The list to check the length of.

list | any

The list of the expected length.

Returns

bool
True if the length is good, False otherwise.

Source code in src/smiffer/parse_yaml/class_set_parameter.py
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
def __length_good(
    self,
    value: "list | any",
    expect_len: "list | any"
) -> bool:
    """Check if the expect length is good in `value`.

    Parameters
    ----------
    value : `list | any`
        The list to check the length of.

    expect_len : `list | any`
        The list of the expected length.

    Returns
    -------
    `bool`
        `True` if the length is good, `False` otherwise.
    """
    # We check that we still have a list.
    if isinstance(expect_len, list):
        # We check that value is a list.
        if isinstance(value, list):
            # Returning False when the length does not match.
            if len(value) != len(expect_len):
                return False
        # value should be a lst and is not, returning False.
        else:
            return False
    # No more list = ending.
    else:
        return True

    for i, err_i in enumerate(expect_len):
        # Checking each sub-list and sub-sub-list and […].
        if not self.__length_good(value[i], err_i):
            return False

    # All lengths were checked and are good.
    return True

__str__()

Redefine the print() comportment of this class.

Returns

str
The message to print.

Source code in src/smiffer/parse_yaml/class_set_parameter.py
253
254
255
256
257
258
259
260
261
262
def __str__(self) -> str:
    """Redefine the `print()` comportment of this class.

    Returns
    -------
    `str`
        The message to print.
    """
    to_print = f"Parameter \"{self.__path}\" is set to {self.__value}."
    return to_print

__type_good(value, typing)

Recursing through to see if the type in value is the same as
define in typing.

Parameters

value : list | any
A list or a value to check.

list | type

A list or the type to compare.

Returns

bool
True if the type is good, False otherwise.

Source code in src/smiffer/parse_yaml/class_set_parameter.py
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
def __type_good(self, value: "list | any", typing: "list | type") -> bool:
    """Recursing through to see if the type in `value` is the same as
    define in `typing`.

    Parameters
    ----------
    value : `list | any`
        A list or a value to check.

    typing : `list | type`
        A list or the type to compare.

    Returns
    -------
    bool
        `True` if the type is good, `False` otherwise.
    """
    # We have no more list, checking if the type matches.
    if not isinstance(typing, list):
        return isinstance(value, typing)

    # Value should be a list and is not, returning False.
    if not isinstance(value, list):
        return False

    for i, type_i in enumerate(typing):
        # Checking each sub-list and sub-sub-list and […].
        if not self.__type_good(value[i], type_i):
            return False

    # Everything was checked all is good.
    return True

category()

Getter of attributes __category.

Returns

any
__category's value.

Source code in src/smiffer/parse_yaml/class_set_parameter.py
243
244
245
246
247
248
249
250
251
def category(self) -> any:
    """Getter of attributes `__category`.

    Returns
    -------
    `any`
        `__category`'s value.
    """
    return self.__category

check_error()

Check, in function of what is indicated in self.__error, if
everything is correct for the user's given value.

Raises

ValueError
A value have a type, a length or does not checked a given
condition.

Source code in src/smiffer/parse_yaml/class_set_parameter.py
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
def check_error(self):
    """Check, in function of what is indicated in `self.__error`, if
    everything is correct for the user's given value.

    Raises
    ------
    ValueError
        A value have a type, a length or does not checked a given
        condition.
    """
    # Convert the "none" string into a None (NoneType).
    if isinstance(self.__value, str):
        if self.__value.strip().lower() == "none":
            self.__value = None

    if None not in [self.__error, self.__value]:
        # Checking that the user's value is inferior to a threshold.
        if "inferior" in self.__error:
            if self.__value < self.__error["inferior"]:
                raise ValueError(f"[Err##] Parameter \"{self.__path}\""
                                 " cannot be inferior to "
                                 f"{self.__error['inferior']}.")

        # Checking if the user's value is included in a given finish set.
        if "set" in self.__error:
            if self.__value not in self.__error["set"]:
                raise ValueError(f"[Err##] Parameter \"{self.__path}\" "
                                 "has to be included in "
                                 f"{self.__error['set']}.")

        # Check if the user's value, which should be a list, have the
        # correct length.
        if "length" in self.__error:
            if not self.__length_good(self.__value, self.__typing):
                raise ValueError("[Err##] Parameter "
                                 f"\"{self.__path}\" have a length "
                                 "problem. Please check that the list "
                                 "respects the next format: "
                                 f"\"{self.__typing}\".")

    # Check if the user's value type is correct.
    if isinstance(self.__typing, list):
        if not self.__type_good(self.__value, self.__typing):
            raise TypeError(f"[Err##] Parameter \"{self.__path}\" "
                            f"has to be of type: \"{self.__typing}\"")
    else:
        if not isinstance(self.__value, self.__typing):
            raise TypeError(f"[Err##] Parameter \"{self.__path}\" "
                            f"has to be of type: \"{self.__typing}\"")

path()

Getter of attributes __path.

Returns

any
__path's value.

Source code in src/smiffer/parse_yaml/class_set_parameter.py
233
234
235
236
237
238
239
240
241
def path(self) -> any:
    """Getter of attributes `__path`.

    Returns
    -------
    `any`
        `__path`'s value.
    """
    return self.__path

value(setter=None)

Getter or setter of attributes __value.

Parameters

setter : any, optional
If a value is given, the method is not any more a getter. It become
a setter of self.__value. By default None, so is a getter.

Returns

any
__value's value.

Source code in src/smiffer/parse_yaml/class_set_parameter.py
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
def value(self, setter: any = None) -> any:
    """Getter or setter of attributes `__value`.

    Parameters
    ----------
    setter : `any`, optional
        If a value is given, the method is not any more a getter. It become
        a setter of `self.__value`. By default None, so is a getter.

    Returns
    -------
    `any`
        `__value`'s value.
    """
    # If None, is a getter. Else, is a setter.
    if setter is None:
        return self.__value

    # Setter.
    self.__value = setter

    # No value to return.
    return None