Files
Carl MeyerandDouglas Creager 2c98e83118 [ty] Treat caller-fixed type variables as concrete during inference (#30423)
Consider this example of a generic call within another generic function
(the last line):

```python
from typing import Any

def keep[L: list[Any]](items: L) -> L:
    return items

def forward[T](items: list[T]) -> list[T]:
    return keep(items)
```

The type variables for the call we are currently inferring (`L`) are
"inferable", and we can pick any solution for them that fits the
constraints: the goal of constraint solving is to pick a valid solution
for inferable type variables.

Type variables from the outer scope (`T`) are "fixed" or "non-inferable"
-- they could take on any type within their bounds/constraints, and our
solution has to work for all their possible specializations; we aren't
allowed to pick a solution for them.

Today on main, our solver largely internally treats non-inferable type
variables as inferable. This can cause us to wrongly report "solutions"
that are only valid for some specializations of the non-inferable
typevars. It can also cause us to wrongly substitute occurrences of the
fixed typevar with some other type.

For example, in the above snippet we get the constraint `list[T] <: L`
from the call argument, and `L <: list[T]` from the return-type context
provided by the return annotation on `forward`. This should be enough to
straightforwardly solve the call to `list[T]`, which is the right
solution. But on main we get confused by the additional constraint `L <:
list[Any]` (from the upper bound of `L`): we combine that with the above
constraints to infer `T = Any`, and then we substitute that into
`list[T]` in order to get the solution `list[Any]`. We should not be
substituting for non-inferable typevars like this.

This change uses the set of inferable type variables when collecting and
solving constraints. It preserves `T` and infers `list[T]` for this
call.

Closes astral-sh/ty#4696.
Closes astral-sh/ty#5019.
Closes astral-sh/ty#5074.
Partially addresses astral-sh/ty#5063 (improves Bokeh perf by ~70%)

---------

Co-authored-by: Douglas Creager <dcreager@dcreager.net>
2026-11-23 12:16:40 -08:00
..
2025-05-03 19:49:15 +02:00