generics_self_attributes
error
Incompatible type for Self-typed attribute
When a class declares an attribute annotated with Self (or Self | None, OptionalSelf, etc.), that attribute's type is bound to the concrete subclass at each usage site. Passing or assigning a parent-class instance where the subclass is expected is a type error.
from typing import Self, TypeVar, Generic
from dataclasses import dataclass
T = TypeVar("T")
@dataclass
class LinkedList(Generic[T]):
value: T
next: Self | None = None
@dataclass
class OrdinalLinkedList(LinkedList[int]):
def ordinal_value(self) -> str:
return str(self.value)
xs = OrdinalLinkedList(value=1, next=LinkedList[int](value=2)) # E
xs.next = LinkedList[int](value=3, next=None) # E
Specification: <https://typing.readthedocs.io/en/latest/spec/generics.html#use-in-attribute-annotations>
How to handle it
Every rule is on by default — strict is the default, not a cage. You can dial
generics_self_attributes down per-file or per-path from your editor or
pyproject.toml, or fix the code
so it type-checks. See the Type System rules and
the complete diagnostic reference.
Canonical URL: https://www.basilisk-python.dev/errors/generics_self_attributes