← Back to index

generics_self_attributes.py

True Positive
False Positive
False Negative
Optional (detected)
Warning or Info
TP: 2
FP: 0
FN: 0
Optional: 0 / 0
1"""
2Tests for usage of the typing.Self type with attributes.
3"""
4
5# Specification: https://typing.readthedocs.io/en/latest/spec/generics.html#use-in-attribute-annotations
6
7from typing import TypeVar, Generic, Self
8from dataclasses import dataclass
9
11T = TypeVar("T")
13@dataclass
14class LinkedList(Generic[T]):
15 value: T
16 next: Self | None = None
19@dataclass
20class OrdinalLinkedList(LinkedList[int]):
21 def ordinal_value(self) -> str:
22 return str(self.value)
25# This should result in a type error.
26xs = OrdinalLinkedList(value=1, next=LinkedList[int](value=2)) # E
[invalid-argument-type] Argument is incorrect: Expected `OrdinalLinkedList | None`, found `LinkedList[int]`
28if xs.next is not None:
29 xs.next = OrdinalLinkedList(value=3, next=None) # OK
31 # This should result in a type error.
32 xs.next = LinkedList[int](value=3, next=None) # E
[invalid-assignment] Object of type `LinkedList[int]` is not assignable to attribute `next` of type `OrdinalLinkedList | None`