Fix issue #1312: Type (typehint) error when calling db.Model
subclass constructor with parameters
#1321
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.
Fix the typehint inconsistence of
db.relationship(...)
.tox>=4
. Mytox
version is4.12.0
.Checklist:
CHANGES.rst
summarizing the change and linking to the issue... versionchanged::
entries in any relevant code docs.pre-commit
hooks and fix any issues.pytest
andtox
, no tests failed.Appendices
Appendix A: The idea of this PR.
This example shows the core idea how this PR works.
Test(prop: _Mul)
makesprop
as a parameter of its type hint. Then the descriptor will solve the type of the propertyTest().prop
dynamically according to the parameter_Mul
of the parameterized type hintTest[_Mul]
. For example, if a new instance is initialized astest: Test[int]
, thenIntOrStr
will solve the type oftest.prop
asint
.Appendix B: Validate the performance of this PR
This PR only changes the behavior during the static type checking. In other words, at run time, the codes work totally the same as the original version. I made this customization because I think the original codes only have type checking issues but work perfectly at run time. That's why I do not submit any changelogs here, because actually I did not change any functionalities or behaviors at run time.
The following code can be used for testing the performance of the type hints provided by this PR. It works perfected in most cases. However, there are two known cases that the type check shows false negative results. See
test_not_as_expectation
.It seems that the static type checking codes cannot be added to pytest. That's why I do not add more tests for this PR.