Prefer "own" type vars (owned by current function) when building "any of" constraints #18986
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.
Sometimes our constraints builder needs to express "at least one of these constraints must be true". Sometimes it's trivial, but sometimes they have nothing in common - in that case we fall back to forgetting all of them and (usually) inferring
Never
.This PR extends the fallback handling logic by one more rule: before giving up, we try restricting the constraints to type variables "owned" by the target function. This means that when we try to express
T :> str || U :> str
in the following setup:we won't ignore both and fall back to
Never
but will pickU :> str
instead. The reason for this heuristic is that function-scoped typevars are definitely something we're trying to infer, while everything else is usually out of our control, any other type variable should stay intact.This isn't safe in general case - it might be that another typevar satisfies the constraints but the chosen one doesn't. However, this shouldn't make any existing inference worse: if we used to infer
Never
and it worked, then anything else should almost definitely work as well.See the added testcase for motivation: currently
mypy
fails to handleMapping.get
with default without return type context whenMapping
has a type variable as the second argument. https://mypy-play.net/?mypy=1.15.0&python=3.12&flags=strict&gist=2f9493548082e66b77750655d3a90218This is a prerequisite of #18976 - that inference change makes the problem solved here occur more often.
This definitely should be a function parameter, but I don't feel like adjusting all 60
infer_constraints
calls inconstraints.py
so just put a stack in typestate.