fastapi
fastapi copied to clipboard
Propagate callable's return type annotation for Depends/Security
I was struck by the following paragraph in tutorial for Depends
:
https://github.com/tiangolo/fastapi/blob/51e920e2fcf3e2a715081f28e3187549f2bf531a/docs/en/docs/tutorial/dependencies/classes-as-dependencies.md#L138-L150
I though that's easily solvable with typing.TypeVar
, and this PR serves as a untested proof-of-concept, further corroborated only by the fact that the following short snippet passes mypy checks:
from typing import Callable, TypeVar
T = TypeVar('T')
class C:
...
def foo(x: Callable[..., T]) -> T:
return bar()
def bar():
return ...
c: C = foo(C) # <-- no error here
This alleviates the need for repeating the dependency (e.g. CommonQueryParams
) in the annotation. :crossed_fingers:
📝 Docs preview for commit 1897679d94afadb006dd8f522dfdde3a95cb3617 at: https://5fcc0b5526e26c0d4e6fe1f5--fastapi.netlify.app
📝 Docs preview for commit 1919f4a4c38b468b2f97d212e3a94fc3937f9121 at: https://5fcc0d23f7ef2c1514108190--fastapi.netlify.app
📝 Docs preview for commit 5f6b3e4bbad744f3bc91e7c290b28e6070000612 at: https://5fcc0ecaf7ef2c0853108389--fastapi.netlify.app
Codecov Report
All modified and coverable lines are covered by tests :white_check_mark:
Comparison is base (
a7a353e
) 100.00% compared to head (8f5174c
) 100.00%. Report is 2021 commits behind head on master.
Additional details and impacted files
@@ Coverage Diff @@
## master #2473 +/- ##
=========================================
Coverage 100.00% 100.00%
=========================================
Files 243 243
Lines 7419 7420 +1
=========================================
+ Hits 7419 7420 +1
:umbrella: View full report in Codecov by Sentry.
:loudspeaker: Have feedback on the report? Share it here.
📝 Docs preview for commit add447ae4d497f0935b51f50d7970ffcef41adf6 at: https://5fcc0fd043cd1713312cbf47--fastapi.netlify.app
While an obvious example of laziness and poor judgement, with tests still passing, the proof-of-concept seems to work. :sweat_smile:
What would extend this PoC into a full-blown PR is:
- [ ] adjusting above documentation paragraph,
- [ ] using the pattern elsewhere where/if useful.
📝 Docs preview for commit 00a05818dc4ee6ee7e8407e511a31ad29a377a07 at: https://5ffd42e826f6439258176331--fastapi.netlify.app
📝 Docs preview for commit 8f5174cf6843fbd48417da48ce748888d5c89c98 at: https://602b101c120af3e0b6222eba--fastapi.netlify.app
Finally took time to make the tests pass. Please have a look. :grin:
I'd love to see this change land. Let me know if I can help.