ruff/crates/ty_python_semantic/resources/mdtest/generics
Douglas Creager ce43dbab58
[ty] Promote literals when inferring class specializations from constructors (#18102)
This implements the stopgap approach described in
https://github.com/astral-sh/ty/issues/336#issuecomment-2880532213 for
handling literal types in generic class specializations.

With this approach, we will promote any literal to its instance type,
but _only_ when inferring a generic class specialization from a
constructor call:

```py
class C[T]:
    def __init__(self, x: T) -> None: ...

reveal_type(C("string"))  # revealed: C[str]
```

If you specialize the class explicitly, we still use whatever type you
provide, even if it's a literal:

```py
from typing import Literal

reveal_type(C[Literal[5]](5))  # revealed: C[Literal[5]]
```

And this doesn't apply at all to generic functions:

```py
def f[T](x: T) -> T:
    return x

reveal_type(f(5))  # revealed: Literal[5]
```

---

As part of making this happen, we also generalize the `TypeMapping`
machinery. This provides a way to apply a function to type, returning a
new type. Complicating matters is that for function literals, we have to
apply the mapping lazily, since the function's signature is not created
until (and if) someone calls its `signature` method. That means we have
to stash away the mappings that we want to apply to the signatures
parameter/return annotations once we do create it. This requires some
minor `Cow` shenanigans to continue working for partial specializations.
2025-05-19 15:42:54 -04:00
..
legacy [ty] Promote literals when inferring class specializations from constructors (#18102) 2025-05-19 15:42:54 -04:00
pep695 [ty] Promote literals when inferring class specializations from constructors (#18102) 2025-05-19 15:42:54 -04:00
builtins.md Rename Red Knot (#17820) 2025-05-03 19:49:15 +02:00
scoping.md [ty] Infer function call typevars in both directions (#18155) 2025-05-19 11:45:40 -04:00