Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 24 additions & 9 deletions injection/integrations/fastapi.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
from collections.abc import Callable
from typing import Any
from types import GenericAlias
from typing import Any, TypeAliasType

from injection import Module, mod
from injection.exceptions import InjectionError
Expand All @@ -11,27 +12,41 @@
from fastapi import Depends


def Inject[T](cls: type[T] | Any, /, module: Module | None = None) -> Any: # noqa: N802
def Inject[T]( # noqa: N802
cls: type[T] | TypeAliasType | GenericAlias,
/,
module: Module | None = None,
*,
scoped: bool = True,
) -> Any:
"""
Declare a FastAPI dependency with `python-injection`.
"""

dependency: InjectionDependency[T] = InjectionDependency(cls, module or mod())
return Depends(dependency)
return Depends(dependency, use_cache=scoped)


class InjectionDependency[T]:
__slots__ = ("__call__",)
__slots__ = ("__call__", "__class")

__call__: Callable[[], T]
__class: type[T] | TypeAliasType | GenericAlias

def __init__(self, cls: type[T] | Any, module: Module):
def __init__(self, cls: type[T] | TypeAliasType | GenericAlias, module: Module):
lazy_instance = module.get_lazy_instance(cls)
self.__call__ = lambda: self.__ensure(~lazy_instance, cls)
self.__call__ = lambda: self.__ensure(~lazy_instance)
self.__class = cls

@staticmethod
def __ensure[_T](instance: _T | None, cls: type[_T] | Any) -> _T:
def __eq__(self, other: Any) -> bool:
cls = type(self)
return isinstance(other, cls) and hash(self) == hash(other)

def __hash__(self) -> int:
return hash((self.__class,))

def __ensure(self, instance: T | None) -> T:
if instance is None:
raise InjectionError(f"`{cls}` is an unknown dependency.")
raise InjectionError(f"`{self.__class}` is an unknown dependency.")

return instance
Loading