Skip to content

Commit

Permalink
Fix type hinting in PyCharm
Browse files Browse the repository at this point in the history
  • Loading branch information
RB387 committed Nov 8, 2024
1 parent 4355b16 commit bee776d
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 21 deletions.
4 changes: 2 additions & 2 deletions src/magic_di/fastapi/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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")
37 changes: 18 additions & 19 deletions src/magic_di/fastapi/_provide.py
Original file line number Diff line number Diff line change
Expand Up @@ -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]

0 comments on commit bee776d

Please sign in to comment.