← Back to index

specialtypes_never.py

True Positive
False Positive
False Negative
Optional (detected)
Warning or Info
TP: 3
FP: 0
FN: 0
Optional: 0 / 0
1"""
2Tests the handling of typing.Never and typing.NoReturn.
3"""
4
5# Specification: https://typing.readthedocs.io/en/latest/spec/special-types.html#noreturn
6
7import sys
8from typing import Any, Generic, Never, NoReturn, TypeVar
9
10T = TypeVar("T")
11T_co = TypeVar("T_co", covariant=True)
12U = TypeVar("U")
15def stop() -> NoReturn:
16 raise RuntimeError("no way")
19def func1(x: int) -> NoReturn: # E: implicitly returns None
[invalid-return-type] Function always implicitly returns `None`, which is not assignable to return type `Never`
20 if x != 0:
21 sys.exit(1)
24# > The checkers will also recognize that the code after calls to such functions
25# > is unreachable and will behave accordingly.
27# No error on implicit None return after stop()
28def func2(x: int) -> int:
29 if x > 0:
30 return x
31 stop()
34# The spec previously said that NoReturn is only valid in a function return type,
35# but this was removed and it should now be accepted in all of these contexts:
38def func3(
39 a: NoReturn, b: list[NoReturn]
40) -> None:
41 c: NoReturn = a
44def func4(
45 a: list[NoReturn],
46) -> None:
47 c: list[NoReturn] = a
50def func5() -> list[NoReturn]:
51 return []
54class ClassA:
55 x: NoReturn
56 y: list[NoReturn]
58 def __init__(self, x: NoReturn, y: list[NoReturn]) -> None:
59 self.x = x
60 self.y = y
63# Never is compatible with all types.
66def func6(a: Never):
67 v1: int = a # OK
68 v2: str = a # OK
69 v3: list[str] = a # OK
72# Never is a synonym for NoReturn.
75def func7(x: int) -> Never:
76 sys.exit(1)
79# Other types are not compatible with Never except for Never (and Any).
82def func8(a: Never, b: Any, c: list[Never]):
83 v1: Never = a # OK
84 v2: Never = b # OK
85 v3: list[int] = c # E
[invalid-assignment] Object of type `list[Never]` is not assignable to `list[int]`
86 v4: Never = stop() # OK
89class ClassB(Generic[T_co]):
90 pass
93def func9(x: U) -> ClassB[U]:
94 # Never is a bottom type and therefore compatible with a covariant type variable.
95 return ClassB[Never]() # OK
98class ClassC(Generic[T]):
99 pass
102def func10(x: U) -> ClassC[U]:
103 # Never is not compatible in an invariant context.
104 return ClassC[Never]() # E
[invalid-return-type] Return type does not match returned value: expected `ClassC[U@func10]`, found `ClassC[Never]`