ruff/crates/ty_python_semantic
Douglas Creager 416e956fe0
[ty] Infer better specializations of unions with None (etc) (#20749)
This PR adds a specialization inference special case that lets us handle
the following examples better:

```py
def f[T](t: T | None) -> T: ...
def g[T](t: T | int | None) -> T | int: ...

def _(x: str | None):
    reveal_type(f(x))  # revealed: str (previously str | None)

def _(y: str | int | None):
    reveal_type(g(x))  # revealed: str | int (previously str | int | None)
```

We already have a special case for when the formal is a union where one
element is a typevar, but it maps the entire actual type to the typevar
(as you can see in the "previously" results above).

The new special case kicks in when the actual is also a union. Now, we
filter out any actual union elements that are already subtypes of the
formal, and only bind whatever types remain to the typevar. (The `|
None` pattern appears quite often in the ecosystem results, but it's
more general and works with any number of non-typevar union elements.)

The new constraint solver should handle this case as well, but it's
worth adding this heuristic now with the old solver because it
eliminates some false positives from the ecosystem report, and makes the
ecosystem report less noisy on the other constraint solver PRs.
2025-10-07 13:33:42 -04:00
..
resources [ty] Infer better specializations of unions with None (etc) (#20749) 2025-10-07 13:33:42 -04:00
src [ty] Infer better specializations of unions with None (etc) (#20749) 2025-10-07 13:33:42 -04:00
tests [ty] Track open files in the server (#19264) 2025-07-18 19:33:35 +05:30
build.rs Rename Red Knot (#17820) 2025-05-03 19:49:15 +02:00
Cargo.toml [ty] Avoid overcounting shared memory usage (#19773) 2025-08-06 15:32:02 -04:00
mdtest.py [ty] Faster iteration on mdtests (#20465) 2025-09-18 10:48:52 +00:00
mdtest.py.lock Rename Red Knot (#17820) 2025-05-03 19:49:15 +02:00