Add support for generic fields in SQLModel#1810
Open
soufianeamini wants to merge 4 commits intofastapi:mainfrom
Open
Add support for generic fields in SQLModel#1810soufianeamini wants to merge 4 commits intofastapi:mainfrom
soufianeamini wants to merge 4 commits intofastapi:mainfrom
Conversation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Motivation
I wanted to implement discriminated unions using SQLModel, but #356 seems to add support for it for SQLModel but not tables.
It’s also not possible to create derived classes that change the type of some fields (setting them to None to “disable” them for example) because of invariance rules.
The last option that I’ve found to have some semblance of type safety and having a single source of truth for the types of each field is using generics.
This feature can be used for cases other than discriminated unions, although admittedly is limited due to Python not having a way to access the resolved type from the generic fields.
Example
You can take a look at the examples in
tests/test_generics.pyto get an idea of what’s possible. In my own project I’m planning to use more type safe wrappers but didn’t want to use it in the tests since it’d be too opinionated.Limitations
To implement this, I’ve made use of the bounds and constraints information that can be extracted from each field, but it does mean that it would only support having generic types that are Optional. Meaning if someone wants to allow more types (more than 1 non-None type) to have multiple models with different resolved types, it won’t be (currently) supported.
P.S: I initially wanted to create an issue but it seems discussions are made for people that are not planning to create PRs, so here goes. I'm happy to receive feedback on the implementation if a different approach is needed.