Improving Type Safety of Annotated Dependencies: (implemented: a run-time approach, TODO: compile-time) #11105
jsimonlane
started this conversation in
Show and tell
Replies: 1 comment
-
This PR 11255 allows you to find such errors using type checkers |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
First Check
Commit to Help
Example Code
But then, imagine a case where we upgrade our DB (and its dependency), but forget to annotate the dependency accordingly.
The above would crash at runtime, and our compiler would not help us.
To fix this, we can use this function I made:
Description
The core problem is duplication of information -- when you define dependencies, that
t.Annotated[]
bit isn't based off the truth, but rather a value you expect it to be.This leads to issues found at runtime and bespoke checks -- for instance, this recent issue uses 'assert' in the body to double check the correctness of the dependency.
We want to do this at compile time.
Unfortunately, I couldn't find a way to get the Python Type checker to dynamically generate the right dependency... it was tricky.
However, my above approach does it when the server boots, which is the next best thing. Fixing this check makes the annotation updated correctly, and the typing to work from there.
Operating System
macOS
Operating System Details
No response
FastAPI Version
0.109.1
Pydantic Version
1.10.14
Python Version
Python 3.11.6
Additional Context
No response
Beta Was this translation helpful? Give feedback.
All reactions