pyutilities_simple 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,2 @@
1
+ def main() -> None:
2
+ print("Hello from pyutilities!")
@@ -0,0 +1,106 @@
1
+ #!/usr/bin/python3
2
+ # -*- coding: UTF-8 -*-
3
+ import sys
4
+ from types import ModuleType
5
+ from typing import Final, Callable
6
+
7
+ from pyutilities_simple.singleton import singleton
8
+
9
+
10
+ @singleton
11
+ class _const(ModuleType):
12
+ """ 单例模式的常量管理模块
13
+
14
+ 特性:
15
+ - 常量名称必须全大写(强制命名规范)
16
+ - 常量一旦定义不可修改或删除(只读特性)
17
+ - 全局唯一实例,确保常量在整个程序中保持一致
18
+ """
19
+
20
+ class ConstError(PermissionError):
21
+ """尝试修改或删除已定义常量时触发的异常"""
22
+ pass
23
+
24
+ class ConstCaseError(TypeError):
25
+ """常量名称不是全大写时触发的异常"""
26
+ pass
27
+
28
+ def __init__(self, module_name: str | None = None) -> None:
29
+ """初始化常量模块,继承ModuleType的特性"""
30
+ # 确定模块名称,默认使用当前模块名
31
+ name = module_name if module_name is not None else __name__
32
+ super().__init__(name)
33
+
34
+ # 初始化内置属性(标记为"内置",清空时保留)
35
+ self.__dict__["__version__"] = "1.0.0"
36
+ self.__dict__["__description__"] = "A singleton-based constant management module"
37
+ # 手动绑定模块原生属性(解决coverage访问__file__的问题)
38
+ self.__dict__["__file__"] = sys.modules[name].__file__ if name in sys.modules else __file__
39
+ self.__dict__["__name__"] = name
40
+
41
+ def __setattr__(self, name: str, value: object) -> None:
42
+ """ 重写属性设置方法,实现常量约束:
43
+ 1. 已存在的常量不允许重新赋值
44
+ 2. 常量名称必须使用全大写字母
45
+ """
46
+ # 跳过内置特殊属性的设置(避免覆盖__file__等)
47
+ if name.startswith("__") and name.endswith("__"):
48
+ self.__dict__[name] = value
49
+ return
50
+ # 校验1:不允许重复赋值(已存在则报错)
51
+ if name in self.__dict__:
52
+ raise self.ConstError(f"Cannot modify constant '{name}': constants are immutable")
53
+ # 校验2:名称必须全大写
54
+ if not name.isupper():
55
+ raise self.ConstCaseError(f"Constant name '{name}' must be in uppercase")
56
+ # 合法常量:添加到字典
57
+ self.__dict__[name] = value
58
+
59
+ def __delattr__(self, name: str) -> None:
60
+ """重写属性删除方法,禁止删除已定义的常量"""
61
+ # 跳过内置特殊属性的设置(避免覆盖__file__等)
62
+ if name.startswith("__") and name.endswith("__"):
63
+ raise self.ConstError(f"Cannot delete built-in attribute '{name}'")
64
+ if name in self.__dict__:
65
+ raise self.ConstError(f"Cannot delete constant '{name}': constants cannot be deleted")
66
+ raise NameError(f"Constant '{name}' is not defined")
67
+
68
+ def __getattr__(self, name: str) -> object:
69
+ """获取属性:内置属性正常返回,未定义常量抛异常"""
70
+ if name.startswith("__") and name.endswith("__"):
71
+ return super().__getattribute__(name)
72
+ if name not in self.__dict__:
73
+ raise NameError(f"Constant '{name}' is not defined")
74
+ return self.__dict__[name]
75
+
76
+ def list_constants(self) -> list[str]:
77
+ """返回所有用户定义的常量名称(排除模块内置属性)"""
78
+ return [
79
+ name for name in sorted(self.__dict__.keys())
80
+ if name.isupper() and not name.startswith("__")
81
+ ]
82
+
83
+ def get_constant(self, name: str) -> object | None:
84
+ """安全获取常量值,不存在时返回None而非抛出异常"""
85
+ return self.__dict__.get(name)
86
+
87
+ def clear_user_constants(self) -> None:
88
+ """彻底清空所有用户常量(保留内置属性)"""
89
+ # 遍历并删除所有用户定义的常量(全大写、非双下划线)
90
+ for name in list(self.__dict__.keys()): # 转列表避免遍历中修改字典
91
+ if name.isupper() and not name.startswith("__"):
92
+ del self.__dict__[name]
93
+
94
+
95
+ # 替换模块为单例实例(全局唯一)
96
+ sys.modules[__name__] = _const(__name__)
97
+
98
+
99
+ # 导出公共接口
100
+ __all__ = ["ConstError", "ConstCaseError", "list_constants", "get_constant", "clear_user_constants"]
101
+
102
+ # 为公共接口添加Final类型提示,明确其不可修改性,绑定模块级接口
103
+ list_constants: Final[Callable[[], list[str]]] = sys.modules[__name__].list_constants
104
+ get_constant: Final[Callable[[str], object | None]] = sys.modules[__name__].get_constant
105
+ ConstError: Final[type[PermissionError]] = sys.modules[__name__].ConstError
106
+ ConstCaseError: Final[type[TypeError]] = sys.modules[__name__].ConstCaseError
@@ -0,0 +1,85 @@
1
+ #!/usr/bin/python3
2
+ # -*- coding: UTF-8 -*-
3
+ import sys
4
+ from types import ModuleType
5
+ from typing import Final, Callable, override, cast
6
+
7
+ from pyutilities_simple.singleton import singleton
8
+
9
+ @singleton
10
+ class GlobalVarModule(ModuleType):
11
+ """
12
+ 单例模式的全局变量管理模块
13
+ 特性:
14
+ 1. 全局唯一实例,跨模块共享变量
15
+ 2. 支持安全获取变量(不存在返回None)
16
+ 3. 支持列出所有全局变量
17
+ 4. 支持清空全局变量(主要用于测试)
18
+ 5. 可选只读变量保护
19
+ """
20
+ # 内置只读变量(不可修改/删除)
21
+ _READ_ONLY_KEYS: Final[list[str]] = ["ver"]
22
+
23
+ def __init__(self, module_name: str = __name__) -> None:
24
+ """初始化全局变量模块,继承ModuleType以兼容模块特性"""
25
+ super().__init__(module_name)
26
+ # 初始化内置版本号(只读)
27
+ self.__dict__["ver"] = "0.1.0"
28
+ # 模块元信息
29
+ self.__dict__["__description__"] = "Singleton-based global variable manager"
30
+
31
+ @override
32
+ def __setattr__(self, name: str, value: object) -> None:
33
+ """重写属性设置:保护只读变量"""
34
+ # 保护内置只读变量
35
+ if name in self._READ_ONLY_KEYS and name in self.__dict__:
36
+ raise PermissionError(f"Read-only variable '{name}' cannot be modified")
37
+ self.__dict__[name] = value
38
+
39
+ @override
40
+ def __delattr__(self, name: str) -> None:
41
+ """重写属性删除:保护只读变量"""
42
+ if name in self._READ_ONLY_KEYS:
43
+ raise PermissionError(f"Read-only variable '{name}' cannot be deleted")
44
+ if name not in self.__dict__:
45
+ raise NameError(f"Global variable '{name}' does not exist")
46
+ del self.__dict__[name]
47
+
48
+ def get_var(self, name: str, default: object = None):
49
+ """
50
+ 安全获取全局变量
51
+ Args:
52
+ name: 变量名
53
+ default: 不存在时的默认值(默认None)
54
+ Returns:
55
+ 变量值或默认值
56
+ """
57
+ return cast(object, self.__dict__.get(name, default))
58
+
59
+ def list_vars(self):
60
+ """返回所有用户定义的全局变量(排除内置属性)"""
61
+ return [
62
+ name for name in sorted(self.__dict__.keys())
63
+ if not name.startswith("__") and name not in self._READ_ONLY_KEYS
64
+ ]
65
+
66
+ def list_all_vars(self):
67
+ """返回所有变量(包含内置/只读变量)"""
68
+ return sorted(self.__dict__.keys())
69
+
70
+ def clear_vars(self):
71
+ """清空所有非只读的全局变量(仅用于测试/重置)"""
72
+ for name in self.list_vars():
73
+ del self.__dict__[name]
74
+
75
+ # 将模块替换为单例实例,实现全局唯一
76
+ sys.modules[__name__] = GlobalVarModule(__name__)
77
+
78
+ # 导出公共接口(增强类型提示)
79
+ __all__ = ["get_var", "list_vars", "list_all_vars", "clear_vars"]
80
+
81
+ # 绑定模块级接口(适配直接调用)
82
+ get_var: Final[Callable[[str, object | None], object | None]] = sys.modules[__name__].get_var
83
+ list_vars: Final[Callable[[], list[str]]] = sys.modules[__name__].list_vars
84
+ list_all_vars: Final[Callable[[], list[str]]] = sys.modules[__name__].list_all_vars
85
+ clear_vars: Final[Callable[[], None]] = sys.modules[__name__].clear_vars