Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 45 additions & 0 deletions crates/ty_python_semantic/resources/mdtest/call/constructor.md
Original file line number Diff line number Diff line change
Expand Up @@ -1128,6 +1128,51 @@ class Box(Generic[T]):
reveal_type(Box(1)) # revealed: Box[int]
```

## Generic constructor inference from overloaded `__init__` self types

```py
from __future__ import annotations

from typing import Generic, TypeVar, overload

T = TypeVar("T")
CT = TypeVar("CT")

class ClassSelector(Generic[T]):
@overload
def __init__(
self: ClassSelector[CT],
*,
default: CT,
class_: type[CT],
) -> None: ...
@overload
def __init__(
self: ClassSelector[CT | None],
*,
default: None = None,
class_: type[CT],
) -> None: ...
def __init__(self, *, default=None, class_=None): ...

class MyClass:
pass

a = ClassSelector(default=MyClass(), class_=MyClass)
reveal_type(a) # revealed: ClassSelector[MyClass]

b = ClassSelector(class_=MyClass)
reveal_type(b) # revealed: ClassSelector[MyClass | None]

# Explicit constructor specializations still reject incompatible inferred `self` types.
ClassSelector[int](class_=MyClass) # error: [invalid-argument-type]

class RequiredClassSelector(Generic[T]):
def __init__(self: RequiredClassSelector[CT | None], *, class_: type[CT]) -> None: ...

reveal_type(RequiredClassSelector(class_=MyClass)) # revealed: RequiredClassSelector[MyClass | None]
```

## `__init__` can remap constructor generic arguments via `self` annotation

```py
Expand Down
14 changes: 14 additions & 0 deletions crates/ty_python_semantic/src/types/generics.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1992,6 +1992,20 @@ impl<'db, 'c> SpecializationBuilder<'db, 'c> {
self.add_type_mapping(*formal_bound_typevar, remaining_actual, polarity, f);
}
(Type::Union(union_formal), _) => {
// If the formal is a union and the actual is a bare inferable TypeVar in an
// invariant position, record the whole union as the mapping. Invariant matching is
// equality-like; probing individual union elements below can leave spurious
// partial mappings from non-matching elements. For example, while comparing
// `ClassSelector[T]` with `ClassSelector[CT | None]`, descending into `None`
// would map `T` to `None` before `CT` is solved from another argument.
if let Type::TypeVar(actual_typevar) = actual
&& actual_typevar.is_inferable(self.db, self.inferable)
&& matches!(polarity, TypeVarVariance::Invariant)
{
self.add_type_mapping(actual_typevar, formal, polarity, f);
return Ok(());
}

// Second, if the formal is a union, and the actual type is assignable to precisely
// one union element, then we don't add any type mapping. This handles a case like
//
Expand Down
Loading