[ty] Simplify `Self` for final types

This commit is contained in:
David Peter 2025-10-23 10:34:51 +02:00
parent e92fd51a2c
commit 5a6bfca0ed
3 changed files with 41 additions and 0 deletions

View File

@ -508,4 +508,22 @@ def _(c: CallableTypeOf[C().method]):
reveal_type(c) # revealed: (...) -> None
```
## Final classes
For final classes, we simplify `Self` to an instance of the class:
```py
from typing import final, Self
@final
class FinalClass:
def implicit_self(self) -> Self:
reveal_type(self) # revealed: FinalClass
return self
def explicit_self(self: Self) -> Self:
reveal_type(self) # revealed: FinalClass
return self
```
[self attribute]: https://typing.python.org/en/latest/spec/generics.html#use-in-attribute-annotations

View File

@ -379,3 +379,22 @@ def as_pattern_non_exhaustive(subject: int | str):
# this diagnostic is correct: the inferred type of `subject` is `str`
assert_never(subject) # error: [type-assertion-failure]
```
## Exhaustiveness checking for methods of enums
```py
from enum import Enum
class Answer(Enum):
YES = "yes"
NO = "no"
def is_yes(self) -> bool:
reveal_type(self) # revealed: Answer
match self:
case Answer.YES:
return True
case Answer.NO:
return False
```

View File

@ -84,6 +84,10 @@ pub(crate) fn typing_self<'db>(
typevar_binding_context: Option<Definition<'db>>,
class: ClassLiteral<'db>,
) -> Option<Type<'db>> {
if class.is_final(db) {
return Some(Type::instance(db, class.identity_specialization(db)));
}
let index = semantic_index(db, function_scope_id.file(db));
let identity = TypeVarIdentity::new(