Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Define strict return value typing for Depends and Security #11255

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
22 changes: 15 additions & 7 deletions fastapi/param_functions.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from typing import Any, Callable, Dict, List, Optional, Sequence, Union
from typing import Any, Callable, Dict, List, Optional, Sequence, TypeVar, Union, cast

from fastapi import params
from fastapi._compat import Undefined
Expand Down Expand Up @@ -2217,9 +2217,12 @@ def File( # noqa: N802
)


DependencyResult = TypeVar("DependencyResult")


def Depends( # noqa: N802
dependency: Annotated[
Optional[Callable[..., Any]],
Optional[Callable[..., DependencyResult]],
Doc(
"""
A "dependable" callable (like a function).
Expand All @@ -2244,7 +2247,7 @@ def Depends( # noqa: N802
"""
),
] = True,
) -> Any:
) -> DependencyResult:
"""
Declare a FastAPI dependency.

Expand Down Expand Up @@ -2274,12 +2277,14 @@ async def read_items(commons: Annotated[dict, Depends(common_parameters)]):
return commons
```
"""
return params.Depends(dependency=dependency, use_cache=use_cache)
return cast(
DependencyResult, params.Depends(dependency=dependency, use_cache=use_cache)
)


def Security( # noqa: N802
dependency: Annotated[
Optional[Callable[..., Any]],
Optional[Callable[..., DependencyResult]],
Doc(
"""
A "dependable" callable (like a function).
Expand Down Expand Up @@ -2321,7 +2326,7 @@ def Security( # noqa: N802
"""
),
] = True,
) -> Any:
) -> DependencyResult:
"""
Declare a FastAPI Security dependency.

Expand Down Expand Up @@ -2357,4 +2362,7 @@ async def read_own_items(
return [{"item_id": "Foo", "owner": current_user.username}]
```
"""
return params.Security(dependency=dependency, scopes=scopes, use_cache=use_cache)
return cast(
DependencyResult,
params.Security(dependency=dependency, scopes=scopes, use_cache=use_cache),
)