|
2 | 2 |
|
3 | 3 | import abc
|
4 | 4 | import json
|
| 5 | +from typing import ( |
| 6 | + NoReturn, |
| 7 | + Optional, |
| 8 | +) |
5 | 9 |
|
6 | 10 | import yaml
|
7 | 11 |
|
8 | 12 |
|
| 13 | +def _raise_error_no_key(key: str) -> NoReturn: |
| 14 | + raise ValueError(f"Key {key!r} is missing") |
| 15 | + |
| 16 | + |
9 | 17 | class EnvParamGetter(abc.ABC):
|
10 | 18 | @abc.abstractmethod
|
11 |
| - def get_str_value(self, key: str) -> str: |
| 19 | + def get_str_value(self, key: str) -> Optional[str]: |
12 | 20 | raise NotImplementedError
|
13 | 21 |
|
14 |
| - def get_int_value(self, key: str) -> int: |
| 22 | + def get_str_value_strict(self, key: str) -> str: |
| 23 | + str_value = self.get_str_value(key) |
| 24 | + if str_value is None: |
| 25 | + _raise_error_no_key(key) |
| 26 | + return str_value |
| 27 | + |
| 28 | + def get_int_value(self, key: str) -> Optional[int]: |
15 | 29 | str_value = self.get_str_value(key)
|
16 |
| - return int(str_value) |
| 30 | + if str_value is not None: |
| 31 | + return int(str_value) |
| 32 | + return None |
17 | 33 |
|
18 |
| - def get_json_value(self, key: str) -> dict: |
| 34 | + def get_int_value_strict(self, key: str) -> int: |
| 35 | + int_value = self.get_int_value(key) |
| 36 | + if int_value is None: |
| 37 | + _raise_error_no_key(key) |
| 38 | + return int_value |
| 39 | + |
| 40 | + def get_json_value(self, key: str) -> Optional[dict]: |
19 | 41 | str_value = self.get_str_value(key)
|
20 |
| - return json.loads(str_value) |
| 42 | + if str_value is not None: |
| 43 | + return json.loads(str_value) |
| 44 | + return None |
| 45 | + |
| 46 | + def get_json_value_strict(self, key: str) -> dict: |
| 47 | + json_value = self.get_json_value(key) |
| 48 | + if json_value is None: |
| 49 | + _raise_error_no_key(key) |
| 50 | + return json_value |
21 | 51 |
|
22 |
| - def get_yaml_value(self, key: str) -> dict: |
| 52 | + def get_yaml_value(self, key: str) -> Optional[dict]: |
23 | 53 | str_value = self.get_str_value(key)
|
24 |
| - return yaml.safe_load(str_value) |
| 54 | + if str_value is not None: |
| 55 | + return yaml.safe_load(str_value) |
| 56 | + return None |
25 | 57 |
|
| 58 | + def get_yaml_value_strict(self, key: str) -> dict: |
| 59 | + yaml_value = self.get_yaml_value(key) |
| 60 | + if yaml_value is None: |
| 61 | + _raise_error_no_key(key) |
| 62 | + return yaml_value |
| 63 | + |
| 64 | + @abc.abstractmethod |
26 | 65 | def initialize(self, config: dict) -> None:
|
27 | 66 | pass
|
0 commit comments