← Back to index
annotations_methods.py
True Positive
False Positive
False Negative
Optional (detected)
Warning or Info
TP: 0
FP: 0
FN: 0
Optional: 1 / 2
1
"""
2
Tests
for
annotating
instance
and
class
methods
.
3
"""
4
5
# Specification: https://typing.readthedocs.io/en/latest/spec/annotations.html#annotating-instance-and-class-methods
6
7
from
typing
import
TypeVar
,
assert_type
8
9
10
T
=
TypeVar
(
"T"
,
bound
=
"A"
)
11
12
13
class
A
:
14
def
copy
(
self
:
T
)
->
T
:
15
return
self
16
17
@classmethod
18
def
factory
(
cls
:
type
[
T
])
->
T
:
19
return
cls
()
20
21
@staticmethod
22
def
static_method
(
val
:
type
[
T
])
->
T
:
23
return
val
()
24
25
26
class
B
(
A
):
27
...
28
29
30
assert_type
(
A
()
.
copy
(),
A
)
31
assert_type
(
A
.
factory
(),
A
)
32
assert_type
(
A
.
copy
(
A
()),
A
)
33
assert_type
(
B
.
copy
(
B
()),
B
)
34
35
assert_type
(
B
()
.
copy
(),
B
)
36
assert_type
(
B
.
factory
(),
B
)
37
38
# This case is ambiguous in the spec, which does not indicate when
39
# type binding should be performed. Currently, pyright evaluates
40
# A here, but mypy evaluates B. Since the spec is not clear, both
41
# of these are currently acceptable answers.
42
assert_type
(
A
.
copy
(
B
()),
A
)
# E?
[type-assertion-failure] Type `A` does not match asserted type `B`
43
44
# Similarly, this case is ambiguous in the spec. Pyright currently
45
# generates a type error here, but mypy accepts this.
46
B
.
copy
(
A
())
# E?
47
48
assert_type
(
A
.
static_method
(
A
),
A
)
49
assert_type
(
A
.
static_method
(
B
),
B
)
50
assert_type
(
B
.
static_method
(
B
),
B
)
51
assert_type
(
B
.
static_method
(
A
),
A
)