You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Only consider meta variables in ambiguous "any of" constraints (#18986)
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 meta variables only.
This means that when we try to express `T :> str || U :> str` in the
following setup:
```
from typing import TypeVar
T = TypeVar("T")
U = TypeVar("U")
class Foo(Generic[T]):
def func(self, arg: T | U) -> None: ...
```
we won't ignore both and fall back to `Never` but will pick `U :> 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.
There are other places where constraint builder may emit restrictions on
type variables it does not control, handling them consistently
everywhere is left as an exercise to the reader.
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 handle
`Mapping.get` with default without return type context when `Mapping`
has a type variable as the second argument.
https://mypy-play.net/?mypy=1.15.0&python=3.12&flags=strict&gist=2f9493548082e66b77750655d3a90218
This is a prerequisite of #18976 - that inference change makes the
problem solved here occur more often.
0 commit comments