Add | 添加了 Option 的 OptionNotFilled 选项

This commit is contained in:
shenjack 2023-12-22 00:40:17 +08:00
parent 364624a996
commit e8b040ab97
Signed by: shenjack
GPG Key ID: 7B1134A979775551
2 changed files with 33 additions and 0 deletions

View File

@ -1,5 +1,16 @@
# lndl 0.3 # lndl 0.3
## 0.3.12
- `Options`
- 又回来维护了哈
- 添加了 `_check_filled` 预定义选项
- 如果为 `True`
- 会在 `Options` 初始化时检查是否有未填写的选项
- 如果有, 则会抛出 `OptionNotFilled`
- 添加 `OptionNotFilled` 异常
- 用于在 `Options` 初始化时检查是否有未填写的选项
## 0.3.11 ## 0.3.11
- 修复了 `Logger` 任意等级消息 `flush` 默认为 `True` - 修复了 `Logger` 任意等级消息 `flush` 默认为 `True`

View File

@ -21,13 +21,16 @@ from typing import (
Iterable, Iterable,
) )
# fmt: off
__all__ = [ __all__ = [
"get_type_hints_", "get_type_hints_",
"Options", "Options",
"OptionsError", "OptionsError",
"OptionNotFound", "OptionNotFound",
"OptionNotFilled",
"OptionNameNotDefined", "OptionNameNotDefined",
] ]
# fmt: on
def get_type_hints_(cls: Type): def get_type_hints_(cls: Type):
@ -61,6 +64,10 @@ class OptionNotFound(OptionsError):
"""某个选项没有找到""" """某个选项没有找到"""
class OptionNotFilled(OptionsError):
"""某个选项没有填写"""
class Options: class Options:
""" """
一个用于存储选项 / 提供 API 定义 的类 一个用于存储选项 / 提供 API 定义 的类
@ -73,11 +80,17 @@ class Options:
定义 一些需要的方法 定义 一些需要的方法
子类: 继承 新的 Options 子类: 继承 新的 Options
实现定义的方法 实现定义的方法
_check_options: 用于检查是否输入的选项都是已经定义的选项
_check_filled: 用于检查是否所有的选项都已经填写
""" """
name = "Option Base" name = "Option Base"
cached_options: Dict[str, Union[str, Any]] = {} cached_options: Dict[str, Union[str, Any]] = {}
# 用于检查是否输入的选项都是已经定义的选项
_check_options: bool = True _check_options: bool = True
# 用于检查是否所有的选项都已经填写
_check_filled: bool = False
def __init__(self, **kwargs): def __init__(self, **kwargs):
""" """
@ -88,12 +101,21 @@ class Options:
if TYPE_CHECKING: if TYPE_CHECKING:
self._options: Dict[str, Union[Callable, object]] = {} self._options: Dict[str, Union[Callable, object]] = {}
self.flush_option() self.flush_option()
miss_list = []
if self._check_filled:
miss_list = [key for key in self.cached_options]
for option, value in kwargs.items(): for option, value in kwargs.items():
if option not in self.cached_options and self._check_options: if option not in self.cached_options and self._check_options:
raise OptionNameNotDefined( raise OptionNameNotDefined(
f"option: {option} with value: {value} is not defined" f"option: {option} with value: {value} is not defined"
) )
setattr(self, option, value) setattr(self, option, value)
if self._check_filled:
miss_list.remove(option)
if self._check_filled and miss_list:
raise OptionNotFilled(
f"option: {miss_list} is not filled in {self.name}"
)
run_load_file = True run_load_file = True
if hasattr(self, "init"): if hasattr(self, "init"):
run_load_file = self.init(**kwargs) # 默认 False/None run_load_file = self.init(**kwargs) # 默认 False/None