|
1 | 1 | from types import GenericAlias |
2 | | -from typing import Any, TypeAliasType |
| 2 | +from typing import TYPE_CHECKING, Annotated, Any, TypeAliasType |
3 | 3 |
|
4 | 4 | from fastapi import Depends |
5 | 5 |
|
|
8 | 8 | __all__ = ("Inject",) |
9 | 9 |
|
10 | 10 |
|
11 | | -def Inject[T]( # noqa: N802 |
12 | | - cls: type[T] | TypeAliasType | GenericAlias, |
13 | | - /, |
14 | | - default: T = NotImplemented, |
15 | | - module: Module | None = None, |
16 | | -) -> Any: |
17 | | - """ |
18 | | - Declare a FastAPI dependency with `python-injection`. |
19 | | - """ |
| 11 | +class FastAPIInject: |
| 12 | + __slots__ = () |
20 | 13 |
|
21 | | - module = module or mod() |
22 | | - lazy_instance = module.aget_lazy_instance(cls, default) |
| 14 | + def __call__[T]( |
| 15 | + self, |
| 16 | + cls: type[T] | TypeAliasType | GenericAlias, |
| 17 | + /, |
| 18 | + default: T = NotImplemented, |
| 19 | + module: Module | None = None, |
| 20 | + ) -> Any: |
| 21 | + module = module or mod() |
| 22 | + lazy_instance = module.aget_lazy_instance(cls, default) |
23 | 23 |
|
24 | | - async def getter() -> T: |
25 | | - return await lazy_instance |
| 24 | + async def getter() -> T: |
| 25 | + return await lazy_instance |
26 | 26 |
|
27 | | - return Depends(getter, use_cache=False) |
| 27 | + return Depends(getter, use_cache=False) |
| 28 | + |
| 29 | + def __getitem__(self, params: Any, /) -> Any: |
| 30 | + if not isinstance(params, tuple): |
| 31 | + params = (params,) |
| 32 | + |
| 33 | + iter_params = iter(params) |
| 34 | + cls = next(iter_params) |
| 35 | + return Annotated[cls, self(cls), *iter_params] |
| 36 | + |
| 37 | + |
| 38 | +if TYPE_CHECKING: |
| 39 | + type Inject[T, *Args] = Annotated[T, Depends(), *Args] |
| 40 | + |
| 41 | +else: |
| 42 | + Inject = FastAPIInject() |
| 43 | + |
| 44 | +del FastAPIInject |
0 commit comments