ErisPulse 2.3.4.dev2__py3-none-any.whl → 2.3.4.dev114514__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.
Files changed (40) hide show
  1. ErisPulse/Core/Bases/module.py +1 -53
  2. ErisPulse/Core/Bases/module.pyi +0 -43
  3. ErisPulse/Core/Event/command.py +1 -6
  4. ErisPulse/Core/_self_config.py +1 -1
  5. ErisPulse/Core/adapter.py +10 -70
  6. ErisPulse/Core/adapter.pyi +1 -18
  7. ErisPulse/Core/exceptions.py +2 -4
  8. ErisPulse/Core/lifecycle.py +0 -9
  9. ErisPulse/Core/logger.py +15 -21
  10. ErisPulse/Core/logger.pyi +1 -2
  11. ErisPulse/Core/module.py +9 -57
  12. ErisPulse/Core/module.pyi +1 -12
  13. ErisPulse/Core/router.py +5 -13
  14. ErisPulse/Core/storage.py +256 -94
  15. ErisPulse/Core/storage.pyi +66 -13
  16. ErisPulse/__init__.py +1237 -35
  17. ErisPulse/__init__.pyi +290 -3
  18. ErisPulse/sdk_protocol.py +143 -0
  19. ErisPulse/sdk_protocol.pyi +97 -0
  20. {erispulse-2.3.4.dev2.dist-info → erispulse-2.3.4.dev114514.dist-info}/METADATA +1 -1
  21. {erispulse-2.3.4.dev2.dist-info → erispulse-2.3.4.dev114514.dist-info}/RECORD +24 -38
  22. ErisPulse/Core/Bases/manager.py +0 -136
  23. ErisPulse/Core/Bases/manager.pyi +0 -108
  24. ErisPulse/loaders/__init__.py +0 -22
  25. ErisPulse/loaders/__init__.pyi +0 -21
  26. ErisPulse/loaders/adapter_loader.py +0 -187
  27. ErisPulse/loaders/adapter_loader.pyi +0 -82
  28. ErisPulse/loaders/base_loader.py +0 -162
  29. ErisPulse/loaders/base_loader.pyi +0 -23
  30. ErisPulse/loaders/initializer.py +0 -150
  31. ErisPulse/loaders/initializer.pyi +0 -60
  32. ErisPulse/loaders/module_loader.py +0 -618
  33. ErisPulse/loaders/module_loader.pyi +0 -179
  34. ErisPulse/loaders/strategy.py +0 -129
  35. ErisPulse/loaders/strategy.pyi +0 -90
  36. ErisPulse/sdk.py +0 -435
  37. ErisPulse/sdk.pyi +0 -158
  38. {erispulse-2.3.4.dev2.dist-info → erispulse-2.3.4.dev114514.dist-info}/WHEEL +0 -0
  39. {erispulse-2.3.4.dev2.dist-info → erispulse-2.3.4.dev114514.dist-info}/entry_points.txt +0 -0
  40. {erispulse-2.3.4.dev2.dist-info → erispulse-2.3.4.dev114514.dist-info}/licenses/LICENSE +0 -0
@@ -1,618 +0,0 @@
1
- """
2
- ErisPulse 模块加载器
3
-
4
- 专门用于从 PyPI 包加载和初始化普通模块
5
-
6
- {!--< tips >!--}
7
- 1. 模块必须通过 entry-points 机制注册到 erispulse.module 组
8
- 2. 模块类名应与 entry-point 名称一致
9
- 3. 模块支持懒加载机制
10
- {!--< /tips >!--}
11
- """
12
-
13
- import sys
14
- import asyncio
15
- import inspect
16
- import importlib.metadata
17
- from typing import Dict, List, Any, Tuple, Type, TYPE_CHECKING
18
- from .base_loader import BaseLoader
19
- from ..Core.logger import logger
20
- from ..Core.lifecycle import lifecycle
21
-
22
- if TYPE_CHECKING:
23
- from ..Core.Bases.module import BaseModule
24
-
25
- class ModuleLoader(BaseLoader):
26
- """
27
- 模块加载器
28
-
29
- 负责从 PyPI entry-points 加载模块,支持懒加载
30
-
31
- {!--< tips >!--}
32
- 使用方式:
33
- >>> loader = ModuleLoader()
34
- >>> module_objs, enabled, disabled = await loader.load(module_manager)
35
- {!--< /tips >!--}
36
- """
37
-
38
- def __init__(self):
39
- """初始化模块加载器"""
40
- super().__init__("ErisPulse.modules")
41
-
42
- def _get_entry_point_group(self) -> str:
43
- """
44
- 获取 entry-point 组名
45
-
46
- :return: "erispulse.module"
47
- """
48
- return "erispulse.module"
49
-
50
- async def _process_entry_point(
51
- self,
52
- entry_point: Any,
53
- objs: Dict[str, Any],
54
- enabled_list: List[str],
55
- disabled_list: List[str],
56
- manager_instance: Any
57
- ) -> Tuple[Dict[str, Any], List[str], List[str]]:
58
- """
59
- 处理单个模块 entry-point
60
-
61
- :param entry_point: entry-point 对象
62
- :param objs: 模块对象字典
63
- :param enabled_list: 启用的模块列表
64
- :param disabled_list: 停用的模块列表
65
- :param manager_instance: 模块管理器实例
66
-
67
- :return:
68
- Dict[str, Any]: 更新后的模块对象字典
69
- List[str]: 更新后的启用模块列表
70
- List[str]: 更新后的禁用模块列表
71
-
72
- :raises ImportError: 当模块加载失败时抛出
73
- """
74
- meta_name = entry_point.name
75
-
76
- logger.debug(f"正在处理模块: {meta_name}")
77
-
78
- # 检查模块是否已经注册,如果未注册则进行注册(默认启用)
79
- if not manager_instance.exists(meta_name):
80
- manager_instance._config_register(meta_name, True)
81
- logger.info(f"发现新模块 {meta_name},默认已启用。如需禁用,请在配置文件中设置 ErisPulse.modules.status.{meta_name} = false")
82
-
83
- # 获取模块当前状态
84
- module_status = manager_instance.is_enabled(meta_name)
85
- logger.debug(f"模块 {meta_name} 状态: {module_status}")
86
-
87
- if not module_status:
88
- disabled_list.append(meta_name)
89
- return objs, enabled_list, disabled_list
90
-
91
- try:
92
- loaded_obj = entry_point.load()
93
- module_obj = sys.modules[loaded_obj.__module__]
94
- dist = importlib.metadata.distribution(entry_point.dist.name)
95
-
96
- # 检查模块是否继承自 BaseModule
97
- from ..Core.Bases.module import BaseModule
98
- is_base_module = inspect.isclass(loaded_obj) and issubclass(loaded_obj, BaseModule)
99
-
100
- if not is_base_module:
101
- logger.warning(f"模块 {meta_name} 未继承自 BaseModule,"\
102
- "如果你是这个模块的作者,请检查 ErisPulse 的文档更新并尽快迁移!")
103
-
104
- # 获取模块加载策略
105
- strategy = self._get_load_strategy(loaded_obj)
106
- lazy_load = strategy.get('lazy_load', True) if isinstance(strategy, dict) else strategy.lazy_load if 'lazy_load' in strategy else True
107
- priority = strategy.get('priority', 0) if isinstance(strategy, dict) else strategy.priority if 'priority' in strategy else 0
108
-
109
- module_info = {
110
- "meta": {
111
- "name": meta_name,
112
- "version": getattr(module_obj, "__version__", dist.version if dist else "1.0.0"),
113
- "description": getattr(module_obj, "__description__", ""),
114
- "author": getattr(module_obj, "__author__", ""),
115
- "license": getattr(module_obj, "__license__", ""),
116
- "package": entry_point.dist.name,
117
- "lazy_load": lazy_load,
118
- "priority": priority,
119
- "is_base_module": is_base_module
120
- },
121
- "module_class": loaded_obj,
122
- "strategy": strategy
123
- }
124
-
125
- setattr(module_obj, "moduleInfo", module_info)
126
-
127
- objs[meta_name] = module_obj
128
- enabled_list.append(meta_name)
129
- logger.debug(f"从 PyPI 包加载模块: {meta_name}")
130
-
131
- except Exception as e:
132
- logger.warning(f"从 entry-point 加载模块 {meta_name} 失败: {e}")
133
- raise ImportError(f"无法加载模块 {meta_name}: {e}")
134
-
135
- return objs, enabled_list, disabled_list
136
-
137
- def _get_load_strategy(self, module_class: Type) -> Any:
138
- """
139
- 获取模块加载策略
140
-
141
- :param module_class: Type 模块类
142
- :return: 加载策略对象或字典
143
-
144
- {!--< internal-use >!--}
145
- 内部方法,用于获取模块的加载策略
146
- {!--< /internal-use >!--}
147
- """
148
- # 首先检查全局懒加载配置
149
- global_lazy_loading = True
150
- try:
151
- from ..Core._self_config import get_framework_config
152
- framework_config = get_framework_config()
153
- global_lazy_loading = framework_config.get("enable_lazy_loading", True)
154
- except Exception as e:
155
- logger.warning(f"获取框架配置失败: {e},将使用模块默认配置")
156
-
157
- # 检查模块是否定义了 get_load_strategy() 方法
158
- if hasattr(module_class, "get_load_strategy"):
159
- try:
160
- strategy = module_class.get_load_strategy()
161
-
162
- # 如果全局禁用懒加载,则覆盖策略中的 lazy_load 设置
163
- if not global_lazy_loading:
164
- if isinstance(strategy, dict):
165
- strategy = dict(strategy, lazy_load=False)
166
- elif 'lazy_load' in strategy:
167
- strategy = self._strategy_with_lazy_load(strategy, False)
168
-
169
- return strategy
170
- except Exception as e:
171
- logger.warning(f"调用模块 {module_class.__name__} 的 get_load_strategy() 失败: {e}")
172
-
173
- # 检查模块是否定义了 should_eager_load() 方法(兼容旧方法)
174
- if hasattr(module_class, "should_eager_load"):
175
- try:
176
- eager_load = module_class.should_eager_load()
177
- return {"lazy_load": not eager_load, "priority": 0}
178
- except Exception as e:
179
- logger.warning(f"调用模块 {module_class.__name__} 的 should_eager_load() 失败: {e}")
180
-
181
- # 默认策略
182
- return {"lazy_load": global_lazy_loading, "priority": 0}
183
-
184
- def _strategy_with_lazy_load(self, strategy: Any, lazy_load: bool) -> Any:
185
- """
186
- 创建修改 lazy_load 的新策略副本
187
-
188
- :param strategy: 原始策略
189
- :param lazy_load: 懒加载值
190
- :return: 新策略
191
-
192
- {!--< internal-use >!--}
193
- 内部方法,用于创建修改后的策略副本
194
- {!--< /internal-use >!--}
195
- """
196
- # 由于 ModuleLoadStrategy 使用 _data 存储,我们需要创建新实例
197
- from .strategy import ModuleLoadStrategy
198
- data = dict(strategy._data)
199
- data['lazy_load'] = lazy_load
200
- return ModuleLoadStrategy(**data)
201
-
202
- async def register_to_manager(
203
- self,
204
- modules: List[str],
205
- module_objs: Dict[str, Any],
206
- manager_instance: Any
207
- ) -> bool:
208
- """
209
- 将模块类注册到管理器
210
-
211
- :param modules: 模块名称列表
212
- :param module_objs: 模块对象字典
213
- :param manager_instance: 模块管理器实例
214
- :return: 模块注册是否成功
215
-
216
- {!--< tips >!--}
217
- 此方法由初始化协调器调用,仅注册模块类,不进行实例化
218
- {!--< /tips >!--}
219
- """
220
- register_tasks = []
221
-
222
- for module_name in modules:
223
- module_obj = module_objs[module_name]
224
- meta_name = module_obj.moduleInfo["meta"]["name"]
225
-
226
- async def register_module(name: str, obj: Any) -> bool:
227
- """注册单个模块"""
228
- try:
229
- entry_points = importlib.metadata.entry_points()
230
- if hasattr(entry_points, 'select'):
231
- module_entries = entry_points.select(group='erispulse.module')
232
- module_entry_map = {entry.name: entry for entry in module_entries}
233
- else:
234
- module_entries = entry_points.get('erispulse.module', []) # type: ignore[assignment]
235
- module_entry_map = {entry.name: entry for entry in module_entries}
236
-
237
- entry_point = module_entry_map.get(name)
238
- if entry_point:
239
- module_class = entry_point.load()
240
-
241
- # 调用管理器的 register 方法
242
- manager_instance.register(name, module_class, obj.moduleInfo)
243
- logger.debug(f"注册模块类: {name}")
244
- return True
245
- return False
246
- except Exception as e:
247
- logger.error(f"注册模块 {name} 失败: {e}")
248
- return False
249
-
250
- register_tasks.append(register_module(meta_name, module_obj))
251
-
252
- # 等待所有注册任务完成
253
- register_results = await asyncio.gather(*register_tasks, return_exceptions=True)
254
-
255
- # 检查是否有注册失败的情况
256
- return not any(isinstance(result, Exception) or result is False for result in register_results)
257
-
258
- async def initialize_modules(
259
- self,
260
- modules: List[str],
261
- module_objs: Dict[str, Any],
262
- manager_instance: Any,
263
- sdk_instance: Any
264
- ) -> bool:
265
- """
266
- 初始化模块(创建实例并挂载到 SDK)
267
-
268
- :param modules: 模块名称列表
269
- :param module_objs: 模块对象字典
270
- :param manager_instance: 模块管理器实例
271
- :param sdk_instance: SDK 实例
272
- :return: 模块初始化是否成功
273
-
274
- {!--< tips >!--}
275
- 此方法处理模块的实际初始化和挂载
276
- {!--< /tips >!--}
277
-
278
- 并行注册所有模块类(已在 register_to_manager 中完成)
279
- 这里处理模块的实例化和挂载
280
- """
281
- for module_name in modules:
282
- module_obj = module_objs[module_name]
283
- meta_name = module_obj.moduleInfo["meta"]["name"]
284
- lazy_load = module_obj.moduleInfo["meta"].get("lazy_load", True)
285
-
286
- if lazy_load:
287
- # 使用懒加载方式挂载
288
- lazy_module = LazyModule(
289
- meta_name,
290
- module_obj.moduleInfo["module_class"],
291
- sdk_instance,
292
- module_obj.moduleInfo,
293
- manager_instance
294
- )
295
- setattr(sdk_instance, meta_name, lazy_module)
296
- logger.debug(f"挂载懒加载模块到 sdk: {meta_name}")
297
- else:
298
- # 立即加载的模块
299
- result = await manager_instance.load(meta_name)
300
- if result:
301
- setattr(sdk_instance, meta_name, manager_instance.get(meta_name))
302
- logger.debug(f"挂载立即加载模块到 sdk: {meta_name}")
303
- else:
304
- logger.error(f"立即加载模块 {meta_name} 失败")
305
- return False
306
-
307
- return True
308
-
309
- class LazyModule:
310
- """
311
- 懒加载模块包装器
312
-
313
- 当模块第一次被访问时才进行实例化
314
-
315
- {!--< tips >!--}
316
- 1. 模块的实际实例化会在第一次属性访问时进行
317
- 2. 依赖模块会在被使用时自动初始化
318
- 3. 对于继承自 BaseModule 的模块,会自动调用生命周期方法
319
- {!--< /tips >!--}
320
- """
321
-
322
- def __init__(
323
- self,
324
- module_name: str,
325
- module_class: Type,
326
- sdk_ref: Any,
327
- module_info: Dict[str, Any],
328
- manager_instance: Any
329
- ) -> None:
330
- """
331
- 初始化懒加载包装器
332
-
333
- :param module_name: str 模块名称
334
- :param module_class: Type 模块类
335
- :param sdk_ref: Any SDK 引用
336
- :param module_info: Dict[str, Any] 模块信息字典
337
- :param manager_instance: 模块管理器实例
338
- """
339
- object.__setattr__(self, '_module_name', module_name)
340
- object.__setattr__(self, '_module_class', module_class)
341
- object.__setattr__(self, '_sdk_ref', sdk_ref)
342
- object.__setattr__(self, '_module_info', module_info)
343
- object.__setattr__(self, '_instance', None)
344
- object.__setattr__(self, '_initialized', False)
345
- object.__setattr__(self, '_manager_instance', manager_instance)
346
- object.__setattr__(self, '_is_base_module', module_info.get("meta", {}).get("is_base_module", False))
347
-
348
- async def _initialize(self) -> None:
349
- """
350
- 实际初始化模块
351
-
352
- :raises Exception: 当模块初始化失败时抛出
353
-
354
- {!--< internal-use >!--}
355
- 内部方法,执行实际的模块初始化
356
- {!--< /internal-use >!--}
357
- """
358
- if object.__getattribute__(self, '_initialized'):
359
- return
360
-
361
- logger.debug(f"正在初始化懒加载模块 {object.__getattribute__(self, '_module_name')}...")
362
-
363
- try:
364
- # 获取类的 __init__ 参数信息
365
- logger.debug(f"正在获取模块 {object.__getattribute__(self, '_module_name')} 的 __init__ 参数信息...")
366
- init_signature = inspect.signature(object.__getattribute__(self, '_module_class').__init__)
367
- params = init_signature.parameters
368
-
369
- # 根据参数决定是否传入 sdk
370
- if 'sdk' in params:
371
- logger.debug(f"模块 {object.__getattribute__(self, '_module_name')} 需要传入 sdk 参数")
372
- instance = object.__getattribute__(self, '_module_class')(object.__getattribute__(self, '_sdk_ref'))
373
- else:
374
- logger.debug(f"模块 {object.__getattribute__(self, '_module_name')} 不需要传入 sdk 参数")
375
- instance = object.__getattribute__(self, '_module_class')()
376
-
377
- logger.debug(f"正在设置模块 {object.__getattribute__(self, '_module_name')} 的 moduleInfo 属性...")
378
- setattr(instance, "moduleInfo", object.__getattribute__(self, '_module_info'))
379
-
380
- object.__setattr__(self, '_instance', instance)
381
- object.__setattr__(self, '_initialized', True)
382
-
383
- # 如果是 BaseModule 子类,在初始化后调用 on_load 方法
384
- if object.__getattribute__(self, '_is_base_module'):
385
- logger.debug(f"正在调用模块 {object.__getattribute__(self, '_module_name')} 的 on_load 方法...")
386
-
387
- try:
388
- await object.__getattribute__(self, '_manager_instance').load(object.__getattribute__(self, '_module_name'))
389
- except Exception as e:
390
- logger.error(f"调用模块 {object.__getattribute__(self, '_module_name')} 的 on_load 方法时出错: {e}")
391
-
392
- await lifecycle.submit_event(
393
- "module.init",
394
- msg=f"模块 {object.__getattribute__(self, '_module_name')} 初始化完毕",
395
- data={
396
- "module_name": object.__getattribute__(self, '_module_name'),
397
- "success": True,
398
- }
399
- )
400
- logger.debug(f"懒加载模块 {object.__getattribute__(self, '_module_name')} 初始化完成")
401
-
402
- except Exception as e:
403
- await lifecycle.submit_event(
404
- "module.init",
405
- msg=f"模块初始化失败: {e}",
406
- data={
407
- "module_name": object.__getattribute__(self, '_module_name'),
408
- "success": False,
409
- }
410
- )
411
- logger.error(f"懒加载模块 {object.__getattribute__(self, '_module_name')} 初始化失败: {e}")
412
- raise e
413
-
414
- def _ensure_initialized(self) -> None:
415
- """
416
- 确保模块已初始化
417
-
418
- :raises RuntimeError: 当模块需要异步初始化时抛出
419
-
420
- {!--< internal-use >!--}
421
- 内部方法,检查并确保模块已初始化
422
- {!--< /internal-use >!--}
423
- """
424
- if not object.__getattribute__(self, '_initialized'):
425
- try:
426
- loop = asyncio.get_running_loop()
427
- init_method = getattr(object.__getattribute__(self, '_module_class'), '__init__', None)
428
-
429
- if asyncio.iscoroutinefunction(init_method):
430
- object.__setattr__(self, '_needs_async_init', True)
431
- logger.warning(f"模块 {object.__getattribute__(self, '_module_name')} 需要异步初始化,请在异步上下文中调用")
432
- return
433
- else:
434
- self._initialize_sync()
435
-
436
- if object.__getattribute__(self, '_is_base_module'):
437
- try:
438
- loop = asyncio.get_running_loop()
439
- loop.create_task(self._complete_async_init())
440
- except Exception as e:
441
- logger.warning(f"无法调度异步初始化任务: {e}")
442
- except RuntimeError:
443
- asyncio.run(self._initialize())
444
-
445
- def _initialize_sync(self) -> None:
446
- """
447
- 同步初始化模块
448
-
449
- {!--< internal-use >!--}
450
- 内部方法,在同步上下文中初始化模块
451
- {!--< /internal-use >!--}
452
- """
453
- if object.__getattribute__(self, '_initialized'):
454
- return
455
-
456
- logger.debug(f"正在同步初始化懒加载模块 {object.__getattribute__(self, '_module_name')}...")
457
-
458
- try:
459
- init_signature = inspect.signature(object.__getattribute__(self, '_module_class').__init__)
460
- params = init_signature.parameters
461
-
462
- if 'sdk' in params:
463
- instance = object.__getattribute__(self, '_module_class')(object.__getattribute__(self, '_sdk_ref'))
464
- else:
465
- instance = object.__getattribute__(self, '_module_class')()
466
-
467
- setattr(instance, "moduleInfo", object.__getattribute__(self, '_module_info'))
468
- object.__setattr__(self, '_instance', instance)
469
- object.__setattr__(self, '_initialized', True)
470
-
471
- logger.debug(f"懒加载模块 {object.__getattribute__(self, '_module_name')} 同步初始化完成")
472
-
473
- except Exception as e:
474
- logger.error(f"懒加载模块 {object.__getattribute__(self, '_module_name')} 同步初始化失败: {e}")
475
- raise e
476
-
477
- async def _complete_async_init(self) -> None:
478
- """
479
- 完成异步初始化部分
480
-
481
- {!--< internal-use >!--}
482
- 内部方法,处理模块的异步初始化部分
483
- {!--< /internal-use >!--}
484
- """
485
- if not object.__getattribute__(self, '_initialized'):
486
- return
487
-
488
- try:
489
- if object.__getattribute__(self, '_is_base_module'):
490
- logger.debug(f"正在异步调用模块 {object.__getattribute__(self, '_module_name')} 的 on_load 方法...")
491
-
492
- try:
493
- await object.__getattribute__(self, '_manager_instance').load(object.__getattribute__(self, '_module_name'))
494
- except Exception as e:
495
- logger.error(f"异步调用模块 {object.__getattribute__(self, '_module_name')} 的 on_load 方法时出错: {e}")
496
-
497
- await lifecycle.submit_event(
498
- "module.init",
499
- msg=f"模块 {object.__getattribute__(self, '_module_name')} 初始化完毕",
500
- data={
501
- "module_name": object.__getattribute__(self, '_module_name'),
502
- "success": True,
503
- }
504
- )
505
- logger.debug(f"懒加载模块 {object.__getattribute__(self, '_module_name')} 异步初始化部分完成")
506
- except Exception as e:
507
- await lifecycle.submit_event(
508
- "module.init",
509
- msg=f"模块初始化失败: {e}",
510
- data={
511
- "module_name": object.__getattribute__(self, '_module_name'),
512
- "success": False,
513
- }
514
- )
515
- logger.error(f"懒加载模块 {object.__getattribute__(self, '_module_name')} 异步初始化部分失败: {e}")
516
-
517
- def __getattr__(self, name: str) -> Any:
518
- """
519
- 属性访问时触发初始化
520
-
521
- :param name: str 属性名
522
- :return: Any 属性值
523
- """
524
- logger.debug(f"正在访问懒加载模块 {object.__getattribute__(self, '_module_name')} 的属性 {name}...")
525
-
526
- if hasattr(self, '_needs_async_init') and object.__getattribute__(self, '_needs_async_init'):
527
- raise RuntimeError(
528
- f"模块 {object.__getattribute__(self, '_module_name')} 需要异步初始化,"
529
- f"请使用 'await sdk.load_module(\"{object.__getattribute__(self, '_module_name')}\")' 来初始化模块"
530
- )
531
-
532
- self._ensure_initialized()
533
- return getattr(object.__getattribute__(self, '_instance'), name)
534
-
535
- def __setattr__(self, name: str, value: Any) -> None:
536
- """
537
- 属性设置
538
-
539
- :param name: str 属性名
540
- :param value: Any 属性值
541
- """
542
- logger.debug(f"正在设置懒加载模块 {object.__getattribute__(self, '_module_name')} 的属性 {name}...")
543
-
544
- if name.startswith('_') or name in ('moduleInfo',):
545
- object.__setattr__(self, name, value)
546
- else:
547
- if name == '_instance' or not hasattr(self, '_initialized') or not object.__getattribute__(self, '_initialized'):
548
- object.__setattr__(self, name, value)
549
- else:
550
- setattr(object.__getattribute__(self, '_instance'), name, value)
551
-
552
- def __delattr__(self, name: str) -> None:
553
- """
554
- 属性删除
555
-
556
- :param name: str 属性名
557
- """
558
- logger.debug(f"正在删除懒加载模块 {object.__getattribute__(self, '_module_name')} 的属性 {name}...")
559
- self._ensure_initialized()
560
- delattr(object.__getattribute__(self, '_instance'), name)
561
-
562
- def __getattribute__(self, name: str) -> Any:
563
- """
564
- 属性访问,初始化后直接委托给实际实例
565
-
566
- :param name: str 属性名
567
- :return: Any 属性值
568
- """
569
- if name.startswith('_') or name in ('moduleInfo',):
570
- return object.__getattribute__(self, name)
571
-
572
- try:
573
- initialized = object.__getattribute__(self, '_initialized')
574
- except AttributeError:
575
- return object.__getattribute__(self, name)
576
-
577
- if not initialized:
578
- self._ensure_initialized()
579
- initialized = object.__getattribute__(self, '_initialized')
580
-
581
- if initialized:
582
- instance = object.__getattribute__(self, '_instance')
583
- return getattr(instance, name)
584
- else:
585
- return object.__getattribute__(self, name)
586
-
587
- def __dir__(self) -> List[str]:
588
- """
589
- 返回模块属性列表
590
-
591
- :return: List[str] 属性列表
592
- """
593
- logger.debug(f"正在获取懒加载模块 {object.__getattribute__(self, '_module_name')} 的属性列表...")
594
- self._ensure_initialized()
595
- return dir(object.__getattribute__(self, '_instance'))
596
-
597
- def __repr__(self) -> str:
598
- """
599
- 返回模块表示字符串
600
-
601
- :return: str 表示字符串
602
- """
603
- logger.debug(f"正在获取懒加载模块 {object.__getattribute__(self, '_module_name')} 的表示字符串...")
604
- if object.__getattribute__(self, '_initialized'):
605
- return repr(object.__getattribute__(self, '_instance'))
606
- return f"<LazyModule {object.__getattribute__(self, '_module_name')} (not initialized)>"
607
-
608
- def __call__(self, *args, **kwargs):
609
- """
610
- 代理函数调用
611
-
612
- :param args: 位置参数
613
- :param kwargs: 关键字参数
614
- :return: 调用结果
615
- """
616
- self._ensure_initialized()
617
- instance = object.__getattribute__(self, '_instance')
618
- return instance(*args, **kwargs)