perf(methods): 通过移除不必要的 self 参数优化方法签名

在包括 chat、plugin_system、schedule 和 mais4u 在内的多个模块中,消除冗余的实例引用。此次改动将无需访问实例状态的实用函数转换为静态方法,从而提升了内存效率,并使方法依赖关系更加清晰。
This commit is contained in:
雅诺狐
2025-09-20 10:55:06 +08:00
parent 0cc4f5bb27
commit 898208f425
111 changed files with 643 additions and 467 deletions

View File

@@ -31,6 +31,7 @@ class ComponentRegistry:
def __init__(self):
# 命名空间式组件名构成法 f"{component_type}.{component_name}"
self._plus_command_registry: Dict[str, Type[PlusCommand]] = {}
self._components: Dict[str, ComponentInfo] = {}
"""组件注册表 命名空间式组件名 -> 组件信息"""
self._components_by_type: Dict[ComponentType, Dict[str, ComponentInfo]] = {types: {} for types in ComponentType}
@@ -618,7 +619,7 @@ class ComponentRegistry:
def get_plus_command_registry(self) -> Dict[str, Type[PlusCommand]]:
"""获取PlusCommand注册表"""
if not hasattr(self, "_plus_command_registry"):
self._plus_command_registry: Dict[str, Type[PlusCommand]] = {}
pass
return self._plus_command_registry.copy()
def get_registered_plus_command_info(self, command_name: str) -> Optional[PlusCommandInfo]:
@@ -667,7 +668,8 @@ class ComponentRegistry:
plugin_info = self.get_plugin_info(plugin_name)
return plugin_info.components if plugin_info else []
def get_plugin_config(self, plugin_name: str) -> dict:
@staticmethod
def get_plugin_config(plugin_name: str) -> dict:
"""获取插件配置
Args:

View File

@@ -7,6 +7,7 @@ from typing import Dict, Type, List, Optional, Any, Union
from threading import Lock
from src.common.logger import get_logger
from src.plugin_system import BaseEventHandler
from src.plugin_system.base.base_event import BaseEvent, HandlerResultsCollection
from src.plugin_system.base.base_events_handler import BaseEventHandler
from src.plugin_system.base.component_types import EventType
@@ -198,7 +199,7 @@ class EventManager:
"""
return self._event_handlers.get(handler_name)
def get_all_event_handlers(self) -> Dict[str, BaseEventHandler]:
def get_all_event_handlers(self) -> dict[str, type[BaseEventHandler]]:
"""获取所有已注册的事件处理器
Returns:

View File

@@ -290,7 +290,8 @@ class PluginHotReloadManager:
logger.error(f"❌ 重载插件 {plugin_name} 时发生错误: {e}", exc_info=True)
return False
def _resolve_plugin_name(self, folder_name: str) -> str:
@staticmethod
def _resolve_plugin_name(folder_name: str) -> str:
"""
将文件夹名称解析为实际的插件名称
通过检查插件管理器中的路径映射来找到对应的插件名
@@ -349,7 +350,8 @@ class PluginHotReloadManager:
# 出错时尝试简单重载
return self._reload_plugin(plugin_name)
def _force_clear_plugin_modules(self, plugin_name: str):
@staticmethod
def _force_clear_plugin_modules(plugin_name: str):
"""强制清理插件相关的模块缓存"""
# 找到所有相关的模块名
@@ -366,7 +368,8 @@ class PluginHotReloadManager:
logger.debug(f"🗑️ 清理模块缓存: {module_name}")
del sys.modules[module_name]
def _force_reimport_plugin(self, plugin_name: str):
@staticmethod
def _force_reimport_plugin(plugin_name: str):
"""强制重新导入插件(委托给插件管理器)"""
try:
# 使用插件管理器的重载功能
@@ -377,7 +380,8 @@ class PluginHotReloadManager:
logger.error(f"❌ 强制重新导入插件 {plugin_name} 时发生错误: {e}", exc_info=True)
return False
def _unload_plugin(self, plugin_name: str):
@staticmethod
def _unload_plugin(plugin_name: str):
"""卸载指定插件"""
try:
logger.info(f"🗑️ 开始卸载插件: {plugin_name}")
@@ -490,7 +494,8 @@ class PluginHotReloadManager:
"debounce_delay": self.file_handlers[0].debounce_delay if self.file_handlers else 0,
}
def clear_all_caches(self):
@staticmethod
def clear_all_caches():
"""清理所有Python模块缓存"""
try:
logger.info("🧹 开始清理所有Python模块缓存...")

View File

@@ -67,7 +67,8 @@ class PluginManager:
except Exception as e:
logger.error(f"同步插件 '{plugin_name}' 配置时发生未知错误: {e}")
def _copy_default_config_to_central(self, plugin_name: str, plugin_config_file: Path, central_config_dir: Path):
@staticmethod
def _copy_default_config_to_central(plugin_name: str, plugin_config_file: Path, central_config_dir: Path):
"""
如果中央配置不存在,则将插件的默认 config.toml 复制到中央目录。
"""
@@ -96,7 +97,8 @@ class PluginManager:
shutil.copy2(central_file, target_plugin_file)
logger.info(f"已将中央配置 '{central_file.name}' 同步到插件 '{plugin_name}'")
def _is_file_content_identical(self, file1: Path, file2: Path) -> bool:
@staticmethod
def _is_file_content_identical(file1: Path, file2: Path) -> bool:
"""
通过比较 MD5 哈希值检查两个文件的内容是否相同。
"""
@@ -403,7 +405,8 @@ class PluginManager:
# == 兼容性检查 ==
def _check_plugin_version_compatibility(self, plugin_name: str, manifest_data: Dict[str, Any]) -> Tuple[bool, str]:
@staticmethod
def _check_plugin_version_compatibility(plugin_name: str, manifest_data: Dict[str, Any]) -> Tuple[bool, str]:
"""检查插件版本兼容性
Args:
@@ -557,7 +560,8 @@ class PluginManager:
else:
logger.warning("😕 没有成功加载任何插件")
def _show_plugin_components(self, plugin_name: str) -> None:
@staticmethod
def _show_plugin_components(plugin_name: str) -> None:
if plugin_info := component_registry.get_plugin_info(plugin_name):
component_types = {}
for comp in plugin_info.components:
@@ -673,7 +677,8 @@ class PluginManager:
"""
return self.reload_plugin(plugin_name)
def clear_all_plugin_caches(self):
@staticmethod
def clear_all_plugin_caches():
"""清理所有插件相关的模块缓存(简化版)"""
try:
logger.info("🧹 清理模块缓存...")