← Back to index

classes_override.py

True Positive
False Positive
False Negative
Optional (detected)
Warning or Info
TP: 5
FP: 0
FN: 0
Optional: 0 / 0
1"""
2Tests the typing.override decorator.
3"""
4
5# Specification: https://typing.readthedocs.io/en/latest/spec/class-compat.html#override
6
7from typing import Any, Callable, overload, override
8
9
10def wrapper(func: Callable[..., Any], /) -> Any:
11 def wrapped(*args: Any, **kwargs: Any) -> Any:
12 raise NotImplementedError
14 return wrapped
17class ParentA:
18 def method1(self) -> int:
19 return 1
21 @overload
22 def method2(self, x: int) -> int:
23 ...
25 @overload
26 def method2(self, x: str) -> str:
27 ...
29 def method2(self, x: int | str) -> int | str:
30 return 0
32 def method5(self):
33 pass
36class ChildA(ParentA):
37 @override
38 def method1(self) -> int: # OK
39 return 2
41 @overload
42 def method2(self, x: int) -> int:
43 ...
45 @overload
46 def method2(self, x: str) -> str:
47 ...
49 def method2(self, x: int | str) -> int | str: # OK
50 return 0
52 @override # E[method3]
53 def method3(self) -> int: # E[method3]: no matching signature in ancestor
Tag 'method3' [invalid-explicit-override] Method `method3` is decorated with `@override` but does not override anything
54 return 1
56 @overload # E[method4]
57 def method4(self, x: int) -> int: # E[method4]
58 ...
60 @overload
61 def method4(self, x: str) -> str:
62 ...
64 @override # E[method4]
65 def method4(self, x: int | str) -> int | str: # E[method4]: no matching signature in ancestor
Tag 'method4' [invalid-explicit-override] Method `method4` is decorated with `@override` but does not override anything
66 return 0
68 @override
69 @wrapper
70 def method5(self): # OK
71 pass
73 # > The @override decorator should be permitted anywhere a type checker
74 # > considers a method to be a valid override, which typically includes not
75 # > only normal methods but also @property, @staticmethod, and @classmethod.
77 @staticmethod
78 @override # E[static_method1]
79 def static_method1() -> int: # E[static_method1]: no matching signature in ancestor
Tag 'static_method1' [invalid-explicit-override] Method `static_method1` is decorated with `@override` but does not override anything
80 return 1
82 @classmethod
83 @override # E[class_method1]
84 def class_method1(cls) -> int: # E[class_method1]: no matching signature in ancestor
Tag 'class_method1' [invalid-explicit-override] Method `class_method1` is decorated with `@override` but does not override anything
85 return 1
87 @property
88 @override # E[property1]
89 def property1(self) -> int: # E[property1]: no matching signature in ancestor
Tag 'property1' [invalid-explicit-override] Method `property1` is decorated with `@override` but does not override anything
90 return 1
93# Test the case where the parent derives from Any
95class ParentB(Any):
96 pass
99class ChildB(ParentB):
100 @override
101 def method1(self) -> None: # OK
102 pass