← 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
"""
2
Tests
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
7
from
typing
import
TypeVar
,
Generic
,
Self
8
from
dataclasses
import
dataclass
9
10
11
T
=
TypeVar
(
"T"
)
12
13
@dataclass
14
class
LinkedList
(
Generic
[
T
]):
15
value
:
T
16
next
:
Self
|
None
=
None
17
18
19
@dataclass
20
class
OrdinalLinkedList
(
LinkedList
[
int
]):
21
def
ordinal_value
(
self
)
->
str
:
22
return
str
(
self
.
value
)
23
24
25
# This should result in a type error.
26
xs
=
OrdinalLinkedList
(
value
=
1
,
next
=
LinkedList
[
int
](
value
=
2
))
# E
[invalid-argument-type] Argument is incorrect: Expected `OrdinalLinkedList | None`, found `LinkedList[int]`
27
28
if
xs
.
next
is
not
None
:
29
xs
.
next
=
OrdinalLinkedList
(
value
=
3
,
next
=
None
)
# OK
30
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`