diff --git a/crates/ty_python_semantic/resources/mdtest/annotations/self.md b/crates/ty_python_semantic/resources/mdtest/annotations/self.md index e476e03a75..24fd966b11 100644 --- a/crates/ty_python_semantic/resources/mdtest/annotations/self.md +++ b/crates/ty_python_semantic/resources/mdtest/annotations/self.md @@ -2,7 +2,7 @@ ```toml [environment] -python-version = "3.11" +python-version = "3.13" ``` `Self` is treated as if it were a `TypeVar` bound to the class it's being used on. @@ -147,6 +147,23 @@ class Shape: return self ``` +## `Self` for classes with a default value for their generic parameter + +This is a regression test for . + +```py +from typing import Self + +class Container[T = bytes]: + def __init__(self: Self, data: T | None = None) -> None: + self.data = data + +reveal_type(Container()) # revealed: Container[bytes] +reveal_type(Container(1)) # revealed: Container[int] +reveal_type(Container("a")) # revealed: Container[str] +reveal_type(Container(b"a")) # revealed: Container[bytes] +``` + ## Invalid Usage `Self` cannot be used in the signature of a function or variable. diff --git a/crates/ty_python_semantic/src/types.rs b/crates/ty_python_semantic/src/types.rs index ecaa485ff7..d47f097440 100644 --- a/crates/ty_python_semantic/src/types.rs +++ b/crates/ty_python_semantic/src/types.rs @@ -5711,9 +5711,7 @@ impl<'db> Type<'db> { ], }); }; - let instance = Type::ClassLiteral(class).to_instance(db).expect( - "nearest_enclosing_class must return type that can be instantiated", - ); + let instance = Type::instance(db, class.unknown_specialization(db)); let class_definition = class.definition(db); let typevar = TypeVarInstance::new( db,