[ty] Don't require default typevars when specializing (#17872)

If a typevar is declared as having a default, we shouldn't require a
type to be specified for that typevar when explicitly specializing a
generic class:

```py
class WithDefault[T, U = int]: ...

reveal_type(WithDefault[str]())  # revealed: WithDefault[str, int]
```

---------

Co-authored-by: Alex Waygood <Alex.Waygood@Gmail.com>
This commit is contained in:
Douglas Creager 2025-05-05 18:29:30 -04:00 committed by GitHub
parent bb6c7cad07
commit ada4c4cb1f
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
5 changed files with 46 additions and 12 deletions

View file

@ -150,6 +150,17 @@ reveal_type(Constrained[int | str]()) # revealed: Constrained[int | str]
reveal_type(Constrained[object]()) # revealed: Unknown
```
If the type variable has a default, it can be omitted:
```py
WithDefaultU = TypeVar("WithDefaultU", default=int)
class WithDefault(Generic[T, WithDefaultU]): ...
reveal_type(WithDefault[str, str]()) # revealed: WithDefault[str, str]
reveal_type(WithDefault[str]()) # revealed: WithDefault[str, int]
```
## Inferring generic class parameters
We can infer the type parameter from a type context:

View file

@ -133,6 +133,15 @@ reveal_type(Constrained[int | str]()) # revealed: Constrained[int | str]
reveal_type(Constrained[object]()) # revealed: Unknown
```
If the type variable has a default, it can be omitted:
```py
class WithDefault[T, U = int]: ...
reveal_type(WithDefault[str, str]()) # revealed: WithDefault[str, str]
reveal_type(WithDefault[str]()) # revealed: WithDefault[str, int]
```
## Inferring generic class parameters
We can infer the type parameter from a type context: