From 760ac693c0ab8a17e2a3161c44d5cee595e29078 Mon Sep 17 00:00:00 2001 From: yanyongyu Date: Sun, 21 Nov 2021 16:12:36 +0800 Subject: [PATCH] :fire: remove dependency override provider --- nonebot/config.py | 3 +-- nonebot/dependencies/__init__.py | 18 +------------- nonebot/dependencies/models.py | 2 +- nonebot/drivers/__init__.py | 5 ---- nonebot/handler.py | 6 +---- nonebot/matcher.py | 7 ++---- nonebot/message.py | 24 +++++-------------- nonebot/permission.py | 10 +++----- nonebot/plugins/echo.py | 2 +- nonebot/plugins/single_session.py | 6 ++--- nonebot/py.typed | 1 - nonebot/rule.py | 12 ++++------ nonebot/typing.py | 4 ++-- .../nonebot/adapters/cqhttp/event.py | 5 ++-- .../nonebot/adapters/cqhttp/exception.py | 13 ++++++---- 15 files changed, 35 insertions(+), 83 deletions(-) diff --git a/nonebot/config.py b/nonebot/config.py index 05baf53b..82fca0d3 100644 --- a/nonebot/config.py +++ b/nonebot/config.py @@ -67,8 +67,7 @@ class CustomEnvSettings(EnvSettingsSource): env_val = settings.__config__.json_loads(env_val) except ValueError as e: raise SettingsError( - f'error parsing JSON for "{env_name}"' # type: ignore - ) from e + f'error parsing JSON for "{env_name}"') from e d[field.alias] = env_val if env_file_vars: diff --git a/nonebot/dependencies/__init__.py b/nonebot/dependencies/__init__.py index f863d5d9..7d0138a8 100644 --- a/nonebot/dependencies/__init__.py +++ b/nonebot/dependencies/__init__.py @@ -121,7 +121,6 @@ async def solve_dependencies( _dependent: Dependent, _stack: Optional[AsyncExitStack] = None, _sub_dependents: Optional[List[Dependent]] = None, - _dependency_overrides_provider: Optional[Any] = None, _dependency_cache: Optional[T_DependencyCache] = None, **params: Any) -> Tuple[Dict[str, Any], T_DependencyCache]: values: Dict[str, Any] = {} @@ -136,24 +135,9 @@ async def solve_dependencies( sub_dependent.cache_key) func = sub_dependent.func - # dependency overrides - use_sub_dependant = sub_dependent - if (_dependency_overrides_provider and hasattr( - _dependency_overrides_provider, "dependency_overrides")): - original_call = sub_dependent.func - func = getattr(_dependency_overrides_provider, - "dependency_overrides", - {}).get(original_call, original_call) - use_sub_dependant = get_dependent( - func=func, - name=sub_dependent.name, - allow_types=sub_dependent.allow_types, - ) - # solve sub dependency with current cache solved_result = await solve_dependencies( - _dependent=use_sub_dependant, - _dependency_overrides_provider=_dependency_overrides_provider, + _dependent=sub_dependent, _dependency_cache=dependency_cache, **params) sub_values, sub_dependency_cache = solved_result diff --git a/nonebot/dependencies/models.py b/nonebot/dependencies/models.py index 4431d11c..36ee5af0 100644 --- a/nonebot/dependencies/models.py +++ b/nonebot/dependencies/models.py @@ -1,6 +1,6 @@ import abc import inspect -from typing import Any, List, Type, Callable, Optional +from typing import Any, List, Type, Optional from pydantic.fields import FieldInfo, ModelField diff --git a/nonebot/drivers/__init__.py b/nonebot/drivers/__init__.py index 74c42ff6..d08f6b0c 100644 --- a/nonebot/drivers/__init__.py +++ b/nonebot/drivers/__init__.py @@ -40,11 +40,6 @@ class Driver(abc.ABC): :类型: ``Set[T_BotDisconnectionHook]`` :说明: Bot 连接断开时执行的函数 """ - dependency_overrides: Dict[Callable[..., Any], Callable[..., Any]] = {} - """ - :类型: ``Dict[Callable[..., Any], Callable[..., Any]]`` - :说明: Depends 函数的替换表 - """ def __init__(self, env: Env, config: Config): """ diff --git a/nonebot/handler.py b/nonebot/handler.py index a39003b1..6203bebd 100644 --- a/nonebot/handler.py +++ b/nonebot/handler.py @@ -23,8 +23,7 @@ class Handler: *, name: Optional[str] = None, dependencies: Optional[List[DependsWrapper]] = None, - allow_types: Optional[List[Type[Param]]] = None, - dependency_overrides_provider: Optional[Any] = None): + allow_types: Optional[List[Type[Param]]] = None): """ :说明: @@ -36,7 +35,6 @@ class Handler: * ``name: Optional[str]``: 事件处理器名称。默认为函数名。 * ``dependencies: Optional[List[DependsWrapper]]``: 额外的非参数依赖注入。 * ``allow_types: Optional[List[Type[Param]]]``: 允许的参数类型。 - * ``dependency_overrides_provider: Optional[Any]``: 依赖注入覆盖提供者。 """ self.func = func """ @@ -63,7 +61,6 @@ class Handler: if dependencies: for depends in dependencies: self.cache_dependent(depends) - self.dependency_overrides_provider = dependency_overrides_provider self.dependent = get_dependent(func=func, allow_types=self.allow_types) def __repr__(self) -> str: @@ -87,7 +84,6 @@ class Handler: self.sub_dependents[dependency.dependency] # type: ignore for dependency in self.dependencies ], - _dependency_overrides_provider=self.dependency_overrides_provider, _dependency_cache=_dependency_cache, **params) diff --git a/nonebot/matcher.py b/nonebot/matcher.py index f68c78de..7eeda5ab 100644 --- a/nonebot/matcher.py +++ b/nonebot/matcher.py @@ -13,10 +13,10 @@ from contextlib import AsyncExitStack from typing import (TYPE_CHECKING, Any, Dict, List, Type, Union, Callable, NoReturn, Optional) +from nonebot import params from nonebot.rule import Rule from nonebot.log import logger from nonebot.handler import Handler -from nonebot import params, get_driver from nonebot.dependencies import DependsWrapper from nonebot.permission import USER, Permission from nonebot.adapters import (Bot, Event, Message, MessageSegment, @@ -238,9 +238,7 @@ class Matcher(metaclass=MatcherMeta): permission or Permission(), "handlers": [ handler if isinstance(handler, Handler) else Handler( - handler, - dependency_overrides_provider=get_driver(), - allow_types=cls.HANDLER_PARAM_TYPES) + handler, allow_types=cls.HANDLER_PARAM_TYPES) for handler in handlers ] if handlers else [], "temp": @@ -372,7 +370,6 @@ class Matcher(metaclass=MatcherMeta): dependencies: Optional[List[DependsWrapper]] = None) -> Handler: handler_ = Handler(handler, dependencies=dependencies, - dependency_overrides_provider=get_driver(), allow_types=cls.HANDLER_PARAM_TYPES) cls.handlers.append(handler_) return handler_ diff --git a/nonebot/message.py b/nonebot/message.py index 3c00423b..bedf778c 100644 --- a/nonebot/message.py +++ b/nonebot/message.py @@ -8,13 +8,13 @@ NoneBot 内部处理并按优先级分发事件给所有事件响应器,提供 import asyncio from datetime import datetime from contextlib import AsyncExitStack -from typing import TYPE_CHECKING, Any, Set, Dict, Type, Callable, Optional +from typing import TYPE_CHECKING, Any, Set, Dict, Type, Optional +from nonebot import params from nonebot.log import logger from nonebot.rule import TrieRule from nonebot.handler import Handler from nonebot.utils import escape_tag -from nonebot import params, get_driver from nonebot.matcher import Matcher, matchers from nonebot.exception import NoLogException, StopPropagation, IgnoredException from nonebot.typing import (T_State, T_DependencyCache, T_RunPreProcessor, @@ -45,10 +45,7 @@ def event_preprocessor(func: T_EventPreProcessor) -> T_EventPreProcessor: 事件预处理。装饰一个函数,使它在每次接收到事件并分发给各响应器之前执行。 """ - _event_preprocessors.add( - Handler(func, - allow_types=EVENT_PCS_PARAMS, - dependency_overrides_provider=get_driver())) + _event_preprocessors.add(Handler(func, allow_types=EVENT_PCS_PARAMS)) return func @@ -58,10 +55,7 @@ def event_postprocessor(func: T_EventPostProcessor) -> T_EventPostProcessor: 事件后处理。装饰一个函数,使它在每次接收到事件并分发给各响应器之后执行。 """ - _event_postprocessors.add( - Handler(func, - allow_types=EVENT_PCS_PARAMS, - dependency_overrides_provider=get_driver())) + _event_postprocessors.add(Handler(func, allow_types=EVENT_PCS_PARAMS)) return func @@ -71,10 +65,7 @@ def run_preprocessor(func: T_RunPreProcessor) -> T_RunPreProcessor: 运行预处理。装饰一个函数,使它在每次事件响应器运行前执行。 """ - _run_preprocessors.add( - Handler(func, - allow_types=RUN_PREPCS_PARAMS, - dependency_overrides_provider=get_driver())) + _run_preprocessors.add(Handler(func, allow_types=RUN_PREPCS_PARAMS)) return func @@ -84,10 +75,7 @@ def run_postprocessor(func: T_RunPostProcessor) -> T_RunPostProcessor: 运行后处理。装饰一个函数,使它在每次事件响应器运行后执行。 """ - _run_postprocessors.add( - Handler(func, - allow_types=RUN_POSTPCS_PARAMS, - dependency_overrides_provider=get_driver())) + _run_postprocessors.add(Handler(func, allow_types=RUN_POSTPCS_PARAMS)) return func diff --git a/nonebot/permission.py b/nonebot/permission.py index 48781e32..e52058cb 100644 --- a/nonebot/permission.py +++ b/nonebot/permission.py @@ -2,7 +2,7 @@ r""" 权限 ==== -每个 ``Matcher`` 拥有一个 ``Permission`` ,其中是 **异步** ``PermissionChecker`` 的集合,只要有一个 ``PermissionChecker`` 检查结果为 ``True`` 时就会继续运行。 +每个 ``Matcher`` 拥有一个 ``Permission`` ,其中是 ``PermissionChecker`` 的集合,只要有一个 ``PermissionChecker`` 检查结果为 ``True`` 时就会继续运行。 \:\:\:tip 提示 ``PermissionChecker`` 既可以是 async function 也可以是 sync function @@ -41,9 +41,7 @@ class Permission: params.BotParam, params.EventParam ] - def __init__(self, - *checkers: Union[T_PermissionChecker, Handler], - dependency_overrides_provider: Optional[Any] = None) -> None: + def __init__(self, *checkers: Union[T_PermissionChecker, Handler]) -> None: """ :参数: @@ -52,9 +50,7 @@ class Permission: self.checkers = set( checker if isinstance(checker, Handler) else Handler( - checker, - allow_types=self.HANDLER_PARAM_TYPES, - dependency_overrides_provider=dependency_overrides_provider) + checker, allow_types=self.HANDLER_PARAM_TYPES) for checker in checkers) """ :说明: diff --git a/nonebot/plugins/echo.py b/nonebot/plugins/echo.py index 440aa4bf..763fd715 100644 --- a/nonebot/plugins/echo.py +++ b/nonebot/plugins/echo.py @@ -26,4 +26,4 @@ echo = on_command("echo", to_me()) @echo.handle() async def echo_escape(event: MessageEvent): - await say.send(message=event.get_message()) + await echo.send(message=event.get_message()) diff --git a/nonebot/plugins/single_session.py b/nonebot/plugins/single_session.py index 81a9a9d1..7bb4d52e 100644 --- a/nonebot/plugins/single_session.py +++ b/nonebot/plugins/single_session.py @@ -1,8 +1,6 @@ -from typing import Dict, Optional +from typing import Dict -from nonebot.typing import T_State -from nonebot.matcher import Matcher -from nonebot.adapters import Bot, Event +from nonebot.adapters import Event from nonebot.message import (IgnoredException, run_preprocessor, run_postprocessor) diff --git a/nonebot/py.typed b/nonebot/py.typed index 8b137891..e69de29b 100644 --- a/nonebot/py.typed +++ b/nonebot/py.typed @@ -1 +0,0 @@ - diff --git a/nonebot/rule.py b/nonebot/rule.py index 177b59d7..1621aef6 100644 --- a/nonebot/rule.py +++ b/nonebot/rule.py @@ -2,10 +2,10 @@ r""" 规则 ==== -每个事件响应器 ``Matcher`` 拥有一个匹配规则 ``Rule`` ,其中是 **异步** ``RuleChecker`` 的集合,只有当所有 ``RuleChecker`` 检查结果为 ``True`` 时继续运行。 +每个事件响应器 ``Matcher`` 拥有一个匹配规则 ``Rule`` ,其中是 ``RuleChecker`` 的集合,只有当所有 ``RuleChecker`` 检查结果为 ``True`` 时继续运行。 \:\:\:tip 提示 -``RuleChecker`` 既可以是 async function 也可以是 sync function,但在最终会被 ``nonebot.utils.run_sync`` 转换为 async function +``RuleChecker`` 既可以是 async function 也可以是 sync function \:\:\: """ @@ -68,9 +68,7 @@ class Rule: params.BotParam, params.EventParam, params.StateParam ] - def __init__(self, - *checkers: Union[T_RuleChecker, Handler], - dependency_overrides_provider: Optional[Any] = None) -> None: + def __init__(self, *checkers: Union[T_RuleChecker, Handler]) -> None: """ :参数: @@ -79,9 +77,7 @@ class Rule: """ self.checkers = set( checker if isinstance(checker, Handler) else Handler( - checker, - allow_types=self.HANDLER_PARAM_TYPES, - dependency_overrides_provider=dependency_overrides_provider) + checker, allow_types=self.HANDLER_PARAM_TYPES) for checker in checkers) """ :说明: diff --git a/nonebot/typing.py b/nonebot/typing.py index ac5a2335..3394cd6f 100644 --- a/nonebot/typing.py +++ b/nonebot/typing.py @@ -17,7 +17,7 @@ .. _typing: https://docs.python.org/3/library/typing.html """ -from collections.abc import Callable as BaseCallable + from typing import (TYPE_CHECKING, Any, Dict, Union, TypeVar, Callable, NoReturn, Optional, Awaitable) @@ -25,7 +25,7 @@ if TYPE_CHECKING: from nonebot.adapters import Bot, Event from nonebot.permission import Permission -T_Wrapped = TypeVar("T_Wrapped", bound=BaseCallable) +T_Wrapped = TypeVar("T_Wrapped", bound=Callable) def overrides(InterfaceClass: object): diff --git a/packages/nonebot-adapter-cqhttp/nonebot/adapters/cqhttp/event.py b/packages/nonebot-adapter-cqhttp/nonebot/adapters/cqhttp/event.py index cfa61315..690a8437 100644 --- a/packages/nonebot-adapter-cqhttp/nonebot/adapters/cqhttp/event.py +++ b/packages/nonebot-adapter-cqhttp/nonebot/adapters/cqhttp/event.py @@ -5,13 +5,12 @@ from typing import TYPE_CHECKING, List, Type, Optional from pydantic import BaseModel from pygtrie import StringTrie +from .message import Message from nonebot.typing import overrides from nonebot.utils import escape_tag -from nonebot.exception import NoLogException +from .exception import NoLogException from nonebot.adapters import Event as BaseEvent -from .message import Message - if TYPE_CHECKING: from .bot import Bot diff --git a/packages/nonebot-adapter-cqhttp/nonebot/adapters/cqhttp/exception.py b/packages/nonebot-adapter-cqhttp/nonebot/adapters/cqhttp/exception.py index af3ae6cd..4d3fd1e9 100644 --- a/packages/nonebot-adapter-cqhttp/nonebot/adapters/cqhttp/exception.py +++ b/packages/nonebot-adapter-cqhttp/nonebot/adapters/cqhttp/exception.py @@ -1,9 +1,10 @@ from typing import Optional -from nonebot.exception import (AdapterException, ActionFailed as - BaseActionFailed, NetworkError as - BaseNetworkError, ApiNotAvailable as - BaseApiNotAvailable) +from nonebot.exception import AdapterException +from nonebot.exception import ActionFailed as BaseActionFailed +from nonebot.exception import NetworkError as BaseNetworkError +from nonebot.exception import NoLogException as BaseNoLogException +from nonebot.exception import ApiNotAvailable as BaseApiNotAvailable class CQHTTPAdapterException(AdapterException): @@ -12,6 +13,10 @@ class CQHTTPAdapterException(AdapterException): super().__init__("cqhttp") +class NoLogException(BaseNoLogException, CQHTTPAdapterException): + pass + + class ActionFailed(BaseActionFailed, CQHTTPAdapterException): """ :说明: