Coverage for src / c41811 / config / basic / factory.py: 100%
21 statements
« prev ^ index » next coverage.py v7.13.3, created at 2026-02-06 06:04 +0000
« prev ^ index » next coverage.py v7.13.3, created at 2026-02-06 06:04 +0000
1# cython: language_level = 3 # noqa: ERA001
4"""
5配置数据工厂
7.. versionadded:: 0.3.0
8"""
10from typing import TYPE_CHECKING
11from typing import Any
12from typing import ClassVar
14if TYPE_CHECKING:
15 from collections import OrderedDict
16 from collections.abc import Callable
18 from ..abc import ABCConfigData
19else:
20 from collections import OrderedDict
21 from collections.abc import Callable
23 ABCConfigData = Any
26class ConfigDataFactory:
27 """
28 配置数据工厂类
30 .. versionchanged:: 0.1.5
31 会自动根据传入的数据类型选择对应的配置数据类
33 .. versionchanged:: 0.3.0
34 不再作为所有 `ConfigData` 的虚拟父类
35 重命名 ``ConfigData`` 为 ``ConfigDataFactory``
36 """
38 TYPES: ClassVar[OrderedDict[tuple[type, ...], Callable[[Any], ABCConfigData] | type]]
39 """
40 存储配置数据类型对应的子类
42 .. versionchanged:: 0.2.0
43 现在使用 ``OrderedDict`` 来保证顺序
44 """
46 _TYPES_LAZY_INITIALIZER: ClassVar[Callable[[], None]]
47 """
48 用于初始化 :py:attr:`TYPES` 的函数
50 .. versionadded:: 0.3.0
51 """
53 def __new__(cls, *args: Any, **kwargs: Any) -> ABCConfigData: # type: ignore[misc]
54 """
55 将根据第一个位置参数决定配置数据类型
57 :param args: 配置数据
58 :type args: Any
59 :param kwargs: 配置数据
60 :type kwargs: Any
62 :return: 配置数据类
63 :rtype: ABCConfigData
64 """
65 if not hasattr(cls, "TYPES"):
66 cls._TYPES_LAZY_INITIALIZER()
68 if not args:
69 args = (None,)
70 for types, config_data_cls in cls.TYPES.items():
71 if not isinstance(args[0], types):
72 continue
73 return config_data_cls(*args, **kwargs)
74 msg = f"Unsupported type: {args[0]}"
75 raise TypeError(msg)
78__all__ = ("ConfigDataFactory",)