2Tests interactions between Literal types and other typing features.
5# Specification: https://typing.readthedocs.io/en/latest/spec/literal.html#interactions-with-other-types-and-features
8from typing import IO, Any, Final, Generic, Literal, TypeVar, assert_type, overload
11def func1(v: tuple[int, str, list[bool]], a: Literal[0], b: Literal[5], c: Literal[-5]):
12 assert_type(v[a], int)
13 assert_type(v[2], list[bool])
15 v[b] # E: index out of range
[index-out-of-bounds] Index 5 is out of bounds for tuple `tuple[int, str, list[bool]]` with length 3
16 v[c] # E: index out of range
[index-out-of-bounds] Index -5 is out of bounds for tuple `tuple[int, str, list[bool]]` with length 3
17 v[4] # E: index out of range
[index-out-of-bounds] Index 4 is out of bounds for tuple `tuple[int, str, list[bool]]` with length 3
18 v[-4] # E: index out of range
[index-out-of-bounds] Index -4 is out of bounds for tuple `tuple[int, str, list[bool]]` with length 3
21_PathType = str | bytes | int
27 mode: Literal["r", "w", "a", "x", "r+", "w+", "a+", "x+"],
35 mode: Literal["rb", "wb", "ab", "xb", "r+b", "w+b", "a+b", "x+b"],
41def open(path: _PathType, mode: str) -> IO[Any]:
45def open(path: _PathType, mode: Any) -> Any:
49assert_type(open("path", "r"), IO[str])
50assert_type(open("path", "wb"), IO[bytes])
51assert_type(open("path", "other"), IO[Any])
54A = TypeVar("A", bound=int)
55B = TypeVar("B", bound=int)
56C = TypeVar("C", bound=int)
59class Matrix(Generic[A, B]):
60 def __add__(self, other: "Matrix[A, B]") -> "Matrix[A, B]":
61 raise NotImplementedError
63 def __matmul__(self, other: "Matrix[B, C]") -> "Matrix[A, C]":
64 raise NotImplementedError
66 def transpose(self) -> "Matrix[B, A]":
67 raise NotImplementedError
70def func2(a: Matrix[Literal[2], Literal[3]], b: Matrix[Literal[3], Literal[7]]):
72 assert_type(c, Matrix[Literal[2], Literal[7]])
75T = TypeVar("T", Literal["a"], Literal["b"], Literal["c"])
76S = TypeVar("S", bound=Literal["foo"])
85def parse_status1(s: str | Status) -> None:
86 if s is Status.SUCCESS:
87 assert_type(s, Literal[Status.SUCCESS])
88 elif s is Status.INVALID_DATA:
89 assert_type(s, Literal[Status.INVALID_DATA])
90 elif s is Status.FATAL_ERROR:
91 assert_type(s, Literal[Status.FATAL_ERROR])
96def expects_bad_status(status: Literal["MALFORMED", "ABORTED"]):
100def expects_pending_status(status: Literal["PENDING"]):
104def parse_status2(status: str) -> None:
105 if status in ("MALFORMED", "ABORTED"):
106 return expects_bad_status(status)
Unexpected error
[invalid-argument-type] Argument to function `expects_bad_status` is incorrect: Expected `Literal["MALFORMED", "ABORTED"]`, found `str`
108 if status == "PENDING":
109 expects_pending_status(status)
Unexpected error
[invalid-argument-type] Argument to function `expects_pending_status` is incorrect: Expected `Literal["PENDING"]`, found `str`
113assert_type(final_val1, Literal[3])
115final_val2: Final = True
116assert_type(final_val2, Literal[True])