-
-
Notifications
You must be signed in to change notification settings - Fork 3.1k
Introduce a helper function to map types to protocols + fix for dict kwargs false positive #20419
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
base: master
Are you sure you want to change the base?
Conversation
This comment has been minimized.
This comment has been minimized.
| from mypy.subtypes import is_subtype | ||
| from mypy.typeops import get_all_type_vars |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
had to put these there due to circular import issues
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This function should definitely not be in this module (ideally we shouldn't even have the existing typeops import below, but that is a separate story).
Also the scope of this function is misleadingly broad. It should probably accept a TypeInfo as target (which probably must be a protocol), and then use fill_typevars(...) as a constraint inference target.
Finally, it is worth doing some performance measurements, we don't want any visible slow-down for something that is only needed for rare edge cases.
| # need to manually include these because solve_constraints ignores them | ||
| # apparently | ||
| constraints.append(Constraint(tvar, SUBTYPE_OF, tvar.upper_bound)) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Is it intentional that solve_constraints ignores the upper bounds of the tvars it solves for?
|
According to mypy_primer, this change doesn't affect type check results on a corpus of open source code. ✅ |
Fixes: #20424
Following my comments in #20416, this PR introduces a new helper function
as_typethat can be used to determine whether a type can be matched to a certain protocol or not.As an example application, I fix a bug in
is_valid_keyword_var_argthat stems from checkingkwargs <: SupportsKeyAndGetItem[str, Any]This check is too eager, because
SupportsKeyAndGetItemis invariant in the key type, it will produce a false positive whenkwargsis for instancedict[Literal["foo", "bar"], int]. The correct test is:Does there exist
T <: strso thatkwargs <: SupportsKeyAndGetItem[T, Any]which can be checked with the new helper function.
Updated tests
I updated
testLiteralKwargsto test:dictargumentMappingargumentSupportsKeyAndGetitemargument