From bee776d52de41e2dbbe93f94a2f8cf66c24cf8d4 Mon Sep 17 00:00:00 2001 From: Nikita Zavadin Date: Fri, 8 Nov 2024 21:25:49 +0100 Subject: [PATCH] Fix type hinting in PyCharm --- src/magic_di/fastapi/__init__.py | 4 ++-- src/magic_di/fastapi/_provide.py | 37 ++++++++++++++++---------------- 2 files changed, 20 insertions(+), 21 deletions(-) diff --git a/src/magic_di/fastapi/__init__.py b/src/magic_di/fastapi/__init__.py index a29c2b5..1594aef 100644 --- a/src/magic_di/fastapi/__init__.py +++ b/src/magic_di/fastapi/__init__.py @@ -3,6 +3,6 @@ """ from ._app import inject_app -from ._provide import Provide, Provider # type: ignore[attr-defined] +from ._provide import Provide # type: ignore[attr-defined] -__all__ = ("inject_app", "Provide", "Provider") +__all__ = ("inject_app", "Provide") diff --git a/src/magic_di/fastapi/_provide.py b/src/magic_di/fastapi/_provide.py index 8bd5459..fbe7bb4 100644 --- a/src/magic_di/fastapi/_provide.py +++ b/src/magic_di/fastapi/_provide.py @@ -16,26 +16,25 @@ class FastAPIInjectionError(Exception): ... -class Provider: - def __getitem__(self, obj: type[T]) -> type[T]: - @lru_cache(maxsize=1) - def get_dependency(injector: DependencyInjector) -> T: - return injector.inject(obj)() - - def inject(request: Request) -> T: - if not hasattr(request.app.state, "dependency_injector"): - error_msg = ( - "FastAPI application is not injected. Did you forget to add `inject_app(app)`?" - ) - raise FastAPIInjectionError(error_msg) +if TYPE_CHECKING: + from typing import Union as Provide # hack for mypy # noqa: FIX004 +else: - injector = request.app.state.dependency_injector - return get_dependency(injector) + class Provide: + def __class_getitem__(cls, obj: T) -> T: + @lru_cache(maxsize=1) + def get_dependency(injector: DependencyInjector) -> T: + return injector.inject(obj)() - return Annotated[obj, Depends(inject), Injectable] # type: ignore[return-value] + def inject(request: Request) -> T: + if not hasattr(request.app.state, "dependency_injector"): + error_msg = ( + "FastAPI application is not injected. " + "Did you forget to add `inject_app(app)`?" + ) + raise FastAPIInjectionError(error_msg) + injector = request.app.state.dependency_injector + return get_dependency(injector) -if TYPE_CHECKING: - from typing import Union as Provide # hack for mypy # noqa: FIX004 -else: - Provide = Provider() + return Annotated[obj, Depends(inject), Injectable] # type: ignore[return-value]