mirror of
https://github.com/astral-sh/ruff.git
synced 2025-08-03 18:28:24 +00:00
![]() 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. |
||
---|---|---|
.. | ||
legacy | ||
pep695 | ||
builtins.md | ||
scoping.md |