← 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"""
2Tests 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
7from typing import TypeVar, assert_type
8
9
10T = TypeVar("T", bound="A")
13class A:
14 def copy(self: T) -> T:
15 return self
17 @classmethod
18 def factory(cls: type[T]) -> T:
19 return cls()
21 @staticmethod
22 def static_method(val: type[T]) -> T:
23 return val()
26class B(A):
27 ...
30assert_type(A().copy(), A)
31assert_type(A.factory(), A)
32assert_type(A.copy(A()), A)
33assert_type(B.copy(B()), B)
35assert_type(B().copy(), B)
36assert_type(B.factory(), B)
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.
42assert_type(A.copy(B()), A) # E?
[type-assertion-failure] Type `A` does not match asserted type `B`
44# Similarly, this case is ambiguous in the spec. Pyright currently
45# generates a type error here, but mypy accepts this.
46B.copy(A()) # E?
48assert_type(A.static_method(A), A)
49assert_type(A.static_method(B), B)
50assert_type(B.static_method(B), B)
51assert_type(B.static_method(A), A)