Debian Codegraph @

test-data/unit/check-narrowing.test

raw
1 [case testNarrowingParentWithStrsBasic]
2 # flags: --strict-equality --warn-unreachable
3 from dataclasses import dataclass
4 from typing import Literal, NamedTuple, Tuple, TypedDict, Union
5
6 class Object1:
7 key: Literal["A"]
8 foo: int
9 class Object2:
10 key: Literal["B"]
11 bar: str
12
13 @dataclass
14 class Dataclass1:
15 key: Literal["A"]
16 foo: int
17 @dataclass
18 class Dataclass2:
19 key: Literal["B"]
20 foo: str
21
22 class NamedTuple1(NamedTuple):
23 key: Literal["A"]
24 foo: int
25 class NamedTuple2(NamedTuple):
26 key: Literal["B"]
27 foo: str
28
29 Tuple1 = Tuple[Literal["A"], int]
30 Tuple2 = Tuple[Literal["B"], str]
31
32 class TypedDict1(TypedDict):
33 key: Literal["A"]
34 foo: int
35 class TypedDict2(TypedDict):
36 key: Literal["B"]
37 foo: str
38
39 x1: Union[Object1, Object2]
40 if x1.key == "A":
41 reveal_type(x1) # N: Revealed type is "__main__.Object1"
42 reveal_type(x1.key) # N: Revealed type is "Literal['A']"
43 else:
44 reveal_type(x1) # N: Revealed type is "__main__.Object2"
45 reveal_type(x1.key) # N: Revealed type is "Literal['B']"
46
47 x2: Union[Dataclass1, Dataclass2]
48 if x2.key == "A":
49 reveal_type(x2) # N: Revealed type is "__main__.Dataclass1"
50 reveal_type(x2.key) # N: Revealed type is "Literal['A']"
51 else:
52 reveal_type(x2) # N: Revealed type is "__main__.Dataclass2"
53 reveal_type(x2.key) # N: Revealed type is "Literal['B']"
54
55 x3: Union[NamedTuple1, NamedTuple2]
56 if x3.key == "A":
57 reveal_type(x3) # N: Revealed type is "tuple[Literal['A'], builtins.int, fallback=__main__.NamedTuple1]"
58 reveal_type(x3.key) # N: Revealed type is "Literal['A']"
59 else:
60 reveal_type(x3) # N: Revealed type is "tuple[Literal['B'], builtins.str, fallback=__main__.NamedTuple2]"
61 reveal_type(x3.key) # N: Revealed type is "Literal['B']"
62 if x3[0] == "A":
63 reveal_type(x3) # N: Revealed type is "tuple[Literal['A'], builtins.int, fallback=__main__.NamedTuple1]"
64 reveal_type(x3[0]) # N: Revealed type is "Literal['A']"
65 else:
66 reveal_type(x3) # N: Revealed type is "tuple[Literal['B'], builtins.str, fallback=__main__.NamedTuple2]"
67 reveal_type(x3[0]) # N: Revealed type is "Literal['B']"
68
69 x4: Union[Tuple1, Tuple2]
70 if x4[0] == "A":
71 reveal_type(x4) # N: Revealed type is "tuple[Literal['A'], builtins.int]"
72 reveal_type(x4[0]) # N: Revealed type is "Literal['A']"
73 else:
74 reveal_type(x4) # N: Revealed type is "tuple[Literal['B'], builtins.str]"
75 reveal_type(x4[0]) # N: Revealed type is "Literal['B']"
76
77 x5: Union[TypedDict1, TypedDict2]
78 if x5["key"] == "A":
79 reveal_type(x5) # N: Revealed type is "TypedDict('__main__.TypedDict1', {'key': Literal['A'], 'foo': builtins.int})"
80 else:
81 reveal_type(x5) # N: Revealed type is "TypedDict('__main__.TypedDict2', {'key': Literal['B'], 'foo': builtins.str})"
82 [builtins fixtures/primitives.pyi]
83 [typing fixtures/typing-typeddict.pyi]
84
85 [case testNarrowingParentWithEnumsBasic]
86 # flags: --strict-equality --warn-unreachable
87 from enum import Enum
88 from dataclasses import dataclass
89 from typing import Literal, NamedTuple, Tuple, TypedDict, Union
90
91 class Key(Enum):
92 A = 1
93 B = 2
94 C = 3
95
96 class Object1:
97 key: Literal[Key.A]
98 foo: int
99 class Object2:
100 key: Literal[Key.B]
101 bar: str
102
103 @dataclass
104 class Dataclass1:
105 key: Literal[Key.A]
106 foo: int
107 @dataclass
108 class Dataclass2:
109 key: Literal[Key.B]
110 foo: str
111
112 class NamedTuple1(NamedTuple):
113 key: Literal[Key.A]
114 foo: int
115 class NamedTuple2(NamedTuple):
116 key: Literal[Key.B]
117 foo: str
118
119 Tuple1 = Tuple[Literal[Key.A], int]
120 Tuple2 = Tuple[Literal[Key.B], str]
121
122 class TypedDict1(TypedDict):
123 key: Literal[Key.A]
124 foo: int
125 class TypedDict2(TypedDict):
126 key: Literal[Key.B]
127 foo: str
128
129 x1: Union[Object1, Object2]
130 if x1.key is Key.A:
131 reveal_type(x1) # N: Revealed type is "__main__.Object1"
132 reveal_type(x1.key) # N: Revealed type is "Literal[__main__.Key.A]"
133 else:
134 reveal_type(x1) # N: Revealed type is "__main__.Object2"
135 reveal_type(x1.key) # N: Revealed type is "Literal[__main__.Key.B]"
136
137 x2: Union[Dataclass1, Dataclass2]
138 if x2.key is Key.A:
139 reveal_type(x2) # N: Revealed type is "__main__.Dataclass1"
140 reveal_type(x2.key) # N: Revealed type is "Literal[__main__.Key.A]"
141 else:
142 reveal_type(x2) # N: Revealed type is "__main__.Dataclass2"
143 reveal_type(x2.key) # N: Revealed type is "Literal[__main__.Key.B]"
144
145 x3: Union[NamedTuple1, NamedTuple2]
146 if x3.key is Key.A:
147 reveal_type(x3) # N: Revealed type is "tuple[Literal[__main__.Key.A], builtins.int, fallback=__main__.NamedTuple1]"
148 reveal_type(x3.key) # N: Revealed type is "Literal[__main__.Key.A]"
149 else:
150 reveal_type(x3) # N: Revealed type is "tuple[Literal[__main__.Key.B], builtins.str, fallback=__main__.NamedTuple2]"
151 reveal_type(x3.key) # N: Revealed type is "Literal[__main__.Key.B]"
152 if x3[0] is Key.A:
153 reveal_type(x3) # N: Revealed type is "tuple[Literal[__main__.Key.A], builtins.int, fallback=__main__.NamedTuple1]"
154 reveal_type(x3[0]) # N: Revealed type is "Literal[__main__.Key.A]"
155 else:
156 reveal_type(x3) # N: Revealed type is "tuple[Literal[__main__.Key.B], builtins.str, fallback=__main__.NamedTuple2]"
157 reveal_type(x3[0]) # N: Revealed type is "Literal[__main__.Key.B]"
158
159 x4: Union[Tuple1, Tuple2]
160 if x4[0] is Key.A:
161 reveal_type(x4) # N: Revealed type is "tuple[Literal[__main__.Key.A], builtins.int]"
162 reveal_type(x4[0]) # N: Revealed type is "Literal[__main__.Key.A]"
163 else:
164 reveal_type(x4) # N: Revealed type is "tuple[Literal[__main__.Key.B], builtins.str]"
165 reveal_type(x4[0]) # N: Revealed type is "Literal[__main__.Key.B]"
166
167 x5: Union[TypedDict1, TypedDict2]
168 if x5["key"] is Key.A:
169 reveal_type(x5) # N: Revealed type is "TypedDict('__main__.TypedDict1', {'key': Literal[__main__.Key.A], 'foo': builtins.int})"
170 else:
171 reveal_type(x5) # N: Revealed type is "TypedDict('__main__.TypedDict2', {'key': Literal[__main__.Key.B], 'foo': builtins.str})"
172 [builtins fixtures/dict.pyi]
173 [typing fixtures/typing-typeddict.pyi]
174
175 [case testNarrowingParentWithIsInstanceBasic]
176 # flags: --strict-equality --warn-unreachable
177 from dataclasses import dataclass
178 from typing import NamedTuple, Tuple, TypedDict, Union
179
180 class Object1:
181 key: int
182 class Object2:
183 key: str
184
185 @dataclass
186 class Dataclass1:
187 key: int
188 @dataclass
189 class Dataclass2:
190 key: str
191
192 class NamedTuple1(NamedTuple):
193 key: int
194 class NamedTuple2(NamedTuple):
195 key: str
196
197 Tuple1 = Tuple[int]
198 Tuple2 = Tuple[str]
199
200 class TypedDict1(TypedDict):
201 key: int
202 class TypedDict2(TypedDict):
203 key: str
204
205 x1: Union[Object1, Object2]
206 if isinstance(x1.key, int):
207 reveal_type(x1) # N: Revealed type is "__main__.Object1"
208 else:
209 reveal_type(x1) # N: Revealed type is "__main__.Object2"
210
211 x2: Union[Dataclass1, Dataclass2]
212 if isinstance(x2.key, int):
213 reveal_type(x2) # N: Revealed type is "__main__.Dataclass1"
214 else:
215 reveal_type(x2) # N: Revealed type is "__main__.Dataclass2"
216
217 x3: Union[NamedTuple1, NamedTuple2]
218 if isinstance(x3.key, int):
219 reveal_type(x3) # N: Revealed type is "tuple[builtins.int, fallback=__main__.NamedTuple1]"
220 else:
221 reveal_type(x3) # N: Revealed type is "tuple[builtins.str, fallback=__main__.NamedTuple2]"
222 if isinstance(x3[0], int):
223 reveal_type(x3) # N: Revealed type is "tuple[builtins.int, fallback=__main__.NamedTuple1]"
224 else:
225 reveal_type(x3) # N: Revealed type is "tuple[builtins.str, fallback=__main__.NamedTuple2]"
226
227 x4: Union[Tuple1, Tuple2]
228 if isinstance(x4[0], int):
229 reveal_type(x4) # N: Revealed type is "tuple[builtins.int]"
230 else:
231 reveal_type(x4) # N: Revealed type is "tuple[builtins.str]"
232
233 x5: Union[TypedDict1, TypedDict2]
234 if isinstance(x5["key"], int):
235 reveal_type(x5) # N: Revealed type is "TypedDict('__main__.TypedDict1', {'key': builtins.int})"
236 else:
237 reveal_type(x5) # N: Revealed type is "TypedDict('__main__.TypedDict2', {'key': builtins.str})"
238 [builtins fixtures/dict.pyi]
239 [typing fixtures/typing-typeddict.pyi]
240
241 [case testNarrowingParentMultipleKeys]
242 # flags: --strict-equality --warn-unreachable
243 from enum import Enum
244 from typing import Literal, Union
245
246 class Key(Enum):
247 A = 1
248 B = 2
249 C = 3
250 D = 4
251
252 class Object1:
253 key: Literal[Key.A, Key.C]
254 class Object2:
255 key: Literal[Key.B, Key.C]
256
257 x: Union[Object1, Object2]
258 if x.key is Key.A:
259 reveal_type(x) # N: Revealed type is "__main__.Object1"
260 else:
261 reveal_type(x) # N: Revealed type is "__main__.Object1 | __main__.Object2"
262
263 if x.key is Key.C:
264 reveal_type(x) # N: Revealed type is "__main__.Object1 | __main__.Object2"
265 else:
266 reveal_type(x) # N: Revealed type is "__main__.Object1 | __main__.Object2"
267
268 if x.key is Key.D: # E: Non-overlapping identity check (left operand type: "Literal[Key.A, Key.C, Key.B]", right operand type: "Literal[Key.D]")
269 reveal_type(x) # E: Statement is unreachable
270 else:
271 reveal_type(x) # N: Revealed type is "__main__.Object1 | __main__.Object2"
272 [builtins fixtures/tuple.pyi]
273
274 [case testNarrowingTypedDictParentMultipleKeys]
275 # flags: --strict-equality --warn-unreachable
276 from typing import Literal, TypedDict, Union
277
278 class TypedDict1(TypedDict):
279 key: Literal['A', 'C']
280 class TypedDict2(TypedDict):
281 key: Literal['B', 'C']
282
283 x: Union[TypedDict1, TypedDict2]
284 if x['key'] == 'A':
285 reveal_type(x) # N: Revealed type is "TypedDict('__main__.TypedDict1', {'key': Literal['A'] | Literal['C']})"
286 else:
287 reveal_type(x) # N: Revealed type is "TypedDict('__main__.TypedDict1', {'key': Literal['A'] | Literal['C']}) | TypedDict('__main__.TypedDict2', {'key': Literal['B'] | Literal['C']})"
288
289 if x['key'] == 'C':
290 reveal_type(x) # N: Revealed type is "TypedDict('__main__.TypedDict1', {'key': Literal['A'] | Literal['C']}) | TypedDict('__main__.TypedDict2', {'key': Literal['B'] | Literal['C']})"
291 else:
292 reveal_type(x) # N: Revealed type is "TypedDict('__main__.TypedDict1', {'key': Literal['A'] | Literal['C']}) | TypedDict('__main__.TypedDict2', {'key': Literal['B'] | Literal['C']})"
293
294 if x['key'] == 'D': # E: Non-overlapping equality check (left operand type: "Literal['A', 'C', 'B']", right operand type: "Literal['D']")
295 reveal_type(x) # E: Statement is unreachable
296 else:
297 reveal_type(x) # N: Revealed type is "TypedDict('__main__.TypedDict1', {'key': Literal['A'] | Literal['C']}) | TypedDict('__main__.TypedDict2', {'key': Literal['B'] | Literal['C']})"
298 [builtins fixtures/primitives.pyi]
299 [typing fixtures/typing-typeddict.pyi]
300
301 [case testNarrowingPartialTypedDictParentMultipleKeys]
302 # flags: --strict-equality --warn-unreachable
303 from typing import Literal, TypedDict, Union
304
305 class TypedDict1(TypedDict, total=False):
306 key: Literal['A', 'C']
307 class TypedDict2(TypedDict, total=False):
308 key: Literal['B', 'C']
309
310 x: Union[TypedDict1, TypedDict2]
311 if x['key'] == 'A':
312 reveal_type(x) # N: Revealed type is "TypedDict('__main__.TypedDict1', {'key'?: Literal['A'] | Literal['C']})"
313 else:
314 reveal_type(x) # N: Revealed type is "TypedDict('__main__.TypedDict1', {'key'?: Literal['A'] | Literal['C']}) | TypedDict('__main__.TypedDict2', {'key'?: Literal['B'] | Literal['C']})"
315
316 if x['key'] == 'C':
317 reveal_type(x) # N: Revealed type is "TypedDict('__main__.TypedDict1', {'key'?: Literal['A'] | Literal['C']}) | TypedDict('__main__.TypedDict2', {'key'?: Literal['B'] | Literal['C']})"
318 else:
319 reveal_type(x) # N: Revealed type is "TypedDict('__main__.TypedDict1', {'key'?: Literal['A'] | Literal['C']}) | TypedDict('__main__.TypedDict2', {'key'?: Literal['B'] | Literal['C']})"
320
321 if x['key'] == 'D': # E: Non-overlapping equality check (left operand type: "Literal['A', 'C', 'B']", right operand type: "Literal['D']")
322 reveal_type(x) # E: Statement is unreachable
323 else:
324 reveal_type(x) # N: Revealed type is "TypedDict('__main__.TypedDict1', {'key'?: Literal['A'] | Literal['C']}) | TypedDict('__main__.TypedDict2', {'key'?: Literal['B'] | Literal['C']})"
325 [builtins fixtures/primitives.pyi]
326 [typing fixtures/typing-typeddict.pyi]
327
328 [case testNarrowingNestedTypedDicts]
329 # flags: --strict-equality --warn-unreachable
330 from typing import Literal, TypedDict, Union
331
332 class A(TypedDict):
333 key: Literal['A']
334 class B(TypedDict):
335 key: Literal['B']
336 class C(TypedDict):
337 key: Literal['C']
338
339 class X(TypedDict):
340 inner: Union[A, B]
341 class Y(TypedDict):
342 inner: Union[B, C]
343
344 unknown: Union[X, Y]
345 if unknown['inner']['key'] == 'A':
346 reveal_type(unknown) # N: Revealed type is "TypedDict('__main__.X', {'inner': TypedDict('__main__.A', {'key': Literal['A']}) | TypedDict('__main__.B', {'key': Literal['B']})})"
347 reveal_type(unknown['inner']) # N: Revealed type is "TypedDict('__main__.A', {'key': Literal['A']})"
348 if unknown['inner']['key'] == 'B':
349 reveal_type(unknown) # N: Revealed type is "TypedDict('__main__.X', {'inner': TypedDict('__main__.A', {'key': Literal['A']}) | TypedDict('__main__.B', {'key': Literal['B']})}) | TypedDict('__main__.Y', {'inner': TypedDict('__main__.B', {'key': Literal['B']}) | TypedDict('__main__.C', {'key': Literal['C']})})"
350 reveal_type(unknown['inner']) # N: Revealed type is "TypedDict('__main__.B', {'key': Literal['B']})"
351 if unknown['inner']['key'] == 'C':
352 reveal_type(unknown) # N: Revealed type is "TypedDict('__main__.Y', {'inner': TypedDict('__main__.B', {'key': Literal['B']}) | TypedDict('__main__.C', {'key': Literal['C']})})"
353 reveal_type(unknown['inner']) # N: Revealed type is "TypedDict('__main__.C', {'key': Literal['C']})"
354 [builtins fixtures/primitives.pyi]
355 [typing fixtures/typing-typeddict.pyi]
356
357 [case testNarrowingParentWithMultipleParents]
358 # flags: --strict-equality --warn-unreachable
359 from enum import Enum
360 from typing import Literal, Union
361
362 class Key(Enum):
363 A = 1
364 B = 2
365 C = 3
366
367 class Object1:
368 key: Literal[Key.A]
369 class Object2:
370 key: Literal[Key.B]
371 class Object3:
372 key: Literal[Key.C]
373 class Object4:
374 key: str
375
376 x: Union[Object1, Object2, Object3, Object4]
377 if x.key is Key.A:
378 reveal_type(x) # N: Revealed type is "__main__.Object1"
379 else:
380 reveal_type(x) # N: Revealed type is "__main__.Object2 | __main__.Object3 | __main__.Object4"
381
382 if isinstance(x.key, str):
383 reveal_type(x) # N: Revealed type is "__main__.Object4"
384 else:
385 reveal_type(x) # N: Revealed type is "__main__.Object1 | __main__.Object2 | __main__.Object3"
386 [builtins fixtures/isinstance.pyi]
387
388 [case testNarrowingParentsWithGenerics]
389 # flags: --strict-equality --warn-unreachable
390 from typing import Union, TypeVar, Generic
391
392 T = TypeVar('T')
393 class Wrapper(Generic[T]):
394 key: T
395
396 x: Union[Wrapper[int], Wrapper[str]]
397 if isinstance(x.key, int):
398 reveal_type(x) # N: Revealed type is "__main__.Wrapper[builtins.int]"
399 else:
400 reveal_type(x) # N: Revealed type is "__main__.Wrapper[builtins.str]"
401 [builtins fixtures/isinstance.pyi]
402
403 [case testNarrowingParentWithParentMixtures]
404 # flags: --strict-equality --warn-unreachable
405 from enum import Enum
406 from typing import Literal, Union, NamedTuple, TypedDict
407
408 class Key(Enum):
409 A = 1
410 B = 2
411 C = 3
412
413 class KeyedObject:
414 key: Literal[Key.A]
415 class KeyedTypedDict(TypedDict):
416 key: Literal[Key.B]
417 class KeyedNamedTuple(NamedTuple):
418 key: Literal[Key.C]
419
420 ok_mixture: Union[KeyedObject, KeyedNamedTuple]
421 if ok_mixture.key is Key.A:
422 reveal_type(ok_mixture) # N: Revealed type is "__main__.KeyedObject"
423 else:
424 reveal_type(ok_mixture) # N: Revealed type is "tuple[Literal[__main__.Key.C], fallback=__main__.KeyedNamedTuple]"
425
426 impossible_mixture: Union[KeyedObject, KeyedTypedDict]
427 if impossible_mixture.key is Key.A: # E: Item "KeyedTypedDict" of "KeyedObject | KeyedTypedDict" has no attribute "key"
428 reveal_type(impossible_mixture) # N: Revealed type is "__main__.KeyedObject | TypedDict('__main__.KeyedTypedDict', {'key': Literal[__main__.Key.B]})"
429 else:
430 reveal_type(impossible_mixture) # N: Revealed type is "__main__.KeyedObject | TypedDict('__main__.KeyedTypedDict', {'key': Literal[__main__.Key.B]})"
431
432 if impossible_mixture["key"] is Key.A: # E: Value of type "KeyedObject | KeyedTypedDict" is not indexable
433 reveal_type(impossible_mixture) # N: Revealed type is "__main__.KeyedObject | TypedDict('__main__.KeyedTypedDict', {'key': Literal[__main__.Key.B]})"
434 else:
435 reveal_type(impossible_mixture) # N: Revealed type is "__main__.KeyedObject | TypedDict('__main__.KeyedTypedDict', {'key': Literal[__main__.Key.B]})"
436
437 weird_mixture: Union[KeyedTypedDict, KeyedNamedTuple]
438 if weird_mixture["key"] is Key.B: # E: No overload variant of "__getitem__" of "tuple" matches argument type "str" \
439 # N: Possible overload variants: \
440 # N: def __getitem__(self, int, /) -> Literal[Key.C] \
441 # N: def __getitem__(self, slice[int | None], /) -> tuple[Literal[Key.C], ...]
442 reveal_type(weird_mixture) # N: Revealed type is "TypedDict('__main__.KeyedTypedDict', {'key': Literal[__main__.Key.B]}) | tuple[Literal[__main__.Key.C], fallback=__main__.KeyedNamedTuple]"
443 else:
444 reveal_type(weird_mixture) # N: Revealed type is "TypedDict('__main__.KeyedTypedDict', {'key': Literal[__main__.Key.B]}) | tuple[Literal[__main__.Key.C], fallback=__main__.KeyedNamedTuple]"
445
446 if weird_mixture[0] is Key.B: # E: TypedDict key must be a string literal; expected one of ("key")
447 reveal_type(weird_mixture) # N: Revealed type is "TypedDict('__main__.KeyedTypedDict', {'key': Literal[__main__.Key.B]}) | tuple[Literal[__main__.Key.C], fallback=__main__.KeyedNamedTuple]"
448 else:
449 reveal_type(weird_mixture) # N: Revealed type is "TypedDict('__main__.KeyedTypedDict', {'key': Literal[__main__.Key.B]}) | tuple[Literal[__main__.Key.C], fallback=__main__.KeyedNamedTuple]"
450 [builtins fixtures/tuple.pyi]
451 [typing fixtures/typing-full.pyi]
452
453 [case testNarrowingParentWithProperties]
454 # flags: --strict-equality --warn-unreachable
455 from enum import Enum
456 from typing import Literal, Union
457
458 class Key(Enum):
459 A = 1
460 B = 2
461 C = 3
462
463 class Object1:
464 key: Literal[Key.A]
465
466 class Object2:
467 @property
468 def key(self) -> Literal[Key.A]: ...
469
470 class Object3:
471 @property
472 def key(self) -> Literal[Key.B]: ...
473
474 x: Union[Object1, Object2, Object3]
475 if x.key is Key.A:
476 reveal_type(x) # N: Revealed type is "__main__.Object1 | __main__.Object2"
477 else:
478 reveal_type(x) # N: Revealed type is "__main__.Object3"
479 [builtins fixtures/property.pyi]
480
481 [case testNarrowingParentWithAny]
482 # flags: --strict-equality --warn-unreachable
483 from enum import Enum
484 from typing import Literal, Union, Any
485
486 class Key(Enum):
487 A = 1
488 B = 2
489 C = 3
490
491 class Object1:
492 key: Literal[Key.A]
493
494 class Object2:
495 key: Literal[Key.B]
496
497 x: Union[Object1, Object2, Any]
498 if x.key is Key.A:
499 reveal_type(x.key) # N: Revealed type is "Literal[__main__.Key.A]"
500 reveal_type(x) # N: Revealed type is "__main__.Object1 | Any"
501 else:
502 # TODO: Is this a bug? Should we skip inferring Any for singleton types?
503 reveal_type(x.key) # N: Revealed type is "Any | Literal[__main__.Key.B]"
504 reveal_type(x) # N: Revealed type is "__main__.Object1 | __main__.Object2 | Any"
505 [builtins fixtures/tuple.pyi]
506
507 [case testNarrowingParentsHierarchy]
508 # flags: --strict-equality --warn-unreachable
509 from typing import Literal, Union
510 from enum import Enum
511
512 class Key(Enum):
513 A = 1
514 B = 2
515 C = 3
516
517 class Parent1:
518 child: Union[Child1, Child2]
519 class Parent2:
520 child: Union[Child2, Child3]
521 class Parent3:
522 child: Union[Child3, Child1]
523
524 class Child1:
525 main: Literal[Key.A]
526 same_for_1_and_2: Literal[Key.A]
527 class Child2:
528 main: Literal[Key.B]
529 same_for_1_and_2: Literal[Key.A]
530 class Child3:
531 main: Literal[Key.C]
532 same_for_1_and_2: Literal[Key.B]
533
534 x: Union[Parent1, Parent2, Parent3]
535 if x.child.main is Key.A:
536 reveal_type(x) # N: Revealed type is "__main__.Parent1 | __main__.Parent3"
537 reveal_type(x.child) # N: Revealed type is "__main__.Child1"
538 else:
539 reveal_type(x) # N: Revealed type is "__main__.Parent1 | __main__.Parent2 | __main__.Parent3"
540 reveal_type(x.child) # N: Revealed type is "__main__.Child2 | __main__.Child3"
541
542 if x.child.same_for_1_and_2 is Key.A:
543 reveal_type(x) # N: Revealed type is "__main__.Parent1 | __main__.Parent2 | __main__.Parent3"
544 reveal_type(x.child) # N: Revealed type is "__main__.Child1 | __main__.Child2"
545 else:
546 reveal_type(x) # N: Revealed type is "__main__.Parent2 | __main__.Parent3"
547 reveal_type(x.child) # N: Revealed type is "__main__.Child3"
548
549 y: Union[Parent1, Parent2]
550 if y.child.main is Key.A:
551 reveal_type(y) # N: Revealed type is "__main__.Parent1"
552 reveal_type(y.child) # N: Revealed type is "__main__.Child1"
553 else:
554 reveal_type(y) # N: Revealed type is "__main__.Parent1 | __main__.Parent2"
555 reveal_type(y.child) # N: Revealed type is "__main__.Child2 | __main__.Child3"
556
557 if y.child.same_for_1_and_2 is Key.A:
558 reveal_type(y) # N: Revealed type is "__main__.Parent1 | __main__.Parent2"
559 reveal_type(y.child) # N: Revealed type is "__main__.Child1 | __main__.Child2"
560 else:
561 reveal_type(y) # N: Revealed type is "__main__.Parent2"
562 reveal_type(y.child) # N: Revealed type is "__main__.Child3"
563 [builtins fixtures/tuple.pyi]
564
565 [case testNarrowingParentsHierarchyGenerics]
566 # flags: --strict-equality --warn-unreachable
567 from typing import Generic, TypeVar, Union
568
569 T = TypeVar('T')
570 class Model(Generic[T]):
571 attr: T
572 class A:
573 model: Model[int]
574 class B:
575 model: Model[str]
576
577 x: Union[A, B]
578 if isinstance(x.model.attr, int):
579 reveal_type(x) # N: Revealed type is "__main__.A"
580 reveal_type(x.model) # N: Revealed type is "__main__.Model[builtins.int]"
581 else:
582 reveal_type(x) # N: Revealed type is "__main__.B"
583 reveal_type(x.model) # N: Revealed type is "__main__.Model[builtins.str]"
584 [builtins fixtures/isinstance.pyi]
585
586 [case testNarrowingParentsHierarchyTypedDict]
587 # flags: --strict-equality --warn-unreachable
588 from typing import Literal, TypedDict, Union
589 from enum import Enum
590
591 class Key(Enum):
592 A = 1
593 B = 2
594 C = 3
595
596 class Parent1(TypedDict):
597 model: Model1
598 foo: int
599
600 class Parent2(TypedDict):
601 model: Model2
602 bar: str
603
604 class Model1(TypedDict):
605 key: Literal[Key.A]
606
607 class Model2(TypedDict):
608 key: Literal[Key.B]
609
610 x: Union[Parent1, Parent2]
611 if x["model"]["key"] is Key.A:
612 reveal_type(x) # N: Revealed type is "TypedDict('__main__.Parent1', {'model': TypedDict('__main__.Model1', {'key': Literal[__main__.Key.A]}), 'foo': builtins.int})"
613 reveal_type(x["model"]) # N: Revealed type is "TypedDict('__main__.Model1', {'key': Literal[__main__.Key.A]})"
614 else:
615 reveal_type(x) # N: Revealed type is "TypedDict('__main__.Parent2', {'model': TypedDict('__main__.Model2', {'key': Literal[__main__.Key.B]}), 'bar': builtins.str})"
616 reveal_type(x["model"]) # N: Revealed type is "TypedDict('__main__.Model2', {'key': Literal[__main__.Key.B]})"
617
618 y: Union[Parent1, Parent2]
619 if y["model"]["key"] is Key.C: # E: Non-overlapping identity check (left operand type: "Literal[Key.A, Key.B]", right operand type: "Literal[Key.C]")
620 reveal_type(y) # E: Statement is unreachable
621 reveal_type(y["model"])
622 else:
623 reveal_type(y) # N: Revealed type is "TypedDict('__main__.Parent1', {'model': TypedDict('__main__.Model1', {'key': Literal[__main__.Key.A]}), 'foo': builtins.int}) | TypedDict('__main__.Parent2', {'model': TypedDict('__main__.Model2', {'key': Literal[__main__.Key.B]}), 'bar': builtins.str})"
624 reveal_type(y["model"]) # N: Revealed type is "TypedDict('__main__.Model1', {'key': Literal[__main__.Key.A]}) | TypedDict('__main__.Model2', {'key': Literal[__main__.Key.B]})"
625 [builtins fixtures/dict.pyi]
626 [typing fixtures/typing-typeddict.pyi]
627
628 [case testNarrowingParentsHierarchyTypedDictWithStr]
629 # flags: --strict-equality --warn-unreachable
630 from typing import Literal, TypedDict, Union
631
632 class Parent1(TypedDict):
633 model: Model1
634 foo: int
635
636 class Parent2(TypedDict):
637 model: Model2
638 bar: str
639
640 class Model1(TypedDict):
641 key: Literal['A']
642
643 class Model2(TypedDict):
644 key: Literal['B']
645
646 x: Union[Parent1, Parent2]
647 if x["model"]["key"] == 'A':
648 reveal_type(x) # N: Revealed type is "TypedDict('__main__.Parent1', {'model': TypedDict('__main__.Model1', {'key': Literal['A']}), 'foo': builtins.int})"
649 reveal_type(x["model"]) # N: Revealed type is "TypedDict('__main__.Model1', {'key': Literal['A']})"
650 else:
651 reveal_type(x) # N: Revealed type is "TypedDict('__main__.Parent2', {'model': TypedDict('__main__.Model2', {'key': Literal['B']}), 'bar': builtins.str})"
652 reveal_type(x["model"]) # N: Revealed type is "TypedDict('__main__.Model2', {'key': Literal['B']})"
653
654 y: Union[Parent1, Parent2]
655 if y["model"]["key"] == 'C': # E: Non-overlapping equality check (left operand type: "Literal['A', 'B']", right operand type: "Literal['C']")
656 reveal_type(y) # E: Statement is unreachable
657 reveal_type(y["model"])
658 else:
659 reveal_type(y) # N: Revealed type is "TypedDict('__main__.Parent1', {'model': TypedDict('__main__.Model1', {'key': Literal['A']}), 'foo': builtins.int}) | TypedDict('__main__.Parent2', {'model': TypedDict('__main__.Model2', {'key': Literal['B']}), 'bar': builtins.str})"
660 reveal_type(y["model"]) # N: Revealed type is "TypedDict('__main__.Model1', {'key': Literal['A']}) | TypedDict('__main__.Model2', {'key': Literal['B']})"
661 [builtins fixtures/primitives.pyi]
662 [typing fixtures/typing-typeddict.pyi]
663
664 [case testNarrowingExprPropagation]
665 # flags: --strict-equality --warn-unreachable
666 from typing import Literal, Union
667
668 class A:
669 tag: Literal['A']
670
671 class B:
672 tag: Literal['B']
673
674 abo: Union[A, B, None]
675
676 if abo is not None and abo.tag == "A":
677 reveal_type(abo.tag) # N: Revealed type is "Literal['A']"
678 reveal_type(abo) # N: Revealed type is "__main__.A"
679
680 if not (abo is None or abo.tag != "B"):
681 reveal_type(abo.tag) # N: Revealed type is "Literal['B']"
682 reveal_type(abo) # N: Revealed type is "__main__.B"
683 [builtins fixtures/primitives.pyi]
684
685 [case testNarrowingEqualityFlipFlop]
686 # flags: --strict-equality --warn-unreachable
687 from typing import Final, Literal
688 from enum import Enum
689
690 class State(Enum):
691 A = 1
692 B = 2
693
694 class FlipFlopEnum:
695 def __init__(self) -> None:
696 self.state = State.A
697
698 def mutate(self) -> None:
699 self.state = State.B if self.state == State.A else State.A
700
701 class FlipFlopStr:
702 def __init__(self) -> None:
703 self.state = "state-1"
704
705 def mutate(self) -> None:
706 self.state = "state-2" if self.state == "state-1" else "state-1"
707
708
709 def test1(switch: FlipFlopStr) -> None:
710 # Naively, we might assume the 'assert' here would narrow the type to
711 # Literal["state-1"]. However, doing this ends up breaking a fair number of real-world
712 # code (usually test cases) that looks similar to this function: e.g. checks
713 # to make sure a field was mutated to some particular value.
714 #
715 # And since mypy can't really reason about state mutation, we take a conservative
716 # approach and avoid narrowing anything here.
717
718 assert switch.state == "state-1"
719 reveal_type(switch.state) # N: Revealed type is "builtins.str"
720
721 switch.mutate()
722
723 assert switch.state == "state-2"
724 reveal_type(switch.state) # N: Revealed type is "builtins.str"
725
726 def test2(switch: FlipFlopEnum) -> None:
727 # This is the same thing as 'test1', except we use enums, which we allow to be narrowed
728 # to literals.
729
730 assert switch.state == State.A
731 reveal_type(switch.state) # N: Revealed type is "Literal[__main__.State.A]"
732
733 switch.mutate()
734
735 assert switch.state == State.B # E: Non-overlapping equality check (left operand type: "Literal[State.A]", right operand type: "Literal[State.B]")
736 reveal_type(switch.state) # E: Statement is unreachable
737
738 def test3(switch: FlipFlopEnum) -> None:
739 # Same thing, but using 'is' comparisons. Previously mypy's behaviour differed
740 # here, narrowing when using 'is', but not when using '=='.
741
742 assert switch.state is State.A
743 reveal_type(switch.state) # N: Revealed type is "Literal[__main__.State.A]"
744
745 switch.mutate()
746
747 assert switch.state is State.B # E: Non-overlapping identity check (left operand type: "Literal[State.A]", right operand type: "Literal[State.B]")
748 reveal_type(switch.state) # E: Statement is unreachable
749 [builtins fixtures/primitives.pyi]
750
751 [case testNarrowingEqualityRequiresExplicitStrLiteral]
752 # flags: --strict-equality --warn-unreachable
753 from typing import Final, Literal
754
755 A_final: Final = "A"
756 A_literal: Literal["A"]
757
758 # Neither the LHS nor the RHS are explicit literals, so regrettably nothing
759 # is narrowed here -- see 'testNarrowingEqualityFlipFlop' for an example of
760 # why more precise inference here is problematic.
761 x_str: str
762 if x_str == "A":
763 reveal_type(x_str) # N: Revealed type is "builtins.str"
764 else:
765 reveal_type(x_str) # N: Revealed type is "builtins.str"
766 reveal_type(x_str) # N: Revealed type is "builtins.str"
767
768 if x_str == A_final:
769 reveal_type(x_str) # N: Revealed type is "builtins.str"
770 else:
771 reveal_type(x_str) # N: Revealed type is "builtins.str"
772 reveal_type(x_str) # N: Revealed type is "builtins.str"
773
774 # But the RHS is a literal, so we can at least narrow the 'if' case now.
775 if x_str == A_literal:
776 reveal_type(x_str) # N: Revealed type is "Literal['A']"
777 else:
778 reveal_type(x_str) # N: Revealed type is "builtins.str"
779 reveal_type(x_str) # N: Revealed type is "builtins.str"
780
781 # But in these two cases, the LHS is a literal/literal-like type. So we
782 # assume the user *does* want literal-based narrowing and narrow accordingly
783 # regardless of whether the RHS is an explicit literal or not.
784 x_union: Literal["A", "B", None]
785 if x_union == A_final:
786 reveal_type(x_union) # N: Revealed type is "Literal['A']"
787 else:
788 reveal_type(x_union) # N: Revealed type is "Literal['B'] | None"
789 reveal_type(x_union) # N: Revealed type is "Literal['A'] | Literal['B'] | None"
790
791 if x_union == A_literal:
792 reveal_type(x_union) # N: Revealed type is "Literal['A']"
793 else:
794 reveal_type(x_union) # N: Revealed type is "Literal['B'] | None"
795 reveal_type(x_union) # N: Revealed type is "Literal['A'] | Literal['B'] | None"
796 [builtins fixtures/primitives.pyi]
797
798 [case testNarrowingEqualityRequiresExplicitEnumLiteral]
799 # flags: --strict-equality --warn-unreachable
800 from typing import Final, Literal, Union
801 from enum import Enum
802
803 class Foo(Enum):
804 A = 1
805 B = 2
806
807 A_final: Final = Foo.A
808 A_literal: Literal[Foo.A]
809
810 # Note this is unlike testNarrowingEqualityRequiresExplicitStrLiteral
811 # See also testNarrowingEqualityFlipFlop
812 x1: Foo
813 if x1 == Foo.A:
814 reveal_type(x1) # N: Revealed type is "Literal[__main__.Foo.A]"
815 else:
816 reveal_type(x1) # N: Revealed type is "Literal[__main__.Foo.B]"
817
818 x2: Foo
819 if x2 == A_final:
820 reveal_type(x2) # N: Revealed type is "Literal[__main__.Foo.A]"
821 else:
822 reveal_type(x2) # N: Revealed type is "Literal[__main__.Foo.B]"
823
824 # But we let this narrow since there's an explicit literal in the RHS.
825 x3: Foo
826 if x3 == A_literal:
827 reveal_type(x3) # N: Revealed type is "Literal[__main__.Foo.A]"
828 else:
829 reveal_type(x3) # N: Revealed type is "Literal[__main__.Foo.B]"
830
831
832 class SingletonFoo(Enum):
833 A = "A"
834
835 def bar(x: Union[SingletonFoo, Foo], y: SingletonFoo) -> None:
836 if x == y:
837 reveal_type(x) # N: Revealed type is "Literal[__main__.SingletonFoo.A]"
838 [builtins fixtures/primitives.pyi]
839
840 [case testNarrowingEqualityCustomEqualityDisabled]
841 # flags: --strict-equality --warn-unreachable
842 from typing import Literal, Union
843
844 class Custom:
845 def __eq__(self, other: object) -> bool: return True
846
847 def f1(x: Union[Custom, Literal[1], Literal[2]]):
848 if x == 1:
849 reveal_type(x) # N: Revealed type is "__main__.Custom | Literal[1]"
850 else:
851 reveal_type(x) # N: Revealed type is "__main__.Custom | Literal[2]"
852
853 class Default: pass
854
855 def f2(x: Union[Default, Literal[1], Literal[2]]):
856 if x == 1:
857 reveal_type(x) # N: Revealed type is "Literal[1]"
858 else:
859 reveal_type(x) # N: Revealed type is "__main__.Default | Literal[2]"
860 [builtins fixtures/primitives.pyi]
861
862 [case testNarrowingEqualityCustomEqualityEnum]
863 # flags: --strict-equality --warn-unreachable
864 from typing import Literal, Union
865 from enum import Enum
866
867 class CustomEnum(Enum):
868 A = 1
869 B = 2
870
871 def __eq__(self, other: object) -> bool: return True
872
873 x3: CustomEnum
874 key: Literal[CustomEnum.A]
875 if x3 == key:
876 reveal_type(x3) # N: Revealed type is "__main__.CustomEnum"
877 else:
878 reveal_type(x3) # N: Revealed type is "Literal[__main__.CustomEnum.B]"
879
880 # For comparison, this narrows since we bypass __eq__
881 if x3 is key:
882 reveal_type(x3) # N: Revealed type is "Literal[__main__.CustomEnum.A]"
883 else:
884 reveal_type(x3) # N: Revealed type is "Literal[__main__.CustomEnum.B]"
885 [builtins fixtures/primitives.pyi]
886
887 [case testNarrowingEqualityCustomEqualityChainedComparison]
888 # flags: --strict-equality --warn-unreachable
889 from typing import Literal, Union
890
891 class Custom:
892 def __eq__(self, other: object) -> bool: return True
893
894 def f1(x: Literal[1, 2, None], y: Custom):
895 if 1 == x == y:
896 reveal_type(x) # N: Revealed type is "Literal[1]"
897 reveal_type(y) # N: Revealed type is "__main__.Custom"
898 else:
899 reveal_type(x) # N: Revealed type is "Literal[1] | Literal[2] | None"
900 reveal_type(y) # N: Revealed type is "__main__.Custom"
901
902 class Default: pass
903
904 def f2(x: Literal[1, 2, None], z: Default):
905 if 1 == x == z: # E: Non-overlapping equality check (left operand type: "Literal[1, 2] | None", right operand type: "Default")
906 reveal_type(x) # E: Statement is unreachable
907 reveal_type(z)
908 else:
909 reveal_type(x) # N: Revealed type is "Literal[1] | Literal[2] | None"
910 reveal_type(z) # N: Revealed type is "__main__.Default"
911 [builtins fixtures/primitives.pyi]
912
913 [case testNarrowingCustomEqualityLiteralElseBranch]
914 # flags: --strict-equality --warn-unreachable
915 from __future__ import annotations
916 from typing import Literal
917
918 class Custom:
919 def __eq__(self, other: object) -> bool:
920 raise
921
922 def f(v: Custom | Literal["text"]) -> Custom | None:
923 if v == "text":
924 reveal_type(v) # N: Revealed type is "__main__.Custom | Literal['text']"
925 return None
926 else:
927 reveal_type(v) # N: Revealed type is "__main__.Custom"
928 return v
929
930 def g(v: Custom | Literal["text"]) -> Custom | None:
931 if v != "text":
932 reveal_type(v) # N: Revealed type is "__main__.Custom"
933 return None
934 else:
935 reveal_type(v) # N: Revealed type is "__main__.Custom | Literal['text']"
936 return v # E: Incompatible return value type (got "Custom | Literal['text']", expected "Custom | None")
937 [builtins fixtures/primitives.pyi]
938
939 [case testNarrowingCustomEqualityUnion]
940 # flags: --strict-equality --warn-unreachable
941 from __future__ import annotations
942 from typing import Any
943
944 def realistic(x: dict[str, Any]):
945 val = x.get("hey")
946 if val == 12:
947 reveal_type(val) # N: Revealed type is "Any"
948
949 def f1(x: Any | None):
950 if x == 12:
951 reveal_type(x) # N: Revealed type is "Any"
952
953 class Custom:
954 def __eq__(self, other: object) -> bool:
955 raise
956
957 def f2(x: Custom | None):
958 if x == 12:
959 reveal_type(x) # N: Revealed type is "__main__.Custom"
960 else:
961 reveal_type(x) # N: Revealed type is "__main__.Custom | None"
962 [builtins fixtures/dict.pyi]
963
964 [case testNarrowingCustomEqualityUnion2]
965 # flags: --strict-equality --warn-unreachable
966 from __future__ import annotations
967 from typing import Any
968
969 class Custom:
970 def __eq__(self, other: object) -> bool:
971 raise
972
973 def f3(x: str | Custom, y: str | int):
974 if x == y:
975 reveal_type(x) # N: Revealed type is "builtins.str | __main__.Custom"
976 reveal_type(y) # N: Revealed type is "builtins.str | builtins.int"
977 else:
978 reveal_type(x) # N: Revealed type is "builtins.str | __main__.Custom"
979 reveal_type(y) # N: Revealed type is "builtins.str | builtins.int"
980
981 def f4(x: str | Any, y: str | int):
982 if x == y:
983 reveal_type(x) # N: Revealed type is "builtins.str | Any"
984 reveal_type(y) # N: Revealed type is "builtins.str | builtins.int"
985 else:
986 reveal_type(x) # N: Revealed type is "builtins.str | Any"
987 reveal_type(y) # N: Revealed type is "builtins.str | builtins.int"
988 [builtins fixtures/dict.pyi]
989
990 [case testNarrowingCustomEqualityUnion3]
991 # flags: --strict-equality --warn-unreachable
992 from __future__ import annotations
993 from typing import Any
994
995 class Custom:
996 def __eq__(self, other: object) -> bool:
997 raise
998
999 def f(x: Custom | None, y: int | None):
1000 if x == y:
1001 reveal_type(x) # N: Revealed type is "__main__.Custom | None"
1002 reveal_type(y) # N: Revealed type is "builtins.int | None"
1003 else:
1004 reveal_type(x) # N: Revealed type is "__main__.Custom | None"
1005 reveal_type(y) # N: Revealed type is "builtins.int | None"
1006 [builtins fixtures/primitives.pyi]
1007
1008 [case testNarrowingCustomEqualityUnion4]
1009 # flags: --strict-equality --warn-unreachable
1010 from __future__ import annotations
1011
1012 class Custom:
1013 def __eq__(self, other: object) -> bool:
1014 return True
1015
1016 def f(x: Custom | None, y: Custom):
1017 if x == y:
1018 # We unsoundly special case None and narrow x to Custom here
1019 reveal_type(x) # N: Revealed type is "__main__.Custom"
1020 else:
1021 reveal_type(x) # N: Revealed type is "__main__.Custom | None"
1022 [builtins fixtures/primitives.pyi]
1023
1024 [case testNarrowingCustomEqualityUnion5]
1025 # flags: --strict-equality --warn-unreachable
1026 from __future__ import annotations
1027 from typing import Any
1028
1029 class Custom1:
1030 def __eq__(self, other: object) -> bool:
1031 raise
1032
1033 class Custom2:
1034 def __eq__(self, other: object) -> bool:
1035 raise
1036
1037 def f(x: Custom1 | int, y: Custom2 | int):
1038 if x == y:
1039 reveal_type(x) # N: Revealed type is "__main__.Custom1 | builtins.int"
1040 reveal_type(y) # N: Revealed type is "__main__.Custom2 | builtins.int"
1041 else:
1042 reveal_type(x) # N: Revealed type is "__main__.Custom1 | builtins.int"
1043 reveal_type(y) # N: Revealed type is "__main__.Custom2 | builtins.int"
1044 [builtins fixtures/primitives.pyi]
1045
1046 [case testNarrowingCustomEqualitySubclass]
1047 # flags: --strict-equality --warn-unreachable
1048 from __future__ import annotations
1049 from typing import Any
1050
1051 class Custom:
1052 def __eq__(self, other: object) -> bool:
1053 raise
1054
1055 class CustomSub(Custom):
1056 def __eq__(self, other: object) -> bool:
1057 raise
1058
1059 def f(x: Custom, y: CustomSub):
1060 if x == y:
1061 reveal_type(x) # N: Revealed type is "__main__.Custom"
1062 reveal_type(y) # N: Revealed type is "__main__.CustomSub"
1063 else:
1064 reveal_type(x) # N: Revealed type is "__main__.Custom"
1065 reveal_type(y) # N: Revealed type is "__main__.CustomSub"
1066 [builtins fixtures/tuple.pyi]
1067
1068 [case testNarrowingCustomEqualityGeneric]
1069 # flags: --strict-equality --warn-unreachable
1070 from __future__ import annotations
1071 from typing import Union
1072
1073 class Custom:
1074 def __eq__(self, other: object) -> bool:
1075 raise
1076
1077 class Default: ...
1078
1079 def f1(x: list[Custom] | Default, y: list[int]):
1080 if x == y: # E: Non-overlapping equality check (left operand type: "list[Custom] | Default", right operand type: "list[int]")
1081 reveal_type(x) # N: Revealed type is "builtins.list[__main__.Custom]"
1082 reveal_type(y) # N: Revealed type is "builtins.list[builtins.int]"
1083 else:
1084 reveal_type(x) # N: Revealed type is "builtins.list[__main__.Custom] | __main__.Default"
1085 reveal_type(y) # N: Revealed type is "builtins.list[builtins.int]"
1086
1087 f1([], [])
1088
1089 def f2(x: list[Custom] | Default, y: list[int] | list[Default]):
1090 if x == y: # E: Non-overlapping equality check (left operand type: "list[Custom] | Default", right operand type: "list[int] | list[Default]")
1091 reveal_type(x) # N: Revealed type is "builtins.list[__main__.Custom]"
1092 reveal_type(y) # N: Revealed type is "builtins.list[builtins.int] | builtins.list[__main__.Default]"
1093 else:
1094 reveal_type(x) # N: Revealed type is "builtins.list[__main__.Custom] | __main__.Default"
1095 reveal_type(y) # N: Revealed type is "builtins.list[builtins.int] | builtins.list[__main__.Default]"
1096
1097 listcustom_or_default = Union[list[Custom], Default]
1098 listint_or_default = Union[list[int], list[Default]]
1099
1100 def f2_with_alias(x: listcustom_or_default, y: listint_or_default):
1101 if x == y: # E: Non-overlapping equality check (left operand type: "list[Custom] | Default", right operand type: "list[int] | list[Default]")
1102 reveal_type(x) # N: Revealed type is "builtins.list[__main__.Custom]"
1103 reveal_type(y) # N: Revealed type is "builtins.list[builtins.int] | builtins.list[__main__.Default]"
1104 else:
1105 reveal_type(x) # N: Revealed type is "builtins.list[__main__.Custom] | __main__.Default"
1106 reveal_type(y) # N: Revealed type is "builtins.list[builtins.int] | builtins.list[__main__.Default]"
1107
1108 def f3(x: Custom | dict[str, str], y: dict[int, int]):
1109 if x == y:
1110 reveal_type(x) # N: Revealed type is "__main__.Custom | builtins.dict[builtins.str, builtins.str]"
1111 reveal_type(y) # N: Revealed type is "builtins.dict[builtins.int, builtins.int]"
1112 else:
1113 reveal_type(x) # N: Revealed type is "__main__.Custom | builtins.dict[builtins.str, builtins.str]"
1114 reveal_type(y) # N: Revealed type is "builtins.dict[builtins.int, builtins.int]"
1115 [builtins fixtures/primitives.pyi]
1116
1117 [case testNarrowingRecursiveCallable]
1118 # flags: --strict-equality --warn-unreachable
1119 from __future__ import annotations
1120 from typing import Callable
1121
1122 class A: ...
1123 class B: ...
1124
1125 T = Callable[[A], "S"]
1126 S = Callable[[B], "T"]
1127
1128 def f(x: S, y: T):
1129 if x == y: # E: Unsupported left operand type for == ("Callable[[B], T]")
1130 reveal_type(x) # E: Statement is unreachable
1131 reveal_type(y)
1132 else:
1133 reveal_type(x) # N: Revealed type is "def (__main__.B) -> def (__main__.A) -> ..."
1134 reveal_type(y) # N: Revealed type is "def (__main__.A) -> def (__main__.B) -> ..."
1135 [builtins fixtures/tuple.pyi]
1136
1137 [case testNarrowingRecursiveUnion]
1138 # flags: --strict-equality --warn-unreachable
1139 from __future__ import annotations
1140 from typing import Union
1141
1142 class A: ...
1143 class B: ...
1144
1145 T = Union[A, "S"]
1146 S = Union[B, "T"] # E: Invalid recursive alias: a union item of itself
1147
1148 def f(x: S, y: T):
1149 if x == y:
1150 reveal_type(x) # N: Revealed type is "Any"
1151 reveal_type(y) # N: Revealed type is "__main__.A | Any"
1152 [builtins fixtures/tuple.pyi]
1153
1154 [case testNarrowingUnreachableCases]
1155 # flags: --strict-equality --warn-unreachable
1156 from typing import Literal, Union
1157
1158 a: Literal[1]
1159 b: Literal[1, 2]
1160 c: Literal[2, 3]
1161
1162 if a == b == c:
1163 reveal_type(a) # E: Statement is unreachable
1164 reveal_type(b)
1165 reveal_type(c)
1166 else:
1167 reveal_type(a) # N: Revealed type is "Literal[1]"
1168 reveal_type(b) # N: Revealed type is "Literal[1] | Literal[2]"
1169 reveal_type(c) # N: Revealed type is "Literal[2] | Literal[3]"
1170
1171 if a == a == a:
1172 reveal_type(a) # N: Revealed type is "Literal[1]"
1173 else:
1174 reveal_type(a) # E: Statement is unreachable
1175
1176 if a == a == b:
1177 reveal_type(a) # N: Revealed type is "Literal[1]"
1178 reveal_type(b) # N: Revealed type is "Literal[1]"
1179 else:
1180 reveal_type(a) # N: Revealed type is "Literal[1]"
1181 reveal_type(b) # N: Revealed type is "Literal[2]"
1182
1183 # In this case, it's ok for 'b' to narrow down to Literal[1] in the else case
1184 # since that's the only way 'b == 2' can be false
1185 if b == 2:
1186 reveal_type(b) # N: Revealed type is "Literal[2]"
1187 else:
1188 reveal_type(b) # N: Revealed type is "Literal[1]"
1189
1190 # But in this case, we can't conclude anything about the else case. This expression
1191 # could end up being either '2 == 2 == 3' or '1 == 2 == 2', which means we can't
1192 # conclude anything.
1193 if b == 2 == c:
1194 reveal_type(b) # N: Revealed type is "Literal[2]"
1195 reveal_type(c) # N: Revealed type is "Literal[2]"
1196 else:
1197 reveal_type(b) # N: Revealed type is "Literal[1] | Literal[2]"
1198 reveal_type(c) # N: Revealed type is "Literal[2] | Literal[3]"
1199 [builtins fixtures/primitives.pyi]
1200
1201 [case testNarrowingUnreachableCases2]
1202 # flags: --strict-equality --warn-unreachable
1203 from typing import Literal, Union
1204
1205 a: Literal[1, 2, 3, 4]
1206 b: Literal[1, 2, 3, 4]
1207
1208 if a == b == 1:
1209 reveal_type(a) # N: Revealed type is "Literal[1]"
1210 reveal_type(b) # N: Revealed type is "Literal[1]"
1211 elif a == b == 2:
1212 reveal_type(a) # N: Revealed type is "Literal[2]"
1213 reveal_type(b) # N: Revealed type is "Literal[2]"
1214 elif a == b == 3:
1215 reveal_type(a) # N: Revealed type is "Literal[3]"
1216 reveal_type(b) # N: Revealed type is "Literal[3]"
1217 elif a == b == 4:
1218 reveal_type(a) # N: Revealed type is "Literal[4]"
1219 reveal_type(b) # N: Revealed type is "Literal[4]"
1220 else:
1221 # This branch is reachable if a == 1 and b == 2, for example.
1222 reveal_type(a) # N: Revealed type is "Literal[1] | Literal[2] | Literal[3] | Literal[4]"
1223 reveal_type(b) # N: Revealed type is "Literal[1] | Literal[2] | Literal[3] | Literal[4]"
1224
1225 if a == a == 1:
1226 reveal_type(a) # N: Revealed type is "Literal[1]"
1227 elif a == a == 2:
1228 reveal_type(a) # N: Revealed type is "Literal[2]"
1229 elif a == a == 3:
1230 reveal_type(a) # N: Revealed type is "Literal[3]"
1231 elif a == a == 4:
1232 reveal_type(a) # N: Revealed type is "Literal[4]"
1233 else:
1234 # In contrast, this branch must be unreachable: we assume (maybe naively)
1235 # that 'a' won't be mutated in the middle of the expression.
1236 reveal_type(a) # E: Statement is unreachable
1237 reveal_type(b)
1238 [builtins fixtures/primitives.pyi]
1239
1240 [case testNarrowingLiteralTruthiness]
1241 # flags: --strict-equality --warn-unreachable
1242 from typing import Literal, Union
1243
1244 str_or_false: Union[Literal[False], str]
1245
1246 if str_or_false:
1247 reveal_type(str_or_false) # N: Revealed type is "builtins.str"
1248 else:
1249 reveal_type(str_or_false) # N: Revealed type is "Literal[False] | Literal['']"
1250
1251 true_or_false: Literal[True, False]
1252
1253 if true_or_false:
1254 reveal_type(true_or_false) # N: Revealed type is "Literal[True]"
1255 else:
1256 reveal_type(true_or_false) # N: Revealed type is "Literal[False]"
1257 [builtins fixtures/primitives.pyi]
1258
1259 [case testNarrowingFalseyToLiteral]
1260 # flags: --strict-equality --warn-unreachable
1261 from typing import Union
1262
1263 a: str
1264 b: bytes
1265 c: int
1266 d: Union[str, bytes, int]
1267
1268 if not a:
1269 reveal_type(a) # N: Revealed type is "Literal['']"
1270 if not b:
1271 reveal_type(b) # N: Revealed type is "Literal[b'']"
1272 if not c:
1273 reveal_type(c) # N: Revealed type is "Literal[0]"
1274 if not d:
1275 reveal_type(d) # N: Revealed type is "Literal[''] | Literal[b''] | Literal[0]"
1276
1277 [case testNarrowingIsInstanceFinalSubclass]
1278 # flags: --strict-equality --warn-unreachable
1279
1280 from typing import final
1281
1282 class N: ...
1283 @final
1284 class F1: ...
1285 @final
1286 class F2: ...
1287
1288 n: N
1289 f1: F1
1290
1291 if isinstance(f1, F1):
1292 reveal_type(f1) # N: Revealed type is "__main__.F1"
1293 else:
1294 reveal_type(f1) # E: Statement is unreachable
1295
1296 if isinstance(n, F1): # E: Subclass of "N" and "F1" cannot exist: "F1" is final
1297 reveal_type(n) # E: Statement is unreachable
1298 else:
1299 reveal_type(n) # N: Revealed type is "__main__.N"
1300
1301 if isinstance(f1, N): # E: Subclass of "F1" and "N" cannot exist: "F1" is final
1302 reveal_type(f1) # E: Statement is unreachable
1303 else:
1304 reveal_type(f1) # N: Revealed type is "__main__.F1"
1305
1306 if isinstance(f1, F2): # E: Subclass of "F1" and "F2" cannot exist: "F1" is final \
1307 # E: Subclass of "F1" and "F2" cannot exist: "F2" is final
1308 reveal_type(f1) # E: Statement is unreachable
1309 else:
1310 reveal_type(f1) # N: Revealed type is "__main__.F1"
1311 [builtins fixtures/isinstance.pyi]
1312
1313
1314 [case testNarrowingIsInstanceFinalSubclassWithUnions]
1315 # flags: --strict-equality --warn-unreachable
1316
1317 from typing import final, Union
1318
1319 class N: ...
1320 @final
1321 class F1: ...
1322 @final
1323 class F2: ...
1324
1325 n_f1: Union[N, F1]
1326 n_f2: Union[N, F2]
1327 f1_f2: Union[F1, F2]
1328
1329 if isinstance(n_f1, F1):
1330 reveal_type(n_f1) # N: Revealed type is "__main__.F1"
1331 else:
1332 reveal_type(n_f1) # N: Revealed type is "__main__.N"
1333
1334 if isinstance(n_f2, F1): # E: Subclass of "N" and "F1" cannot exist: "F1" is final \
1335 # E: Subclass of "F2" and "F1" cannot exist: "F2" is final \
1336 # E: Subclass of "F2" and "F1" cannot exist: "F1" is final
1337 reveal_type(n_f2) # E: Statement is unreachable
1338 else:
1339 reveal_type(n_f2) # N: Revealed type is "__main__.N | __main__.F2"
1340
1341 if isinstance(f1_f2, F1):
1342 reveal_type(f1_f2) # N: Revealed type is "__main__.F1"
1343 else:
1344 reveal_type(f1_f2) # N: Revealed type is "__main__.F2"
1345 [builtins fixtures/isinstance.pyi]
1346
1347
1348 [case testNarrowingIsSubclassFinalSubclassWithTypeVar]
1349 # flags: --strict-equality --warn-unreachable
1350
1351 from typing import final, Type, TypeVar
1352
1353 @final
1354 class A: ...
1355 @final
1356 class B: ...
1357
1358 T = TypeVar("T", A, B)
1359
1360 def f(cls: Type[T]) -> T:
1361 if issubclass(cls, A):
1362 reveal_type(cls) # N: Revealed type is "type[__main__.A]"
1363 x: bool
1364 if x:
1365 return A()
1366 else:
1367 return B() # E: Incompatible return value type (got "B", expected "A")
1368 assert False
1369
1370 reveal_type(f(A)) # N: Revealed type is "__main__.A"
1371 reveal_type(f(B)) # N: Revealed type is "__main__.B"
1372 [builtins fixtures/isinstance.pyi]
1373
1374
1375 [case testNarrowingLiteralIdentityCheck]
1376 # flags: --strict-equality --warn-unreachable
1377 from typing import Literal, Union
1378
1379 str_or_false: Union[Literal[False], str]
1380
1381 if str_or_false is not False:
1382 reveal_type(str_or_false) # N: Revealed type is "builtins.str"
1383 else:
1384 reveal_type(str_or_false) # N: Revealed type is "Literal[False]"
1385
1386 if str_or_false is False:
1387 reveal_type(str_or_false) # N: Revealed type is "Literal[False]"
1388 else:
1389 reveal_type(str_or_false) # N: Revealed type is "builtins.str"
1390
1391 str_or_true: Union[Literal[True], str]
1392
1393 if str_or_true is True:
1394 reveal_type(str_or_true) # N: Revealed type is "Literal[True]"
1395 else:
1396 reveal_type(str_or_true) # N: Revealed type is "builtins.str"
1397
1398 if str_or_true is not True:
1399 reveal_type(str_or_true) # N: Revealed type is "builtins.str"
1400 else:
1401 reveal_type(str_or_true) # N: Revealed type is "Literal[True]"
1402
1403 str_or_bool_literal: Union[Literal[False], Literal[True], str]
1404
1405 if str_or_bool_literal is not True:
1406 reveal_type(str_or_bool_literal) # N: Revealed type is "Literal[False] | builtins.str"
1407 else:
1408 reveal_type(str_or_bool_literal) # N: Revealed type is "Literal[True]"
1409
1410 if str_or_bool_literal is not True and str_or_bool_literal is not False:
1411 reveal_type(str_or_bool_literal) # N: Revealed type is "builtins.str"
1412 else:
1413 reveal_type(str_or_bool_literal) # N: Revealed type is "builtins.bool"
1414 [builtins fixtures/primitives.pyi]
1415
1416 [case testNarrowingBooleanIdentityCheck]
1417 # flags: --strict-equality --warn-unreachable
1418 from typing import Literal, Optional
1419
1420 bool_val: bool
1421
1422 if bool_val is not False:
1423 reveal_type(bool_val) # N: Revealed type is "Literal[True]"
1424 else:
1425 reveal_type(bool_val) # N: Revealed type is "Literal[False]"
1426
1427 opt_bool_val: Optional[bool]
1428
1429 if opt_bool_val is not None:
1430 reveal_type(opt_bool_val) # N: Revealed type is "builtins.bool"
1431
1432 if opt_bool_val is not False:
1433 reveal_type(opt_bool_val) # N: Revealed type is "Literal[True] | None"
1434 else:
1435 reveal_type(opt_bool_val) # N: Revealed type is "Literal[False]"
1436 [builtins fixtures/primitives.pyi]
1437
1438 [case testNarrowingBooleanTruthiness]
1439 # flags: --strict-equality --warn-unreachable
1440 from typing import Literal, Optional
1441
1442 bool_val: bool
1443
1444 if bool_val:
1445 reveal_type(bool_val) # N: Revealed type is "Literal[True]"
1446 else:
1447 reveal_type(bool_val) # N: Revealed type is "Literal[False]"
1448 reveal_type(bool_val) # N: Revealed type is "builtins.bool"
1449
1450 opt_bool_val: Optional[bool]
1451
1452 if opt_bool_val:
1453 reveal_type(opt_bool_val) # N: Revealed type is "Literal[True]"
1454 else:
1455 reveal_type(opt_bool_val) # N: Revealed type is "Literal[False] | None"
1456 reveal_type(opt_bool_val) # N: Revealed type is "builtins.bool | None"
1457 [builtins fixtures/primitives.pyi]
1458
1459 [case testNarrowingBooleanBoolOp]
1460 # flags: --strict-equality --warn-unreachable
1461 from typing import Literal, Optional
1462
1463 bool_a: bool
1464 bool_b: bool
1465
1466 if bool_a and bool_b:
1467 reveal_type(bool_a) # N: Revealed type is "Literal[True]"
1468 reveal_type(bool_b) # N: Revealed type is "Literal[True]"
1469 else:
1470 reveal_type(bool_a) # N: Revealed type is "builtins.bool"
1471 reveal_type(bool_b) # N: Revealed type is "builtins.bool"
1472
1473 if not bool_a or bool_b:
1474 reveal_type(bool_a) # N: Revealed type is "builtins.bool"
1475 reveal_type(bool_b) # N: Revealed type is "builtins.bool"
1476 else:
1477 reveal_type(bool_a) # N: Revealed type is "Literal[True]"
1478 reveal_type(bool_b) # N: Revealed type is "Literal[False]"
1479
1480 if True and bool_b:
1481 reveal_type(bool_b) # N: Revealed type is "Literal[True]"
1482
1483 x = True and bool_b
1484 reveal_type(x) # N: Revealed type is "builtins.bool"
1485 [builtins fixtures/primitives.pyi]
1486
1487 [case testNarrowingTypedDictUsingEnumLiteral]
1488 # flags: --strict-equality --warn-unreachable
1489 from typing import Literal, TypedDict, Union
1490 from enum import Enum
1491
1492 class E(Enum):
1493 FOO = "a"
1494 BAR = "b"
1495
1496 class Foo(TypedDict):
1497 tag: Literal[E.FOO]
1498 x: int
1499
1500 class Bar(TypedDict):
1501 tag: Literal[E.BAR]
1502 y: int
1503
1504 def f(d: Union[Foo, Bar]) -> None:
1505 assert d['tag'] == E.FOO
1506 d['x']
1507 reveal_type(d) # N: Revealed type is "TypedDict('__main__.Foo', {'tag': Literal[__main__.E.FOO], 'x': builtins.int})"
1508 [builtins fixtures/dict.pyi]
1509 [typing fixtures/typing-typeddict.pyi]
1510
1511 [case testNarrowingUsingMetaclass]
1512 # flags: --strict-equality --warn-unreachable
1513 from typing import Type
1514
1515 class M(type):
1516 pass
1517
1518 class C: pass
1519
1520 def f(t: Type[C]) -> None:
1521 if type(t) is M:
1522 reveal_type(t) # N: Revealed type is "type[__main__.C]"
1523 else:
1524 reveal_type(t) # N: Revealed type is "type[__main__.C]"
1525 if type(t) is not M:
1526 reveal_type(t) # N: Revealed type is "type[__main__.C]"
1527 else:
1528 reveal_type(t) # N: Revealed type is "type[__main__.C]"
1529 reveal_type(t) # N: Revealed type is "type[__main__.C]"
1530
1531 [case testNarrowingUsingTypeVar]
1532 # flags: --strict-equality --warn-unreachable
1533 from typing import Type, TypeVar
1534
1535 class A: pass
1536 class B(A): pass
1537
1538 T = TypeVar("T", bound=A)
1539
1540 def f(t: Type[T], a: A, b: B) -> None:
1541 if type(a) is t:
1542 reveal_type(a) # N: Revealed type is "T`-1"
1543 else:
1544 reveal_type(a) # N: Revealed type is "__main__.A"
1545
1546 if type(b) is t:
1547 reveal_type(b) # N: Revealed type is "T`-1"
1548 else:
1549 reveal_type(b) # N: Revealed type is "__main__.B"
1550
1551 [case testNarrowingNestedUnionOfTypedDicts]
1552 # flags: --strict-equality --warn-unreachable
1553 from typing import Literal, TypedDict, Union
1554
1555 class A(TypedDict):
1556 tag: Literal["A"]
1557 a: int
1558
1559 class B(TypedDict):
1560 tag: Literal["B"]
1561 b: int
1562
1563 class C(TypedDict):
1564 tag: Literal["C"]
1565 c: int
1566
1567 AB = Union[A, B]
1568 ABC = Union[AB, C]
1569 abc: ABC
1570
1571 if abc["tag"] == "A":
1572 reveal_type(abc) # N: Revealed type is "TypedDict('__main__.A', {'tag': Literal['A'], 'a': builtins.int})"
1573 elif abc["tag"] == "C":
1574 reveal_type(abc) # N: Revealed type is "TypedDict('__main__.C', {'tag': Literal['C'], 'c': builtins.int})"
1575 else:
1576 reveal_type(abc) # N: Revealed type is "TypedDict('__main__.B', {'tag': Literal['B'], 'b': builtins.int})"
1577 [builtins fixtures/primitives.pyi]
1578 [typing fixtures/typing-typeddict.pyi]
1579
1580 [case testNarrowingRuntimeCover]
1581 # flags: --strict-equality --warn-unreachable
1582 from typing import Dict, List, Union
1583
1584 def unreachable(x: Union[str, List[str]]) -> None:
1585 if isinstance(x, str):
1586 reveal_type(x) # N: Revealed type is "builtins.str"
1587 elif isinstance(x, list):
1588 reveal_type(x) # N: Revealed type is "builtins.list[builtins.str]"
1589 else:
1590 reveal_type(x) # No output: this branch is unreachable # E: Statement is unreachable
1591
1592 def all_parts_covered(x: Union[str, List[str], List[int], int]) -> None:
1593 if isinstance(x, str):
1594 reveal_type(x) # N: Revealed type is "builtins.str"
1595 elif isinstance(x, list):
1596 reveal_type(x) # N: Revealed type is "builtins.list[builtins.str] | builtins.list[builtins.int]"
1597 else:
1598 reveal_type(x) # N: Revealed type is "builtins.int"
1599
1600 def two_type_vars(x: Union[str, Dict[str, int], Dict[bool, object], int]) -> None:
1601 if isinstance(x, str):
1602 reveal_type(x) # N: Revealed type is "builtins.str"
1603 elif isinstance(x, dict):
1604 reveal_type(x) # N: Revealed type is "builtins.dict[builtins.str, builtins.int] | builtins.dict[builtins.bool, builtins.object]"
1605 else:
1606 reveal_type(x) # N: Revealed type is "builtins.int"
1607 [builtins fixtures/dict.pyi]
1608
1609
1610 [case testNarrowingWithDef]
1611 # flags: --strict-equality --warn-unreachable
1612 from typing import Callable, Optional
1613
1614 def g() -> None:
1615 foo: Optional[Callable[[], None]] = None
1616 if foo is None:
1617 def foo(): ...
1618 foo()
1619 [builtins fixtures/dict.pyi]
1620
1621
1622 [case testNarrowingOptionalEqualsNone]
1623 # flags: --strict-equality --warn-unreachable
1624 from typing import Optional
1625
1626 class A: ...
1627
1628 val: Optional[A]
1629
1630 if val == None:
1631 reveal_type(val) # N: Revealed type is "None"
1632 else:
1633 reveal_type(val) # N: Revealed type is "__main__.A"
1634 if val != None:
1635 reveal_type(val) # N: Revealed type is "__main__.A"
1636 else:
1637 reveal_type(val) # N: Revealed type is "None"
1638
1639 if val in (None,):
1640 reveal_type(val) # N: Revealed type is "None"
1641 else:
1642 reveal_type(val) # N: Revealed type is "__main__.A"
1643 if val not in (None,):
1644 reveal_type(val) # N: Revealed type is "__main__.A"
1645 else:
1646 reveal_type(val) # N: Revealed type is "None"
1647 [builtins fixtures/primitives.pyi]
1648
1649 [case testNarrowingCustomEqualityOptionalEqualsNone]
1650 # flags: --strict-equality --warn-unreachable
1651 from __future__ import annotations
1652 class Custom:
1653 def __eq__(self, other) -> bool: ...
1654
1655 def f(x: Custom | None):
1656 if x == None:
1657 reveal_type(x) # N: Revealed type is "__main__.Custom | None"
1658 else:
1659 reveal_type(x) # N: Revealed type is "__main__.Custom"
1660 if x != None:
1661 reveal_type(x) # N: Revealed type is "__main__.Custom"
1662 else:
1663 reveal_type(x) # N: Revealed type is "__main__.Custom | None"
1664 [builtins fixtures/primitives.pyi]
1665
1666 [case testNarrowingWithTupleOfTypes]
1667 # flags: --strict-equality --warn-unreachable
1668 from typing import Tuple, Type
1669
1670 class Base: ...
1671
1672 class Impl1(Base): ...
1673 class Impl2(Base): ...
1674
1675 impls: Tuple[Type[Base], ...] = (Impl1, Impl2)
1676 some: object
1677
1678 if isinstance(some, impls):
1679 reveal_type(some) # N: Revealed type is "__main__.Base"
1680 else:
1681 reveal_type(some) # N: Revealed type is "builtins.object"
1682
1683 raw: Tuple[type, ...]
1684 if isinstance(some, raw):
1685 reveal_type(some) # N: Revealed type is "builtins.object"
1686 else:
1687 reveal_type(some) # N: Revealed type is "builtins.object"
1688 [builtins fixtures/dict.pyi]
1689
1690
1691 [case testNarrowingWithTupleOfTypesPy310Plus]
1692 # flags: --strict-equality --warn-unreachable
1693 class Base: ...
1694
1695 class Impl1(Base): ...
1696 class Impl2(Base): ...
1697
1698 some: int | Base
1699
1700 impls: tuple[type[Base], ...] = (Impl1, Impl2)
1701 if isinstance(some, impls):
1702 reveal_type(some) # N: Revealed type is "__main__.Base"
1703 else:
1704 reveal_type(some) # N: Revealed type is "builtins.int | __main__.Base"
1705
1706 raw: tuple[type, ...]
1707 if isinstance(some, raw):
1708 reveal_type(some) # N: Revealed type is "builtins.int | __main__.Base"
1709 else:
1710 reveal_type(some) # N: Revealed type is "builtins.int | __main__.Base"
1711 [builtins fixtures/dict.pyi]
1712
1713 [case testNarrowingWithAnyOps]
1714 # flags: --strict-equality --warn-unreachable
1715 from typing import Any
1716
1717 class C: ...
1718 class D(C): ...
1719 tp: Any
1720
1721 c: C
1722 if isinstance(c, tp) or isinstance(c, D):
1723 reveal_type(c) # N: Revealed type is "Any | __main__.D"
1724 else:
1725 reveal_type(c) # N: Revealed type is "__main__.C"
1726 reveal_type(c) # N: Revealed type is "__main__.C"
1727
1728 c1: C
1729 if isinstance(c1, tp) and isinstance(c1, D):
1730 reveal_type(c1) # N: Revealed type is "__main__.D"
1731 else:
1732 reveal_type(c1) # N: Revealed type is "__main__.C"
1733 reveal_type(c1) # N: Revealed type is "__main__.C"
1734
1735 c2: C
1736 if isinstance(c2, D) or isinstance(c2, tp):
1737 reveal_type(c2) # N: Revealed type is "__main__.D | Any"
1738 else:
1739 reveal_type(c2) # N: Revealed type is "__main__.C"
1740 reveal_type(c2) # N: Revealed type is "__main__.C"
1741
1742 c3: C
1743 if isinstance(c3, D) and isinstance(c3, tp):
1744 reveal_type(c3) # N: Revealed type is "__main__.D"
1745 else:
1746 reveal_type(c3) # N: Revealed type is "__main__.C"
1747 reveal_type(c3) # N: Revealed type is "__main__.C"
1748
1749 t: Any
1750 if isinstance(t, (list, tuple)) and isinstance(t, tuple):
1751 reveal_type(t) # N: Revealed type is "builtins.tuple[Any, ...]"
1752 else:
1753 reveal_type(t) # N: Revealed type is "Any"
1754 reveal_type(t) # N: Revealed type is "Any"
1755 [builtins fixtures/isinstancelist.pyi]
1756
1757 [case testNarrowingAnyUnion]
1758 # flags: --strict-equality --warn-unreachable
1759 from __future__ import annotations
1760 from unknown import A, AA # E: Cannot find implementation or library stub for module named "unknown" \
1761 # N: See https://mypy.readthedocs.io/en/stable/running_mypy.html#missing-imports
1762
1763 class B: ...
1764
1765 def f(x: A | B) -> None:
1766 if isinstance(x, (AA, B)):
1767 reveal_type(x) # N: Revealed type is "Any | __main__.B"
1768 else:
1769 reveal_type(x) # N: Revealed type is "Any"
1770 [builtins fixtures/isinstancelist.pyi]
1771
1772 [case testNarrowingLenItemAndLenCompare]
1773 # flags: --strict-equality --warn-unreachable
1774 from typing import Any
1775
1776 x: Any
1777 if len(x) == x:
1778 reveal_type(x) # N: Revealed type is "Any"
1779 [builtins fixtures/len.pyi]
1780
1781 [case testNarrowingLenTuple]
1782 # flags: --strict-equality --warn-unreachable
1783 from typing import Tuple, Union
1784
1785 VarTuple = Union[Tuple[int, int], Tuple[int, int, int]]
1786
1787 x: VarTuple
1788 a = b = c = 0
1789 if len(x) == 3:
1790 a, b, c = x
1791 else:
1792 a, b = x
1793
1794 if len(x) != 3:
1795 a, b = x
1796 else:
1797 a, b, c = x
1798 [builtins fixtures/len.pyi]
1799
1800 [case testNarrowingLenHomogeneousTuple]
1801 # flags: --strict-equality --warn-unreachable
1802 from typing import Tuple
1803
1804 x: Tuple[int, ...]
1805 if len(x) == 3:
1806 reveal_type(x) # N: Revealed type is "tuple[builtins.int, builtins.int, builtins.int]"
1807 else:
1808 reveal_type(x) # N: Revealed type is "builtins.tuple[builtins.int, ...]"
1809
1810 if len(x) != 3:
1811 reveal_type(x) # N: Revealed type is "builtins.tuple[builtins.int, ...]"
1812 else:
1813 reveal_type(x) # N: Revealed type is "tuple[builtins.int, builtins.int, builtins.int]"
1814 [builtins fixtures/len.pyi]
1815
1816 [case testNarrowingLenTypeUnaffected]
1817 # flags: --strict-equality --warn-unreachable
1818 from typing import Union, List
1819
1820 x: Union[str, List[int]]
1821 if len(x) == 3:
1822 reveal_type(x) # N: Revealed type is "builtins.str | builtins.list[builtins.int]"
1823 else:
1824 reveal_type(x) # N: Revealed type is "builtins.str | builtins.list[builtins.int]"
1825 [builtins fixtures/len.pyi]
1826
1827 [case testNarrowingLenAnyListElseNotAffected]
1828 # flags: --strict-equality --warn-unreachable
1829 from typing import Any
1830
1831 def f(self, value: Any) -> Any:
1832 if isinstance(value, list) and len(value) == 0:
1833 reveal_type(value) # N: Revealed type is "builtins.list[Any]"
1834 return value
1835 reveal_type(value) # N: Revealed type is "Any"
1836 return None
1837 [builtins fixtures/len.pyi]
1838
1839 [case testNarrowingLenMultiple]
1840 # flags: --strict-equality --warn-unreachable
1841 from typing import Tuple, Union
1842
1843 VarTuple = Union[Tuple[int, int], Tuple[int, int, int]]
1844
1845 x: VarTuple
1846 y: VarTuple
1847 if len(x) == len(y) == 3:
1848 reveal_type(x) # N: Revealed type is "tuple[builtins.int, builtins.int, builtins.int]"
1849 reveal_type(y) # N: Revealed type is "tuple[builtins.int, builtins.int, builtins.int]"
1850 [builtins fixtures/len.pyi]
1851
1852 [case testNarrowingLenFinal]
1853 # flags: --strict-equality --warn-unreachable
1854 from typing import Final, Tuple, Union
1855
1856 VarTuple = Union[Tuple[int, int], Tuple[int, int, int]]
1857
1858 x: VarTuple
1859 fin: Final = 3
1860 if len(x) == fin:
1861 reveal_type(x) # N: Revealed type is "tuple[builtins.int, builtins.int, builtins.int]"
1862 [builtins fixtures/len.pyi]
1863
1864 [case testNarrowingLenGreaterThan]
1865 # flags: --strict-equality --warn-unreachable
1866 from typing import Tuple, Union
1867
1868 VarTuple = Union[Tuple[int], Tuple[int, int], Tuple[int, int, int]]
1869
1870 x: VarTuple
1871 if len(x) > 1:
1872 reveal_type(x) # N: Revealed type is "tuple[builtins.int, builtins.int] | tuple[builtins.int, builtins.int, builtins.int]"
1873 else:
1874 reveal_type(x) # N: Revealed type is "tuple[builtins.int]"
1875
1876 if len(x) < 2:
1877 reveal_type(x) # N: Revealed type is "tuple[builtins.int]"
1878 else:
1879 reveal_type(x) # N: Revealed type is "tuple[builtins.int, builtins.int] | tuple[builtins.int, builtins.int, builtins.int]"
1880
1881 if len(x) >= 2:
1882 reveal_type(x) # N: Revealed type is "tuple[builtins.int, builtins.int] | tuple[builtins.int, builtins.int, builtins.int]"
1883 else:
1884 reveal_type(x) # N: Revealed type is "tuple[builtins.int]"
1885
1886 if len(x) <= 2:
1887 reveal_type(x) # N: Revealed type is "tuple[builtins.int] | tuple[builtins.int, builtins.int]"
1888 else:
1889 reveal_type(x) # N: Revealed type is "tuple[builtins.int, builtins.int, builtins.int]"
1890 [builtins fixtures/len.pyi]
1891
1892 [case testNarrowingLenBothSidesUnionTuples]
1893 # flags: --strict-equality --warn-unreachable
1894 from typing import Tuple, Union
1895
1896 VarTuple = Union[
1897 Tuple[int],
1898 Tuple[int, int],
1899 Tuple[int, int, int],
1900 Tuple[int, int, int, int],
1901 ]
1902
1903 x: VarTuple
1904 if 2 <= len(x) <= 3:
1905 reveal_type(x) # N: Revealed type is "tuple[builtins.int, builtins.int] | tuple[builtins.int, builtins.int, builtins.int]"
1906 else:
1907 reveal_type(x) # N: Revealed type is "tuple[builtins.int] | tuple[builtins.int, builtins.int, builtins.int, builtins.int]"
1908 [builtins fixtures/len.pyi]
1909
1910 [case testNarrowingLenGreaterThanHomogeneousTupleShort]
1911 # flags: --enable-incomplete-feature=PreciseTupleTypes --strict-equality --warn-unreachable
1912 from typing import Tuple
1913
1914 VarTuple = Tuple[int, ...]
1915
1916 x: VarTuple
1917 if len(x) < 3:
1918 reveal_type(x) # N: Revealed type is "tuple[()] | tuple[builtins.int] | tuple[builtins.int, builtins.int]"
1919 else:
1920 reveal_type(x) # N: Revealed type is "tuple[builtins.int, builtins.int, builtins.int, Unpack[builtins.tuple[builtins.int, ...]]]"
1921 reveal_type(x) # N: Revealed type is "builtins.tuple[builtins.int, ...]"
1922 [builtins fixtures/len.pyi]
1923
1924 [case testNarrowingLenBiggerThanHomogeneousTupleLong]
1925 # flags: --enable-incomplete-feature=PreciseTupleTypes --strict-equality --warn-unreachable
1926 from typing import Tuple
1927
1928 VarTuple = Tuple[int, ...]
1929
1930 x: VarTuple
1931 if len(x) < 30:
1932 reveal_type(x) # N: Revealed type is "builtins.tuple[builtins.int, ...]"
1933 else:
1934 reveal_type(x) # N: Revealed type is "builtins.tuple[builtins.int, ...]"
1935 [builtins fixtures/len.pyi]
1936
1937 [case testNarrowingLenBothSidesHomogeneousTuple]
1938 # flags: --enable-incomplete-feature=PreciseTupleTypes --strict-equality --warn-unreachable
1939 from typing import Tuple
1940
1941 x: Tuple[int, ...]
1942 if 1 < len(x) < 4:
1943 reveal_type(x) # N: Revealed type is "tuple[builtins.int, builtins.int] | tuple[builtins.int, builtins.int, builtins.int]"
1944 else:
1945 reveal_type(x) # N: Revealed type is "tuple[()] | tuple[builtins.int] | tuple[builtins.int, builtins.int, builtins.int, builtins.int, Unpack[builtins.tuple[builtins.int, ...]]]"
1946 reveal_type(x) # N: Revealed type is "builtins.tuple[builtins.int, ...]"
1947 [builtins fixtures/len.pyi]
1948
1949 [case testNarrowingLenUnionTupleUnreachable]
1950 # flags: --strict-equality --warn-unreachable
1951 from typing import Tuple, Union
1952
1953 x: Union[Tuple[int, int], Tuple[int, int, int]]
1954 if len(x) >= 4:
1955 reveal_type(x) # E: Statement is unreachable
1956 else:
1957 reveal_type(x) # N: Revealed type is "tuple[builtins.int, builtins.int] | tuple[builtins.int, builtins.int, builtins.int]"
1958
1959 if len(x) < 2:
1960 reveal_type(x) # E: Statement is unreachable
1961 else:
1962 reveal_type(x) # N: Revealed type is "tuple[builtins.int, builtins.int] | tuple[builtins.int, builtins.int, builtins.int]"
1963 [builtins fixtures/len.pyi]
1964
1965 [case testNarrowingLenMixedTypes]
1966 # flags: --strict-equality --warn-unreachable
1967 from typing import Tuple, List, Union
1968
1969 x: Union[Tuple[int, int], Tuple[int, int, int], List[int]]
1970 a = b = c = 0
1971 if len(x) == 3:
1972 reveal_type(x) # N: Revealed type is "tuple[builtins.int, builtins.int, builtins.int] | builtins.list[builtins.int]"
1973 a, b, c = x
1974 else:
1975 reveal_type(x) # N: Revealed type is "tuple[builtins.int, builtins.int] | builtins.list[builtins.int]"
1976 a, b = x
1977
1978 if len(x) != 3:
1979 reveal_type(x) # N: Revealed type is "tuple[builtins.int, builtins.int] | builtins.list[builtins.int]"
1980 a, b = x
1981 else:
1982 reveal_type(x) # N: Revealed type is "tuple[builtins.int, builtins.int, builtins.int] | builtins.list[builtins.int]"
1983 a, b, c = x
1984 [builtins fixtures/len.pyi]
1985
1986 [case testNarrowingLenTypeVarTupleEquals]
1987 # flags: --strict-equality --warn-unreachable
1988 from typing import Tuple
1989 from typing_extensions import TypeVarTuple, Unpack
1990
1991 Ts = TypeVarTuple("Ts")
1992 def foo(x: Tuple[int, Unpack[Ts], str]) -> None:
1993 if len(x) == 5:
1994 reveal_type(x) # N: Revealed type is "tuple[builtins.int, Unpack[Ts`-1], builtins.str]"
1995 else:
1996 reveal_type(x) # N: Revealed type is "tuple[builtins.int, Unpack[Ts`-1], builtins.str]"
1997
1998 if len(x) != 5:
1999 reveal_type(x) # N: Revealed type is "tuple[builtins.int, Unpack[Ts`-1], builtins.str]"
2000 else:
2001 reveal_type(x) # N: Revealed type is "tuple[builtins.int, Unpack[Ts`-1], builtins.str]"
2002 [builtins fixtures/len.pyi]
2003
2004 [case testNarrowingLenTypeVarTupleGreaterThan]
2005 # flags: --strict-equality --warn-unreachable
2006 from typing import Tuple
2007 from typing_extensions import TypeVarTuple, Unpack
2008
2009 Ts = TypeVarTuple("Ts")
2010 def foo(x: Tuple[int, Unpack[Ts], str]) -> None:
2011 if len(x) > 5:
2012 reveal_type(x) # N: Revealed type is "tuple[builtins.int, Unpack[Ts`-1], builtins.str]"
2013 reveal_type(x[5]) # N: Revealed type is "builtins.object"
2014 reveal_type(x[-6]) # N: Revealed type is "builtins.object"
2015 reveal_type(x[-1]) # N: Revealed type is "builtins.str"
2016 else:
2017 reveal_type(x) # N: Revealed type is "tuple[builtins.int, Unpack[Ts`-1], builtins.str]"
2018
2019 if len(x) < 5:
2020 reveal_type(x) # N: Revealed type is "tuple[builtins.int, Unpack[Ts`-1], builtins.str]"
2021 else:
2022 reveal_type(x) # N: Revealed type is "tuple[builtins.int, Unpack[Ts`-1], builtins.str]"
2023 x[5] # E: Tuple index out of range \
2024 # N: Variadic tuple can have length 5
2025 x[-6] # E: Tuple index out of range \
2026 # N: Variadic tuple can have length 5
2027 x[2] # E: Tuple index out of range \
2028 # N: Variadic tuple can have length 2
2029 x[-3] # E: Tuple index out of range \
2030 # N: Variadic tuple can have length 2
2031 [builtins fixtures/len.pyi]
2032
2033 [case testNarrowingLenTypeVarTupleUnreachable]
2034 # flags: --strict-equality --warn-unreachable
2035 from typing import Tuple
2036 from typing_extensions import TypeVarTuple, Unpack
2037
2038 Ts = TypeVarTuple("Ts")
2039 def foo(x: Tuple[int, Unpack[Ts], str]) -> None:
2040 if len(x) == 1:
2041 reveal_type(x) # E: Statement is unreachable
2042 else:
2043 reveal_type(x) # N: Revealed type is "tuple[builtins.int, Unpack[Ts`-1], builtins.str]"
2044
2045 if len(x) != 1:
2046 reveal_type(x) # N: Revealed type is "tuple[builtins.int, Unpack[Ts`-1], builtins.str]"
2047 else:
2048 reveal_type(x) # E: Statement is unreachable
2049
2050 def bar(x: Tuple[int, Unpack[Ts], str]) -> None:
2051 if len(x) >= 2:
2052 reveal_type(x) # N: Revealed type is "tuple[builtins.int, Unpack[Ts`-1], builtins.str]"
2053 else:
2054 reveal_type(x) # E: Statement is unreachable
2055
2056 if len(x) < 2:
2057 reveal_type(x) # E: Statement is unreachable
2058 else:
2059 reveal_type(x) # N: Revealed type is "tuple[builtins.int, Unpack[Ts`-1], builtins.str]"
2060 [builtins fixtures/len.pyi]
2061
2062 [case testNarrowingLenVariadicTupleEquals]
2063 # flags: --strict-equality --warn-unreachable
2064 from typing import Tuple
2065 from typing_extensions import Unpack
2066
2067 def foo(x: Tuple[int, Unpack[Tuple[float, ...]], str]) -> None:
2068 if len(x) == 4:
2069 reveal_type(x) # N: Revealed type is "tuple[builtins.int, builtins.float, builtins.float, builtins.str]"
2070 else:
2071 reveal_type(x) # N: Revealed type is "tuple[builtins.int, Unpack[builtins.tuple[builtins.float, ...]], builtins.str]"
2072
2073 if len(x) != 4:
2074 reveal_type(x) # N: Revealed type is "tuple[builtins.int, Unpack[builtins.tuple[builtins.float, ...]], builtins.str]"
2075 else:
2076 reveal_type(x) # N: Revealed type is "tuple[builtins.int, builtins.float, builtins.float, builtins.str]"
2077 [builtins fixtures/len.pyi]
2078
2079 [case testNarrowingLenVariadicTupleGreaterThan]
2080 # flags: --strict-equality --warn-unreachable
2081 from typing import Tuple
2082 from typing_extensions import Unpack
2083
2084 def foo(x: Tuple[int, Unpack[Tuple[float, ...]], str]) -> None:
2085 if len(x) > 3:
2086 reveal_type(x) # N: Revealed type is "tuple[builtins.int, builtins.float, builtins.float, Unpack[builtins.tuple[builtins.float, ...]], builtins.str]"
2087 else:
2088 reveal_type(x) # N: Revealed type is "tuple[builtins.int, builtins.str] | tuple[builtins.int, builtins.float, builtins.str]"
2089 reveal_type(x) # N: Revealed type is "tuple[builtins.int, Unpack[builtins.tuple[builtins.float, ...]], builtins.str]"
2090
2091 if len(x) < 3:
2092 reveal_type(x) # N: Revealed type is "tuple[builtins.int, builtins.str]"
2093 else:
2094 reveal_type(x) # N: Revealed type is "tuple[builtins.int, builtins.float, Unpack[builtins.tuple[builtins.float, ...]], builtins.str]"
2095 reveal_type(x) # N: Revealed type is "tuple[builtins.int, Unpack[builtins.tuple[builtins.float, ...]], builtins.str]"
2096 [builtins fixtures/len.pyi]
2097
2098 [case testNarrowingLenVariadicTupleUnreachable]
2099 # flags: --strict-equality --warn-unreachable
2100 from typing import Tuple
2101 from typing_extensions import Unpack
2102
2103 def foo(x: Tuple[int, Unpack[Tuple[float, ...]], str]) -> None:
2104 if len(x) == 1:
2105 reveal_type(x) # E: Statement is unreachable
2106 else:
2107 reveal_type(x) # N: Revealed type is "tuple[builtins.int, Unpack[builtins.tuple[builtins.float, ...]], builtins.str]"
2108
2109 if len(x) != 1:
2110 reveal_type(x) # N: Revealed type is "tuple[builtins.int, Unpack[builtins.tuple[builtins.float, ...]], builtins.str]"
2111 else:
2112 reveal_type(x) # E: Statement is unreachable
2113
2114 def bar(x: Tuple[int, Unpack[Tuple[float, ...]], str]) -> None:
2115 if len(x) >= 2:
2116 reveal_type(x) # N: Revealed type is "tuple[builtins.int, Unpack[builtins.tuple[builtins.float, ...]], builtins.str]"
2117 else:
2118 reveal_type(x) # E: Statement is unreachable
2119
2120 if len(x) < 2:
2121 reveal_type(x) # E: Statement is unreachable
2122 else:
2123 reveal_type(x) # N: Revealed type is "tuple[builtins.int, Unpack[builtins.tuple[builtins.float, ...]], builtins.str]"
2124 [builtins fixtures/len.pyi]
2125
2126 [case testNarrowingLenBareExpressionPrecise]
2127 # flags: --enable-incomplete-feature=PreciseTupleTypes --strict-equality --warn-unreachable
2128 from typing import Tuple
2129
2130 x: Tuple[int, ...]
2131 assert x
2132 reveal_type(x) # N: Revealed type is "tuple[builtins.int, Unpack[builtins.tuple[builtins.int, ...]]]"
2133 [builtins fixtures/len.pyi]
2134
2135 [case testNarrowingLenBareExpressionTypeVarTuple]
2136 # flags: --strict-equality --warn-unreachable
2137 from typing import Tuple
2138 from typing_extensions import TypeVarTuple, Unpack
2139
2140 Ts = TypeVarTuple("Ts")
2141 def test(*xs: Unpack[Ts]) -> None:
2142 assert xs
2143 xs[0] # OK
2144 [builtins fixtures/len.pyi]
2145
2146 [case testNarrowingLenBareExpressionWithNonePrecise]
2147 # flags: --enable-incomplete-feature=PreciseTupleTypes --strict-equality --warn-unreachable
2148 from typing import Tuple, Optional
2149
2150 x: Optional[Tuple[int, ...]]
2151 if x:
2152 reveal_type(x) # N: Revealed type is "tuple[builtins.int, Unpack[builtins.tuple[builtins.int, ...]]]"
2153 else:
2154 reveal_type(x) # N: Revealed type is "tuple[()] | None"
2155 [builtins fixtures/len.pyi]
2156
2157 [case testNarrowingLenBareExpressionWithNoneImprecise]
2158 # flags: --strict-equality --warn-unreachable
2159 from typing import Tuple, Optional
2160
2161 x: Optional[Tuple[int, ...]]
2162 if x:
2163 reveal_type(x) # N: Revealed type is "builtins.tuple[builtins.int, ...]"
2164 else:
2165 reveal_type(x) # N: Revealed type is "builtins.tuple[builtins.int, ...] | None"
2166 [builtins fixtures/len.pyi]
2167
2168 [case testNarrowingLenMixWithAnyPrecise]
2169 # flags: --enable-incomplete-feature=PreciseTupleTypes --strict-equality --warn-unreachable
2170 from typing import Any
2171
2172 x: Any
2173 if isinstance(x, (list, tuple)) and len(x) == 0:
2174 reveal_type(x) # N: Revealed type is "tuple[()] | builtins.list[Any]"
2175 else:
2176 reveal_type(x) # N: Revealed type is "Any"
2177 reveal_type(x) # N: Revealed type is "Any"
2178
2179 x1: Any
2180 if isinstance(x1, (list, tuple)) and len(x1) > 1:
2181 reveal_type(x1) # N: Revealed type is "tuple[Any, Any, Unpack[builtins.tuple[Any, ...]]] | builtins.list[Any]"
2182 else:
2183 reveal_type(x1) # N: Revealed type is "Any"
2184 reveal_type(x1) # N: Revealed type is "Any"
2185 [builtins fixtures/len.pyi]
2186
2187 [case testNarrowingLenMixWithAnyImprecise]
2188 # flags: --strict-equality --warn-unreachable
2189 from typing import Any
2190
2191 x: Any
2192 if isinstance(x, (list, tuple)) and len(x) == 0:
2193 reveal_type(x) # N: Revealed type is "tuple[()] | builtins.list[Any]"
2194 else:
2195 reveal_type(x) # N: Revealed type is "Any"
2196 reveal_type(x) # N: Revealed type is "Any"
2197
2198 x1: Any
2199 if isinstance(x1, (list, tuple)) and len(x1) > 1:
2200 reveal_type(x1) # N: Revealed type is "builtins.tuple[Any, ...] | builtins.list[Any]"
2201 else:
2202 reveal_type(x1) # N: Revealed type is "Any"
2203 reveal_type(x1) # N: Revealed type is "Any"
2204 [builtins fixtures/len.pyi]
2205
2206 [case testNarrowingLenExplicitLiteralTypes]
2207 # flags: --strict-equality --warn-unreachable
2208 from typing import Literal, Tuple, Union
2209
2210 VarTuple = Union[
2211 Tuple[int],
2212 Tuple[int, int],
2213 Tuple[int, int, int],
2214 ]
2215 x: VarTuple
2216
2217 supported: Literal[2]
2218 if len(x) == supported:
2219 reveal_type(x) # N: Revealed type is "tuple[builtins.int, builtins.int]"
2220 else:
2221 reveal_type(x) # N: Revealed type is "tuple[builtins.int] | tuple[builtins.int, builtins.int, builtins.int]"
2222
2223 not_supported_yet: Literal[2, 3]
2224 if len(x) == not_supported_yet:
2225 reveal_type(x) # N: Revealed type is "tuple[builtins.int] | tuple[builtins.int, builtins.int] | tuple[builtins.int, builtins.int, builtins.int]"
2226 else:
2227 reveal_type(x) # N: Revealed type is "tuple[builtins.int] | tuple[builtins.int, builtins.int] | tuple[builtins.int, builtins.int, builtins.int]"
2228 [builtins fixtures/len.pyi]
2229
2230 [case testNarrowingLenUnionOfVariadicTuples]
2231 # flags: --strict-equality --warn-unreachable
2232 from typing import Tuple, Union
2233
2234 x: Union[Tuple[int, ...], Tuple[str, ...]]
2235 if len(x) == 2:
2236 reveal_type(x) # N: Revealed type is "tuple[builtins.int, builtins.int] | tuple[builtins.str, builtins.str]"
2237 else:
2238 reveal_type(x) # N: Revealed type is "builtins.tuple[builtins.int, ...] | builtins.tuple[builtins.str, ...]"
2239 [builtins fixtures/len.pyi]
2240
2241 [case testNarrowingLenUnionOfNamedTuples]
2242 # flags: --strict-equality --warn-unreachable
2243 from typing import NamedTuple, Union
2244
2245 class Point2D(NamedTuple):
2246 x: int
2247 y: int
2248 class Point3D(NamedTuple):
2249 x: int
2250 y: int
2251 z: int
2252
2253 x: Union[Point2D, Point3D]
2254 if len(x) == 2:
2255 reveal_type(x) # N: Revealed type is "tuple[builtins.int, builtins.int, fallback=__main__.Point2D]"
2256 else:
2257 reveal_type(x) # N: Revealed type is "tuple[builtins.int, builtins.int, builtins.int, fallback=__main__.Point3D]"
2258 [builtins fixtures/len.pyi]
2259
2260 [case testNarrowingLenTupleSubclass]
2261 # flags: --strict-equality --warn-unreachable
2262 from typing import Tuple
2263
2264 class Ints(Tuple[int, ...]):
2265 size: int
2266
2267 x: Ints
2268 if len(x) == 2:
2269 reveal_type(x) # N: Revealed type is "tuple[builtins.int, builtins.int, fallback=__main__.Ints]"
2270 reveal_type(x.size) # N: Revealed type is "builtins.int"
2271 else:
2272 reveal_type(x) # N: Revealed type is "__main__.Ints"
2273 reveal_type(x.size) # N: Revealed type is "builtins.int"
2274
2275 reveal_type(x) # N: Revealed type is "__main__.Ints"
2276 [builtins fixtures/len.pyi]
2277
2278 [case testNarrowingLenTupleSubclassCustomNotAllowed]
2279 # flags: --strict-equality --warn-unreachable
2280 from typing import Tuple
2281
2282 class Ints(Tuple[int, ...]):
2283 def __len__(self) -> int:
2284 return 0
2285
2286 x: Ints
2287 if len(x) > 2:
2288 reveal_type(x) # N: Revealed type is "__main__.Ints"
2289 else:
2290 reveal_type(x) # N: Revealed type is "__main__.Ints"
2291 [builtins fixtures/len.pyi]
2292
2293 [case testNarrowingLenTupleSubclassPreciseNotAllowed]
2294 # flags: --enable-incomplete-feature=PreciseTupleTypes --strict-equality --warn-unreachable
2295 from typing import Tuple
2296
2297 class Ints(Tuple[int, ...]):
2298 size: int
2299
2300 x: Ints
2301 if len(x) > 2:
2302 reveal_type(x) # N: Revealed type is "__main__.Ints"
2303 else:
2304 reveal_type(x) # N: Revealed type is "__main__.Ints"
2305 [builtins fixtures/len.pyi]
2306
2307 [case testNarrowingLenUnknownLen]
2308 # flags: --strict-equality --warn-unreachable
2309 from typing import Any, Tuple, Union
2310
2311 x: Union[Tuple[int, int], Tuple[int, int, int]]
2312
2313 n: int
2314 if len(x) == n:
2315 reveal_type(x) # N: Revealed type is "tuple[builtins.int, builtins.int] | tuple[builtins.int, builtins.int, builtins.int]"
2316 else:
2317 reveal_type(x) # N: Revealed type is "tuple[builtins.int, builtins.int] | tuple[builtins.int, builtins.int, builtins.int]"
2318
2319 a: Any
2320 if len(x) == a:
2321 reveal_type(x) # N: Revealed type is "tuple[builtins.int, builtins.int] | tuple[builtins.int, builtins.int, builtins.int]"
2322 else:
2323 reveal_type(x) # N: Revealed type is "tuple[builtins.int, builtins.int] | tuple[builtins.int, builtins.int, builtins.int]"
2324 [builtins fixtures/len.pyi]
2325
2326 [case testNarrowingLenUnionWithUnreachable]
2327 # flags: --strict-equality --warn-unreachable
2328 from typing import Union, Sequence
2329
2330 def f(x: Union[int, Sequence[int]]) -> None:
2331 if (
2332 isinstance(x, tuple)
2333 and len(x) == 2
2334 and isinstance(x[0], int)
2335 and isinstance(x[1], int)
2336 ):
2337 reveal_type(x) # N: Revealed type is "tuple[builtins.int, builtins.int]"
2338 [builtins fixtures/len.pyi]
2339
2340 [case testNarrowingIsSubclassNoneType1]
2341 # flags: --strict-equality --warn-unreachable
2342 from typing import Type, Union
2343
2344 def f(cls: Type[Union[None, int]]) -> None:
2345 if issubclass(cls, int):
2346 reveal_type(cls) # N: Revealed type is "type[builtins.int]"
2347 else:
2348 reveal_type(cls) # N: Revealed type is "type[None]"
2349 [builtins fixtures/isinstance.pyi]
2350
2351 [case testNarrowingIsSubclassNoneType2]
2352 # flags: --strict-equality --warn-unreachable
2353 from typing import Type, Union
2354
2355 def f(cls: Type[Union[None, int]]) -> None:
2356 if issubclass(cls, type(None)):
2357 reveal_type(cls) # N: Revealed type is "type[None]"
2358 else:
2359 reveal_type(cls) # N: Revealed type is "type[builtins.int]"
2360 [builtins fixtures/isinstance.pyi]
2361
2362 [case testNarrowingIsSubclassNoneType3]
2363 # flags: --strict-equality --warn-unreachable
2364 from typing import Type, Union
2365
2366 NoneType_ = type(None)
2367
2368 def f(cls: Type[Union[None, int]]) -> None:
2369 if issubclass(cls, NoneType_):
2370 reveal_type(cls) # N: Revealed type is "type[None]"
2371 else:
2372 reveal_type(cls) # N: Revealed type is "type[builtins.int]"
2373 [builtins fixtures/isinstance.pyi]
2374
2375 [case testNarrowingIsSubclassNoneType4]
2376 # flags: --strict-equality --warn-unreachable
2377
2378 from types import NoneType
2379 from typing import Type, Union
2380
2381 def f(cls: Type[Union[None, int]]) -> None:
2382 if issubclass(cls, NoneType):
2383 reveal_type(cls) # N: Revealed type is "type[None]"
2384 else:
2385 reveal_type(cls) # N: Revealed type is "type[builtins.int]"
2386 [builtins fixtures/isinstance.pyi]
2387
2388 [case testNarrowingIsInstanceNoIntersectionWithFinalTypeAndNoneType]
2389 # flags: --warn-unreachable --strict-equality
2390
2391 from types import NoneType
2392 from typing import final
2393
2394 class X: ...
2395 class Y: ...
2396 @final
2397 class Z: ...
2398
2399 x: X
2400
2401 if isinstance(x, (Y, Z)):
2402 reveal_type(x) # N: Revealed type is "__main__.<subclass of "__main__.X" and "__main__.Y">"
2403 if isinstance(x, (Y, NoneType)):
2404 reveal_type(x) # N: Revealed type is "__main__.<subclass of "__main__.X" and "__main__.Y">"
2405 if isinstance(x, (Y, Z, NoneType)):
2406 reveal_type(x) # N: Revealed type is "__main__.<subclass of "__main__.X" and "__main__.Y">"
2407 if isinstance(x, (Z, NoneType)): # E: Subclass of "X" and "Z" cannot exist: "Z" is final \
2408 # E: Subclass of "X" and "NoneType" cannot exist: "NoneType" is final
2409 reveal_type(x) # E: Statement is unreachable
2410
2411 [builtins fixtures/isinstance.pyi]
2412
2413 [case testTypeNarrowingReachableNegative]
2414 # flags: --strict-equality --warn-unreachable
2415 from typing import Literal
2416
2417 x: Literal[-1]
2418
2419 if x == -1:
2420 assert True
2421
2422 [typing fixtures/typing-medium.pyi]
2423 [builtins fixtures/ops.pyi]
2424
2425 [case testTypeNarrowingReachableNegativeUnion]
2426 # flags: --strict-equality --warn-unreachable
2427 from typing import Literal
2428
2429 x: Literal[-1, 1]
2430
2431 if x == -1:
2432 reveal_type(x) # N: Revealed type is "Literal[-1]"
2433 else:
2434 reveal_type(x) # N: Revealed type is "Literal[1]"
2435
2436 [typing fixtures/typing-medium.pyi]
2437 [builtins fixtures/ops.pyi]
2438
2439 [case testNarrowingWithIntEnum]
2440 # flags: --strict-equality --warn-unreachable
2441 from __future__ import annotations
2442 from typing import Any
2443 from enum import IntEnum
2444
2445 class IE(IntEnum):
2446 X = 1
2447 Y = 2
2448
2449 def f1(x: int) -> None:
2450 if x == IE.X:
2451 reveal_type(x) # N: Revealed type is "builtins.int"
2452 else:
2453 reveal_type(x) # N: Revealed type is "builtins.int"
2454 if x != IE.X:
2455 reveal_type(x) # N: Revealed type is "builtins.int"
2456 else:
2457 reveal_type(x) # N: Revealed type is "builtins.int"
2458
2459 def f2(x: IE) -> None:
2460 if x == 1:
2461 reveal_type(x) # N: Revealed type is "__main__.IE"
2462 else:
2463 reveal_type(x) # N: Revealed type is "__main__.IE"
2464
2465 def f3(x: object) -> None:
2466 if x == IE.X:
2467 reveal_type(x) # N: Revealed type is "builtins.object"
2468 else:
2469 reveal_type(x) # N: Revealed type is "builtins.object"
2470
2471 def f4(x: int | Any) -> None:
2472 if x == IE.X:
2473 reveal_type(x) # N: Revealed type is "builtins.int | Any"
2474 else:
2475 reveal_type(x) # N: Revealed type is "builtins.int | Any"
2476
2477 def f5(x: int) -> None:
2478 if x is IE.X:
2479 reveal_type(x) # N: Revealed type is "Literal[__main__.IE.X]"
2480 else:
2481 reveal_type(x) # N: Revealed type is "builtins.int"
2482 if x is not IE.X:
2483 reveal_type(x) # N: Revealed type is "builtins.int"
2484 else:
2485 reveal_type(x) # N: Revealed type is "Literal[__main__.IE.X]"
2486
2487 def f6(x: IE) -> None:
2488 if x == IE.X:
2489 reveal_type(x) # N: Revealed type is "Literal[__main__.IE.X]"
2490 else:
2491 reveal_type(x) # N: Revealed type is "Literal[__main__.IE.Y]"
2492 [builtins fixtures/primitives.pyi]
2493
2494 [case testNarrowingWithIntEnum2]
2495 # flags: --strict-equality --warn-unreachable
2496 from __future__ import annotations
2497 from typing import Any
2498 from enum import IntEnum, Enum
2499
2500 class MyDecimal: ...
2501
2502 class IE(IntEnum):
2503 X = 1
2504 Y = 2
2505
2506 class IE2(IntEnum):
2507 X = 1
2508 Y = 2
2509
2510 class E(Enum):
2511 X = 1
2512 Y = 2
2513
2514 def f1(x: IE | MyDecimal) -> None:
2515 if x == IE.X:
2516 reveal_type(x) # N: Revealed type is "Literal[__main__.IE.X]"
2517 else:
2518 reveal_type(x) # N: Revealed type is "Literal[__main__.IE.Y] | __main__.MyDecimal"
2519
2520 def f2(x: E | bytes) -> None:
2521 if x == E.X:
2522 reveal_type(x) # N: Revealed type is "Literal[__main__.E.X]"
2523 else:
2524 reveal_type(x) # N: Revealed type is "Literal[__main__.E.Y] | builtins.bytes"
2525
2526 def f3(x: IE | IE2) -> None:
2527 if x == IE.X:
2528 reveal_type(x) # N: Revealed type is "Literal[__main__.IE.X] | __main__.IE2"
2529 else:
2530 reveal_type(x) # N: Revealed type is "Literal[__main__.IE.Y] | __main__.IE2"
2531
2532 def f4(x: IE | E) -> None:
2533 if x == IE.X:
2534 reveal_type(x) # N: Revealed type is "Literal[__main__.IE.X]"
2535 elif x == E.X:
2536 reveal_type(x) # N: Revealed type is "Literal[__main__.E.X]"
2537 else:
2538 reveal_type(x) # N: Revealed type is "Literal[__main__.IE.Y] | Literal[__main__.E.Y]"
2539
2540 def f5(x: E | str | int) -> None:
2541 if x == E.X:
2542 reveal_type(x) # N: Revealed type is "Literal[__main__.E.X]"
2543 else:
2544 reveal_type(x) # N: Revealed type is "Literal[__main__.E.Y] | builtins.str | builtins.int"
2545
2546 def f6(x: IE | Any) -> None:
2547 if x == IE.X:
2548 reveal_type(x) # N: Revealed type is "Literal[__main__.IE.X] | Any"
2549 else:
2550 reveal_type(x) # N: Revealed type is "Literal[__main__.IE.Y] | Any"
2551
2552 def f7(x: IE | None) -> None:
2553 if x == IE.X:
2554 reveal_type(x) # N: Revealed type is "Literal[__main__.IE.X]"
2555 else:
2556 reveal_type(x) # N: Revealed type is "Literal[__main__.IE.Y] | None"
2557
2558 def f8(x: IE | None) -> None:
2559 if x is None:
2560 reveal_type(x) # N: Revealed type is "None"
2561 elif x == IE.X:
2562 reveal_type(x) # N: Revealed type is "Literal[__main__.IE.X]"
2563 else:
2564 reveal_type(x) # N: Revealed type is "Literal[__main__.IE.Y]"
2565 [builtins fixtures/primitives.pyi]
2566
2567 [case testNarrowingWithStrEnum]
2568 # flags: --strict-equality --warn-unreachable
2569 # mypy: strict-equality
2570 from enum import StrEnum
2571
2572 class SE(StrEnum):
2573 A = 'a'
2574 B = 'b'
2575
2576 def f1(x: str) -> None:
2577 if x == SE.A:
2578 reveal_type(x) # N: Revealed type is "builtins.str"
2579 else:
2580 reveal_type(x) # N: Revealed type is "builtins.str"
2581
2582 def f2(x: SE) -> None:
2583 if x == 'a':
2584 reveal_type(x) # N: Revealed type is "__main__.SE"
2585 else:
2586 reveal_type(x) # N: Revealed type is "__main__.SE"
2587
2588 def f3(x: object) -> None:
2589 if x == SE.A:
2590 reveal_type(x) # N: Revealed type is "builtins.object"
2591 else:
2592 reveal_type(x) # N: Revealed type is "builtins.object"
2593
2594 def f4(x: SE) -> None:
2595 if x == SE.A:
2596 reveal_type(x) # N: Revealed type is "Literal[__main__.SE.A]"
2597 else:
2598 reveal_type(x) # N: Revealed type is "Literal[__main__.SE.B]"
2599 [builtins fixtures/primitives.pyi]
2600
2601 [case testNarrowingWithBytesEnum]
2602 # flags: --strict-equality --warn-unreachable
2603 from enum import Enum
2604
2605 class BE(bytes, Enum):
2606 A = b'a'
2607 B = b'b'
2608
2609 def f1(x: object) -> None:
2610 if x == BE.A:
2611 reveal_type(x) # N: Revealed type is "Literal[__main__.BE.A]"
2612 else:
2613 reveal_type(x) # N: Revealed type is "builtins.object"
2614
2615 def f2(x: BE) -> None:
2616 if x == BE.A:
2617 reveal_type(x) # N: Revealed type is "Literal[__main__.BE.A]"
2618 else:
2619 reveal_type(x) # N: Revealed type is "Literal[__main__.BE.B]"
2620
2621 def f3(x: bytearray | BE) -> None:
2622 if x == BE.A:
2623 reveal_type(x) # N: Revealed type is "builtins.bytearray | Literal[__main__.BE.A]"
2624 else:
2625 reveal_type(x) # N: Revealed type is "builtins.bytearray | Literal[__main__.BE.B]"
2626
2627 def f4(x: memoryview | BE) -> None:
2628 if x == BE.A:
2629 reveal_type(x) # N: Revealed type is "builtins.memoryview | Literal[__main__.BE.A]"
2630 else:
2631 reveal_type(x) # N: Revealed type is "builtins.memoryview | Literal[__main__.BE.B]"
2632 [builtins fixtures/primitives.pyi]
2633
2634 [case testNarrowingWithEnumStrSubclass]
2635 # flags: --strict-equality --warn-unreachable
2636 from enum import Enum
2637
2638 class ParameterLocation(str, Enum):
2639 QUERY = "query"
2640 HEADER = "header"
2641 PATH = "path"
2642
2643 def foo(location: ParameterLocation):
2644 if location == "path":
2645 reveal_type(location) # N: Revealed type is "__main__.ParameterLocation"
2646 else:
2647 reveal_type(location) # N: Revealed type is "__main__.ParameterLocation"
2648
2649 if location == ParameterLocation.PATH:
2650 reveal_type(location) # N: Revealed type is "Literal[__main__.ParameterLocation.PATH]"
2651 else:
2652 reveal_type(location) # N: Revealed type is "Literal[__main__.ParameterLocation.QUERY] | Literal[__main__.ParameterLocation.HEADER]"
2653 [builtins fixtures/primitives.pyi]
2654
2655 [case testConsistentNarrowingEqAndIn]
2656 # flags: --strict-equality --warn-unreachable
2657
2658 # https://github.com/python/mypy/issues/17864
2659 def f(x: str | int) -> None:
2660 if x == "x":
2661 reveal_type(x) # N: Revealed type is "builtins.str"
2662 y = x
2663
2664 if x in ["x"]:
2665 reveal_type(x) # N: Revealed type is "builtins.str"
2666 y = x
2667 z = x
2668 z = y
2669 [builtins fixtures/primitives.pyi]
2670
2671 [case testConsistentNarrowingEqAndInWithCustomEq]
2672 # flags: --strict-equality --warn-unreachable
2673
2674 # https://github.com/python/mypy/issues/17864
2675 class C:
2676 def __init__(self, x: int) -> None:
2677 self.x = x
2678
2679 def __eq__(self, other: object) -> bool:
2680 raise
2681 # Example implementation:
2682 # if isinstance(other, C) and other.x == self.x:
2683 # return True
2684 # return NotImplemented
2685
2686 class D(C):
2687 pass
2688
2689 def f1(x: C) -> None:
2690 if x in [D(5)]:
2691 reveal_type(x) # D # N: Revealed type is "__main__.C"
2692
2693 f1(C(5))
2694
2695 def f2(x: C) -> None:
2696 if x == D(5):
2697 reveal_type(x) # D # N: Revealed type is "__main__.C"
2698
2699 f2(C(5))
2700 [builtins fixtures/primitives.pyi]
2701
2702 [case testNarrowingTypeVarNone]
2703 # flags: --strict-equality --warn-unreachable
2704
2705 # https://github.com/python/mypy/issues/18126
2706 from typing import TypeVar
2707
2708 T = TypeVar("T")
2709
2710 def fn_if(arg: T) -> None:
2711 if arg is None:
2712 return None
2713 return None
2714
2715 def fn_while(arg: T) -> None:
2716 while arg is None:
2717 return None
2718 return None
2719 [builtins fixtures/primitives.pyi]
2720
2721 -- Parallel mode does not support --no-local-partial-types
2722 [case testRefinePartialTypeWithinLoop_no_parallel]
2723 # flags: --no-local-partial-types --strict-equality --warn-unreachable
2724
2725 x = None
2726 for _ in range(2):
2727 if x is not None:
2728 reveal_type(x) # N: Revealed type is "builtins.int"
2729 x = 1
2730 reveal_type(x) # N: Revealed type is "builtins.int | None"
2731
2732 def f() -> bool: ...
2733
2734 y = None
2735 while f():
2736 reveal_type(y) # N: Revealed type is "None | builtins.int"
2737 y = 1
2738 reveal_type(y) # N: Revealed type is "builtins.int | None"
2739
2740 z = [] # E: Need type annotation for "z" (hint: "z: list[<type>] = ...")
2741 def g() -> None:
2742 for i in range(2):
2743 while f():
2744 if z:
2745 z[0] + "v" # E: Unsupported operand types for + ("int" and "str")
2746 z.append(1)
2747
2748 class A:
2749 def g(self) -> None:
2750 z = [] # E: Need type annotation for "z" (hint: "z: list[<type>] = ...")
2751 for i in range(2):
2752 while f():
2753 if z:
2754 z[0] + "v" # E: Unsupported operand types for + ("int" and "str")
2755 z.append(1)
2756 [builtins fixtures/primitives.pyi]
2757
2758 [case testPersistentUnreachableLinesNestedInInpersistentUnreachableLines]
2759 # flags: --warn-unreachable --python-version 3.11 --strict-equality
2760
2761 x = None
2762 y = None
2763 while True:
2764 if x is not None:
2765 if y is not None:
2766 reveal_type(y) # E: Statement is unreachable
2767 x = 1
2768 [builtins fixtures/bool.pyi]
2769
2770 [case testAvoidFalseRedundantCastInLoops]
2771 # flags: --warn-redundant-casts --strict-equality --warn-unreachable
2772
2773 from typing import Callable, cast, Union
2774
2775 ProcessorReturnValue = Union[str, int]
2776 Processor = Callable[[str], ProcessorReturnValue]
2777
2778 def main_cast(p: Processor) -> None:
2779 ed: ProcessorReturnValue
2780 ed = cast(str, ...)
2781 while True:
2782 ed = p(cast(str, ed))
2783
2784 def main_no_cast(p: Processor) -> None:
2785 ed: ProcessorReturnValue
2786 ed = cast(str, ...)
2787 while True:
2788 ed = p(ed) # E: Argument 1 has incompatible type "str | int"; expected "str"
2789 [builtins fixtures/bool.pyi]
2790
2791 [case testAvoidFalseUnreachableInLoop1]
2792 # flags: --warn-unreachable --python-version 3.11 --strict-equality
2793
2794 def f() -> int | None: ...
2795 def b() -> bool: ...
2796
2797 x: int | None
2798 x = 1
2799 while x is not None or b():
2800 x = f()
2801 [builtins fixtures/bool.pyi]
2802
2803 [case testAvoidFalseUnreachableInLoop2]
2804 # flags: --warn-unreachable --python-version 3.11 --strict-equality
2805
2806 y = None
2807 while y is None:
2808 if y is None:
2809 y = []
2810 y.append(1)
2811 [builtins fixtures/list.pyi]
2812
2813 [case testAvoidFalseUnreachableInLoop3]
2814 # flags: --warn-unreachable --python-version 3.11 --strict-equality
2815
2816 xs: list[int | None]
2817 y = None
2818 for x in xs:
2819 if x is not None:
2820 if y is None:
2821 y = {} # E: Need type annotation for "y" (hint: "y: dict[<type>, <type>] = ...")
2822 [builtins fixtures/list.pyi]
2823
2824 [case testAvoidFalseRedundantExprInLoop]
2825 # flags: --enable-error-code redundant-expr --python-version 3.11 --strict-equality --warn-unreachable
2826
2827 def f() -> int | None: ...
2828 def b() -> bool: ...
2829
2830 x: int | None
2831 x = 1
2832 while x is not None and b():
2833 x = f()
2834 [builtins fixtures/primitives.pyi]
2835
2836 [case testAvoidFalseNonOverlappingEqualityCheckInLoop1]
2837 # flags: --allow-redefinition --strict-equality --warn-unreachable
2838
2839 def f(x: int) -> None:
2840 while True:
2841 if x == str():
2842 break
2843 x = str()
2844 if x == int(): # E: Non-overlapping equality check (left operand type: "str", right operand type: "int")
2845 break # E: Statement is unreachable
2846 [builtins fixtures/primitives.pyi]
2847
2848 [case testAvoidFalseNonOverlappingEqualityCheckInLoop2]
2849 # flags: --allow-redefinition --strict-equality --warn-unreachable
2850
2851 class A: ...
2852 class B: ...
2853 class C: ...
2854
2855 def f(x: A) -> None:
2856 while True:
2857 if x == C(): # E: Non-overlapping equality check (left operand type: "A | B", right operand type: "C")
2858 break # E: Statement is unreachable
2859 x = B()
2860 [builtins fixtures/primitives.pyi]
2861
2862 [case testAvoidFalseNonOverlappingEqualityCheckInLoop3]
2863 # flags: --strict-equality --warn-unreachable
2864
2865 for y in [1.0]:
2866 if y is not None or y != "None": # E: Right operand of "or" is never evaluated
2867 ...
2868
2869 [builtins fixtures/primitives.pyi]
2870
2871 [case testNarrowPromotionsInsideUnions1]
2872 # flags: --strict-equality --warn-unreachable
2873
2874 from typing import Union
2875
2876 x: Union[str, float, None]
2877 y: Union[int, str]
2878 x = y
2879 reveal_type(x) # N: Revealed type is "builtins.str | builtins.int"
2880 z: Union[complex, str]
2881 z = x
2882 reveal_type(z) # N: Revealed type is "builtins.int | builtins.str"
2883
2884 [builtins fixtures/primitives.pyi]
2885
2886 [case testNarrowPromotionsInsideUnions2]
2887 # flags: --strict-equality --warn-unreachable
2888
2889 from typing import Optional
2890
2891 def b() -> bool: ...
2892 def i() -> int: ...
2893 x: Optional[float]
2894
2895 while b():
2896 x = None
2897 while b():
2898 reveal_type(x) # N: Revealed type is "None | builtins.int"
2899 if x is None or b():
2900 x = i()
2901 reveal_type(x) # N: Revealed type is "builtins.int"
2902
2903 [builtins fixtures/bool.pyi]
2904
2905 [case testAvoidFalseUnreachableInFinally]
2906 # flags: --allow-redefinition --strict-equality --warn-unreachable
2907 def f() -> None:
2908 try:
2909 x = 1
2910 if int():
2911 x = ""
2912 return
2913 if int():
2914 x = None
2915 return
2916 finally:
2917 reveal_type(x) # N: Revealed type is "builtins.int | builtins.str | None"
2918 if isinstance(x, str):
2919 reveal_type(x) # N: Revealed type is "builtins.str"
2920 reveal_type(x) # N: Revealed type is "builtins.int | builtins.str | None"
2921
2922 [builtins fixtures/isinstancelist.pyi]
2923
2924 [case testNarrowingTypeVarMultiple]
2925 # flags: --strict-equality --warn-unreachable
2926 from typing import TypeVar
2927
2928 class A: ...
2929 class B: ...
2930
2931 T = TypeVar("T")
2932 def foo(x: T) -> T:
2933 if isinstance(x, A):
2934 pass
2935 elif isinstance(x, B):
2936 pass
2937 else:
2938 raise
2939 reveal_type(x) # N: Revealed type is "T`-1"
2940 return x
2941 [builtins fixtures/isinstance.pyi]
2942
2943 [case testDoNotNarrowToNever]
2944 # flags: --strict-equality --warn-unreachable
2945 def any():
2946 return 1
2947
2948 def f() -> None:
2949 x = "a"
2950 x = any()
2951 assert isinstance(x, int)
2952 reveal_type(x) # N: Revealed type is "builtins.int"
2953 [builtins fixtures/isinstance.pyi]
2954
2955 [case testNarrowTypeVarBoundType]
2956 # flags: --strict-equality --warn-unreachable
2957 from typing import Type, TypeVar
2958
2959 class A: ...
2960 class B(A):
2961 other: int
2962
2963 T = TypeVar("T", bound=A)
2964 def test(cls: Type[T]) -> T:
2965 if issubclass(cls, B):
2966 reveal_type(cls) # N: Revealed type is "type[T`-1]"
2967 reveal_type(cls().other) # N: Revealed type is "builtins.int"
2968 return cls()
2969 return cls()
2970 [builtins fixtures/isinstance.pyi]
2971
2972 [case testNarrowTypeVarBoundUnion]
2973 # flags: --strict-equality --warn-unreachable
2974 from typing import TypeVar
2975
2976 class A:
2977 x: int
2978 class B:
2979 x: str
2980
2981 T = TypeVar("T")
2982 def test(x: T) -> T:
2983 if not isinstance(x, (A, B)):
2984 return x
2985 reveal_type(x) # N: Revealed type is "T`-1"
2986 reveal_type(x.x) # N: Revealed type is "builtins.int | builtins.str"
2987 if isinstance(x, A):
2988 reveal_type(x) # N: Revealed type is "T`-1"
2989 reveal_type(x.x) # N: Revealed type is "builtins.int"
2990 return x
2991 reveal_type(x) # N: Revealed type is "T`-1"
2992 reveal_type(x.x) # N: Revealed type is "builtins.str"
2993 return x
2994 [builtins fixtures/isinstance.pyi]
2995
2996 [case testIsinstanceNarrowingWithSelfTypes]
2997 # flags: --strict-equality --warn-unreachable
2998 from typing import Generic, TypeVar, overload
2999
3000 T = TypeVar("T")
3001
3002 class A(Generic[T]):
3003 def __init__(self: A[int]) -> None:
3004 pass
3005
3006 def check_a(obj: "A[T] | str") -> None:
3007 reveal_type(obj) # N: Revealed type is "__main__.A[T`-1] | builtins.str"
3008 if isinstance(obj, A):
3009 reveal_type(obj) # N: Revealed type is "__main__.A[T`-1]"
3010 else:
3011 reveal_type(obj) # N: Revealed type is "builtins.str"
3012
3013
3014 class B(Generic[T]):
3015 @overload
3016 def __init__(self, x: T) -> None: ...
3017 @overload
3018 def __init__(self: B[int]) -> None: ...
3019 def __init__(self, x: "T | None" = None) -> None:
3020 pass
3021
3022 def check_b(obj: "B[T] | str") -> None:
3023 reveal_type(obj) # N: Revealed type is "__main__.B[T`-1] | builtins.str"
3024 if isinstance(obj, B):
3025 reveal_type(obj) # N: Revealed type is "__main__.B[T`-1]"
3026 else:
3027 reveal_type(obj) # N: Revealed type is "builtins.str"
3028
3029
3030 class C(Generic[T]):
3031 @overload
3032 def __init__(self: C[int]) -> None: ...
3033 @overload
3034 def __init__(self, x: T) -> None: ...
3035 def __init__(self, x: "T | None" = None) -> None:
3036 pass
3037
3038 def check_c(obj: "C[T] | str") -> None:
3039 reveal_type(obj) # N: Revealed type is "__main__.C[T`-1] | builtins.str"
3040 if isinstance(obj, C):
3041 reveal_type(obj) # N: Revealed type is "__main__.C[T`-1]"
3042 else:
3043 reveal_type(obj) # N: Revealed type is "builtins.str"
3044
3045
3046 class D(tuple[T], Generic[T]): ...
3047
3048 def check_d(arg: D[T]) -> None:
3049 if not isinstance(arg, D):
3050 return # E: Statement is unreachable
3051 reveal_type(arg) # N: Revealed type is "tuple[T`-1, fallback=__main__.D[Any]]"
3052 [builtins fixtures/tuple.pyi]
3053
3054
3055 [case testNarrowingUnionMixins]
3056 # flags: --strict-equality --warn-unreachable
3057 class Base: ...
3058
3059 class FooMixin:
3060 def foo(self) -> None: ...
3061
3062 class BarMixin:
3063 def bar(self) -> None: ...
3064
3065 def baz(item: Base) -> None:
3066 if not isinstance(item, (FooMixin, BarMixin)):
3067 raise
3068
3069 reveal_type(item) # N: Revealed type is "__main__.<subclass of "__main__.Base" and "__main__.FooMixin"> | __main__.<subclass of "__main__.Base" and "__main__.BarMixin">"
3070 if isinstance(item, FooMixin):
3071 reveal_type(item) # N: Revealed type is "__main__.<subclass of "__main__.Base" and "__main__.FooMixin">"
3072 item.foo()
3073 else:
3074 reveal_type(item) # N: Revealed type is "__main__.<subclass of "__main__.Base" and "__main__.BarMixin">"
3075 item.bar()
3076 [builtins fixtures/isinstance.pyi]
3077
3078 [case testCustomSetterNarrowingReWidened]
3079 # flags: --strict-equality --warn-unreachable
3080 class B: ...
3081 class C(B): ...
3082 class C1(B): ...
3083 class D(C): ...
3084
3085 class Test:
3086 @property
3087 def foo(self) -> C: ...
3088 @foo.setter
3089 def foo(self, val: B) -> None: ...
3090
3091 t: Test
3092 t.foo = D()
3093 reveal_type(t.foo) # N: Revealed type is "__main__.D"
3094 t.foo = C1()
3095 reveal_type(t.foo) # N: Revealed type is "__main__.C"
3096 [builtins fixtures/property.pyi]
3097
3098 [case testNarrowingNotImplemented]
3099 # flags: --warn-unreachable
3100 from __future__ import annotations
3101 import types
3102
3103 def foo(x: types.NotImplementedType | str):
3104 if x is not NotImplemented:
3105 reveal_type(x) # N: Revealed type is "builtins.str"
3106
3107 from typing_extensions import Self
3108
3109 class X:
3110 def __divmod__(self, other: Self | int) -> tuple[Self, Self]: ...
3111
3112 def __floordiv__(self, other: Self | int) -> Self:
3113 qr = self.__divmod__(other)
3114 if qr is NotImplemented:
3115 return NotImplemented
3116 return qr[0]
3117 [builtins fixtures/notimplemented.pyi]
3118
3119
3120 [case testNarrowingBooleans]
3121 # flags: --warn-return-any --strict-equality --warn-unreachable
3122 from typing import Any
3123
3124 def foo(x: dict[str, Any]) -> bool:
3125 if x.get("event") is False:
3126 return False
3127 if x.get("event") is True:
3128 return True
3129 raise
3130 [builtins fixtures/dict.pyi]
3131
3132
3133 [case testNarrowingTypeObjects]
3134 # flags: --strict-equality --warn-unreachable
3135 from __future__ import annotations
3136 from typing import Callable, Any, TypeVar, Generic, Protocol
3137 _T_co = TypeVar('_T_co', covariant=True)
3138
3139 class Boxxy(Protocol[_T_co]):
3140 def get_box(self) -> _T_co: ...
3141
3142 class TupleLike(Generic[_T_co]):
3143 def __init__(self, iterable: Boxxy[_T_co], /) -> None:
3144 raise
3145
3146 class Box1(Generic[_T_co]):
3147 def __init__(self, content: _T_co, /) -> None: ...
3148 def get_box(self) -> _T_co: raise
3149
3150 class Box2(Generic[_T_co]):
3151 def __init__(self, content: _T_co, /) -> None: ...
3152 def get_box(self) -> _T_co: raise
3153
3154 def get_type(setting_name: str) -> Callable[[Box1], Any] | type[Any]:
3155 raise
3156
3157 def main(key: str):
3158 existing_value_type = get_type(key)
3159 if existing_value_type is TupleLike:
3160 reveal_type(TupleLike) # N: Revealed type is "def [_T_co] (__main__.Boxxy[_T_co`1]) -> __main__.TupleLike[_T_co`1]"
3161 reveal_type(TupleLike(Box2("str"))) # N: Revealed type is "__main__.TupleLike[builtins.str]"
3162
3163 reveal_type(existing_value_type) # N: Revealed type is "(def [_T_co] (__main__.Boxxy[_T_co`1]) -> __main__.TupleLike[_T_co`1]) | type[Any]"
3164 reveal_type(existing_value_type(Box2("str"))) # N: Revealed type is "__main__.TupleLike[builtins.str] | Any"
3165 [builtins fixtures/tuple.pyi]
3166
3167 [case testNarrowingCollections]
3168 # flags: --strict-equality --warn-unreachable
3169 from typing import cast
3170
3171 class X:
3172 def __init__(self) -> None:
3173 self.x: dict[str, str] = {}
3174 self.y: list[str] = []
3175
3176 def xxx(self) -> None:
3177 if self.x == {}:
3178 reveal_type(self.x) # N: Revealed type is "builtins.dict[builtins.str, builtins.str]"
3179 self.x["asdf"]
3180
3181 if self.x == dict():
3182 reveal_type(self.x) # N: Revealed type is "builtins.dict[builtins.str, builtins.str]"
3183 self.x["asdf"]
3184
3185 if self.x == cast(dict[int, int], {}): # E: Non-overlapping equality check (left operand type: "dict[str, str]", right operand type: "dict[int, int]")
3186 reveal_type(self.x) # N: Revealed type is "builtins.dict[builtins.str, builtins.str]"
3187 self.x["asdf"]
3188
3189 def yyy(self) -> None:
3190 if self.y == []:
3191 reveal_type(self.y) # N: Revealed type is "builtins.list[builtins.str]"
3192 self.y[0].does_not_exist # E: "str" has no attribute "does_not_exist"
3193
3194 if self.y == list():
3195 reveal_type(self.y) # N: Revealed type is "builtins.list[builtins.str]"
3196 self.y[0].does_not_exist # E: "str" has no attribute "does_not_exist"
3197
3198 if self.y == cast(list[int], []): # E: Non-overlapping equality check (left operand type: "list[str]", right operand type: "list[int]")
3199 reveal_type(self.y) # N: Revealed type is "builtins.list[builtins.str]"
3200 self.y[0].does_not_exist # E: "str" has no attribute "does_not_exist"
3201 [builtins fixtures/dict.pyi]
3202
3203
3204 [case testNarrowStringInLiteralContainer]
3205 # flags: --strict-equality --warn-unreachable
3206 from typing import Literal
3207
3208 def narrow_tuple(x: str, t: tuple[Literal['a', 'b']]):
3209 if x in t:
3210 reveal_type(x) # N: Revealed type is "Literal['a'] | Literal['b']"
3211 else:
3212 reveal_type(x) # N: Revealed type is "builtins.str"
3213
3214 if x not in t:
3215 reveal_type(x) # N: Revealed type is "builtins.str"
3216 else:
3217 reveal_type(x) # N: Revealed type is "Literal['a'] | Literal['b']"
3218
3219 def narrow_homo_tuple(x: str, t: tuple[Literal['a', 'b'], ...]):
3220 if x in t:
3221 reveal_type(x) # N: Revealed type is "Literal['a'] | Literal['b']"
3222 else:
3223 reveal_type(x) # N: Revealed type is "builtins.str"
3224
3225 def narrow_list(x: str, t: list[Literal['a', 'b']]):
3226 if x in t:
3227 reveal_type(x) # N: Revealed type is "Literal['a'] | Literal['b']"
3228 else:
3229 reveal_type(x) # N: Revealed type is "builtins.str"
3230
3231 def narrow_set(x: str, t: set[Literal['a', 'b']]):
3232 if x in t:
3233 reveal_type(x) # N: Revealed type is "Literal['a'] | Literal['b']"
3234 else:
3235 reveal_type(x) # N: Revealed type is "builtins.str"
3236 [builtins fixtures/primitives.pyi]
3237
3238 [case testNarrowLiteralInLiteralContainer]
3239 # flags: --strict-equality --warn-unreachable
3240 from typing import Literal
3241
3242 def narrow_tuple_exact(x: Literal['a', 'b', 'c'], t: tuple[Literal['a'], Literal['b']]):
3243 if x in t:
3244 reveal_type(x) # N: Revealed type is "Literal['a'] | Literal['b']"
3245 else:
3246 reveal_type(x) # N: Revealed type is "Literal['c']"
3247
3248 if x not in t:
3249 reveal_type(x) # N: Revealed type is "Literal['c']"
3250 else:
3251 reveal_type(x) # N: Revealed type is "Literal['a'] | Literal['b']"
3252
3253 def narrow_tuple_expression(x: Literal['a', 'b', 'c']):
3254 # TODO: this should match narrow_tuple_exact
3255 if x in ('a', 'b'):
3256 reveal_type(x) # N: Revealed type is "Literal['a'] | Literal['b']"
3257 else:
3258 reveal_type(x) # N: Revealed type is "Literal['a'] | Literal['b'] | Literal['c']"
3259
3260 if x not in ('a', 'b'):
3261 reveal_type(x) # N: Revealed type is "Literal['a'] | Literal['b'] | Literal['c']"
3262 else:
3263 reveal_type(x) # N: Revealed type is "Literal['a'] | Literal['b']"
3264
3265 def narrow_tuple_union(x: Literal['a', 'b', 'c'], t: tuple[Literal['a', 'b']]):
3266 if x in t:
3267 reveal_type(x) # N: Revealed type is "Literal['a'] | Literal['b']"
3268 else:
3269 reveal_type(x) # N: Revealed type is "Literal['a'] | Literal['b'] | Literal['c']"
3270
3271 if x not in t:
3272 reveal_type(x) # N: Revealed type is "Literal['a'] | Literal['b'] | Literal['c']"
3273 else:
3274 reveal_type(x) # N: Revealed type is "Literal['a'] | Literal['b']"
3275
3276 def narrow_tuple_with_other_type(x: Literal['a', 'b', 'c'], t: tuple[Literal['a'], int]):
3277 if x in t:
3278 reveal_type(x) # N: Revealed type is "Literal['a']"
3279 else:
3280 reveal_type(x) # N: Revealed type is "Literal['b'] | Literal['c']"
3281
3282 def narrow_homo_tuple(x: Literal['a', 'b', 'c'], t: tuple[Literal['a', 'b'], ...]):
3283 if x in t:
3284 reveal_type(x) # N: Revealed type is "Literal['a'] | Literal['b']"
3285 else:
3286 reveal_type(x) # N: Revealed type is "Literal['a'] | Literal['b'] | Literal['c']"
3287
3288 def narrow_list(x: Literal['a', 'b', 'c'], t: list[Literal['a', 'b']]):
3289 if x in t:
3290 reveal_type(x) # N: Revealed type is "Literal['a'] | Literal['b']"
3291 else:
3292 reveal_type(x) # N: Revealed type is "Literal['a'] | Literal['b'] | Literal['c']"
3293
3294 if x in ['a', 'b']:
3295 reveal_type(x) # N: Revealed type is "Literal['a'] | Literal['b']"
3296 else:
3297 reveal_type(x) # N: Revealed type is "Literal['a'] | Literal['b'] | Literal['c']"
3298
3299 if x in ['a', 'b', *[]]:
3300 reveal_type(x) # N: Revealed type is "Literal['a'] | Literal['b'] | Literal['c']"
3301 else:
3302 reveal_type(x) # N: Revealed type is "Literal['a'] | Literal['b'] | Literal['c']"
3303
3304 def narrow_set(x: Literal['a', 'b', 'c'], t: set[Literal['a', 'b']]):
3305 if x in t:
3306 reveal_type(x) # N: Revealed type is "Literal['a'] | Literal['b']"
3307 else:
3308 reveal_type(x) # N: Revealed type is "Literal['a'] | Literal['b'] | Literal['c']"
3309
3310 if x in {'a', 'b'}:
3311 reveal_type(x) # N: Revealed type is "Literal['a'] | Literal['b']"
3312 else:
3313 reveal_type(x) # N: Revealed type is "Literal['a'] | Literal['b'] | Literal['c']"
3314
3315 if x in {'a', 'b', *[]}:
3316 reveal_type(x) # N: Revealed type is "Literal['a'] | Literal['b'] | Literal['c']"
3317 else:
3318 reveal_type(x) # N: Revealed type is "Literal['a'] | Literal['b'] | Literal['c']"
3319
3320 def narrow_dict(x: Literal['a', 'b', 'c'], t: dict[Literal['a', 'b'], int]):
3321 if x in t: # E: Unsupported operand types for in ("Literal['a', 'b', 'c']" and "dict[Literal['a', 'b'], int]")
3322 reveal_type(x) # N: Revealed type is "Literal['a'] | Literal['b']"
3323 else:
3324 reveal_type(x) # N: Revealed type is "Literal['a'] | Literal['b'] | Literal['c']"
3325
3326 if x in {'a': 0, 'b': 1}:
3327 reveal_type(x) # N: Revealed type is "Literal['a'] | Literal['b']"
3328 else:
3329 reveal_type(x) # N: Revealed type is "Literal['a'] | Literal['b'] | Literal['c']"
3330
3331 if x in {'a': 0, 'b': 1, **{}}:
3332 reveal_type(x) # N: Revealed type is "Literal['a'] | Literal['b'] | Literal['c']"
3333 else:
3334 reveal_type(x) # N: Revealed type is "Literal['a'] | Literal['b'] | Literal['c']"
3335 [builtins fixtures/primitives.pyi]
3336
3337
3338 [case testNarrowingLiteralInLiteralContainer]
3339 # flags: --strict-equality --warn-unreachable
3340 from typing import Literal
3341
3342 def narrow_tuple(x: Literal['c'], overlap: list[Literal['b', 'c']], no_overlap: list[Literal['a', 'b']]):
3343 if x in overlap:
3344 reveal_type(x) # N: Revealed type is "Literal['c']"
3345 else:
3346 reveal_type(x) # N: Revealed type is "Literal['c']"
3347
3348 if x in no_overlap:
3349 reveal_type(x) # E: Statement is unreachable
3350 else:
3351 reveal_type(x) # N: Revealed type is "Literal['c']"
3352 [builtins fixtures/tuple.pyi]
3353
3354 [case testTypeNarrowingUnionInContainer]
3355 # flags: --strict-equality --warn-unreachable
3356 from typing import Union, Literal
3357
3358 def f1(x: Union[str, float], t1: list[Literal['a', 'b']], t2: list[str]):
3359 if x in t1:
3360 reveal_type(x) # N: Revealed type is "Literal['a'] | Literal['b']"
3361 else:
3362 reveal_type(x) # N: Revealed type is "builtins.str | builtins.float"
3363
3364 if x in t2:
3365 reveal_type(x) # N: Revealed type is "builtins.str"
3366 else:
3367 reveal_type(x) # N: Revealed type is "builtins.str | builtins.float"
3368 [builtins fixtures/primitives.pyi]
3369
3370 [case testNegativeNarrowingInContainer]
3371 # flags: --warn-unreachable
3372 from enum import Enum
3373
3374 class Color(Enum):
3375 RED = 1
3376
3377 def count(colors: list[Color]) -> None:
3378 counts: dict[Color, int] = {}
3379 for color in colors:
3380 if color not in counts:
3381 counts[color] = 0
3382 counts[color] += 1
3383 [builtins fixtures/dict.pyi]
3384
3385 [case testNarrowAnyWithEqualityOrContainment]
3386 # flags: --strict-equality --warn-unreachable
3387 # https://github.com/python/mypy/issues/17841
3388 from typing import Any
3389
3390 def f1(x: Any) -> None:
3391 if x is not None and x not in ["x"]:
3392 return
3393 reveal_type(x) # N: Revealed type is "Any"
3394
3395 def f2(x: Any) -> None:
3396 if x is not None and x != "x":
3397 return
3398 reveal_type(x) # N: Revealed type is "Any"
3399 [builtins fixtures/tuple.pyi]
3400
3401 [case testNarrowAnyUnion]
3402 from typing import Any
3403
3404 class A: ...
3405
3406 def f1(x: A | int, y: Any):
3407 if x == y:
3408 reveal_type(x) # N: Revealed type is "__main__.A | builtins.int"
3409 reveal_type(y) # N: Revealed type is "Any"
3410 else:
3411 reveal_type(x) # N: Revealed type is "__main__.A | builtins.int"
3412 reveal_type(y) # N: Revealed type is "Any"
3413
3414 def f2(x: A | int, y: Any | None):
3415 if x == y:
3416 reveal_type(x) # N: Revealed type is "__main__.A | builtins.int"
3417 reveal_type(y) # N: Revealed type is "Any"
3418 else:
3419 reveal_type(x) # N: Revealed type is "__main__.A | builtins.int"
3420 reveal_type(y) # N: Revealed type is "Any | None"
3421
3422 class AA(A): ...
3423
3424 def f3(x: A | int, y: AA | Any):
3425 if x == y:
3426 reveal_type(x) # N: Revealed type is "__main__.A | builtins.int"
3427 reveal_type(y) # N: Revealed type is "__main__.AA | Any"
3428 else:
3429 reveal_type(x) # N: Revealed type is "__main__.A | builtins.int"
3430 reveal_type(y) # N: Revealed type is "__main__.AA | Any"
3431 [builtins fixtures/primitives.pyi]
3432
3433 [case testNarrowChainedContainment]
3434 # flags: --strict-equality --warn-unreachable
3435
3436 def bad_compare_has_key(has_key: bool, key: str, s: tuple[str, ...]) -> None:
3437 if has_key == key in s: # E: Non-overlapping equality check (left operand type: "bool", right operand type: "str")
3438 reveal_type(has_key) # E: Statement is unreachable
3439 reveal_type(key)
3440
3441 def bad_but_should_pass(has_key: bool, key: bool, s: tuple[bool, ...]) -> None:
3442 if has_key == key in s:
3443 reveal_type(has_key) # N: Revealed type is "builtins.bool"
3444 reveal_type(key) # N: Revealed type is "builtins.bool"
3445 [builtins fixtures/primitives.pyi]
3446
3447 [case testNarrowChainedComparisonMeetAndForwardPropagation]
3448 # flags: --strict-equality --warn-unreachable
3449 from __future__ import annotations
3450 from typing import Any
3451
3452 def f1(a: str | None, b: str | None) -> None:
3453 if None is not a == b:
3454 reveal_type(a) # N: Revealed type is "builtins.str"
3455 reveal_type(b) # N: Revealed type is "builtins.str"
3456
3457 if (None is not a) and (a == b):
3458 reveal_type(a) # N: Revealed type is "builtins.str"
3459 reveal_type(b) # N: Revealed type is "builtins.str"
3460
3461 def f2(a: Any | None, b: str | None) -> None:
3462 if None is not a == b:
3463 reveal_type(a) # N: Revealed type is "Any"
3464 reveal_type(b) # N: Revealed type is "builtins.str | None"
3465
3466 if (None is not a) and (a == b):
3467 reveal_type(a) # N: Revealed type is "Any"
3468 reveal_type(b) # N: Revealed type is "builtins.str | None"
3469
3470 def f3(a: str | None, b: Any | None) -> None:
3471 if None is not a == b:
3472 reveal_type(a) # N: Revealed type is "builtins.str"
3473 reveal_type(b) # N: Revealed type is "Any"
3474
3475 if (None is not a) and (a == b):
3476 reveal_type(a) # N: Revealed type is "builtins.str"
3477 reveal_type(b) # N: Revealed type is "Any"
3478
3479 def f4(a: str | None, b: str | None, c: str | None) -> None:
3480 if None is not a == b == c:
3481 reveal_type(a) # N: Revealed type is "builtins.str"
3482 reveal_type(b) # N: Revealed type is "builtins.str"
3483 reveal_type(c) # N: Revealed type is "builtins.str"
3484
3485 if (None is not a) and (a == b) and (b == c):
3486 reveal_type(a) # N: Revealed type is "builtins.str"
3487 reveal_type(b) # N: Revealed type is "builtins.str"
3488 reveal_type(c) # N: Revealed type is "builtins.str"
3489
3490 def f5(pair: tuple[None, int] | tuple[str, str], other: str | None) -> None:
3491 if None is not pair[0] == other:
3492 reveal_type(pair[0]) # N: Revealed type is "builtins.str"
3493 reveal_type(pair) # N: Revealed type is "tuple[builtins.str, builtins.str]"
3494 reveal_type(other) # N: Revealed type is "builtins.str"
3495
3496 if (None is not pair[0]) and (pair[0] == other):
3497 reveal_type(pair[0]) # N: Revealed type is "builtins.str"
3498 reveal_type(pair) # N: Revealed type is "tuple[builtins.str, builtins.str]"
3499 reveal_type(other) # N: Revealed type is "builtins.str"
3500 [builtins fixtures/primitives.pyi]
3501
3502 [case testNarrowTypeObject]
3503 # flags: --strict-equality --warn-unreachable
3504 from typing import Any
3505
3506 # https://github.com/python/mypy/issues/13704
3507
3508 def f1(cls: type):
3509 if cls is str:
3510 reveal_type(cls) # N: Revealed type is "def (o: builtins.object =) -> builtins.str"
3511 reveal_type(cls(5)) # N: Revealed type is "builtins.str"
3512
3513 if issubclass(cls, int):
3514 reveal_type(cls) # N: Revealed type is "type[builtins.int]"
3515 elif cls is str:
3516 reveal_type(cls) # N: Revealed type is "def (o: builtins.object =) -> builtins.str"
3517 reveal_type(cls(5)) # N: Revealed type is "builtins.str"
3518
3519 def f2(cls: type[object]):
3520 if cls is str:
3521 reveal_type(cls) # N: Revealed type is "def (o: builtins.object =) -> builtins.str"
3522 reveal_type(cls(5)) # N: Revealed type is "builtins.str"
3523
3524 if issubclass(cls, int):
3525 reveal_type(cls) # N: Revealed type is "type[builtins.int]"
3526 elif cls is str:
3527 reveal_type(cls) # N: Revealed type is "def (o: builtins.object =) -> builtins.str"
3528 reveal_type(cls(5)) # N: Revealed type is "builtins.str"
3529
3530 def f3(cls: type[Any]):
3531 if cls is str:
3532 reveal_type(cls) # N: Revealed type is "type[Any]"
3533 reveal_type(cls(5)) # N: Revealed type is "Any"
3534
3535 if issubclass(cls, int):
3536 reveal_type(cls) # N: Revealed type is "type[builtins.int]"
3537 elif cls is str:
3538 reveal_type(cls) # N: Revealed type is "type[Any]"
3539 reveal_type(cls(5)) # N: Revealed type is "Any"
3540 [builtins fixtures/isinstance.pyi]
3541
3542 [case testNarrowTypeObjectUnion]
3543 # flags: --strict-equality --warn-unreachable
3544 from __future__ import annotations
3545
3546 def f4(cls: type[str | int]):
3547 reveal_type(cls) # N: Revealed type is "type[builtins.str] | type[builtins.int]"
3548
3549 if cls is int:
3550 reveal_type(cls) # N: Revealed type is "type[builtins.int]"
3551 if cls == int:
3552 reveal_type(cls) # N: Revealed type is "type[builtins.int]"
3553 [builtins fixtures/primitives.pyi]
3554
3555
3556 [case testTypeEqualsCheck]
3557 # flags: --strict-equality --warn-unreachable
3558 from typing import Any
3559
3560 y: Any
3561 if type(y) == int:
3562 reveal_type(y) # N: Revealed type is "builtins.int"
3563
3564 [case testMultipleTypeEqualsCheck]
3565 # flags: --strict-equality --warn-unreachable
3566 from typing import Any
3567
3568 x: Any
3569 y: Any
3570 if type(x) == type(y) == int:
3571 reveal_type(y) # N: Revealed type is "builtins.int"
3572 reveal_type(x) # N: Revealed type is "builtins.int"
3573
3574 z: Any
3575 if int == type(z) == int:
3576 reveal_type(z) # N: Revealed type is "builtins.int"
3577
3578 [case testTypeEqualsCheckWidening]
3579 # flags: --strict-equality --warn-unreachable
3580 from typing import Any
3581
3582 def f(x: str, y: Any, z: object):
3583 if type(x) is type(y):
3584 reveal_type(x) # N: Revealed type is "builtins.str"
3585 reveal_type(y) # N: Revealed type is "builtins.str"
3586
3587 if type(x) == type(y):
3588 reveal_type(x) # N: Revealed type is "builtins.str"
3589 reveal_type(y) # N: Revealed type is "builtins.str"
3590
3591 if type(x) is type(z):
3592 reveal_type(x) # N: Revealed type is "builtins.str"
3593 reveal_type(z) # N: Revealed type is "builtins.str"
3594
3595 if type(x) == type(z):
3596 reveal_type(x) # N: Revealed type is "builtins.str"
3597 reveal_type(z) # N: Revealed type is "builtins.str"
3598 [builtins fixtures/primitives.pyi]
3599
3600 [case testTypeEqualsCheckWideningSelf]
3601 # flags: --strict-equality --warn-unreachable
3602 from typing import Any
3603 from typing_extensions import Self
3604
3605 class A:
3606 def f(self: Self, y: Any, z: object):
3607 if type(self) is type(y):
3608 reveal_type(self) # N: Revealed type is "Self`0"
3609 reveal_type(y) # N: Revealed type is "Self`0"
3610
3611 if type(self) is type(z):
3612 reveal_type(self) # N: Revealed type is "Self`0"
3613 reveal_type(z) # N: Revealed type is "Self`0"
3614
3615 if type(self) == type(y):
3616 reveal_type(self) # N: Revealed type is "Self`0"
3617 reveal_type(y) # N: Revealed type is "Self`0"
3618
3619 if type(self) == type(z):
3620 reveal_type(self) # N: Revealed type is "Self`0"
3621 reveal_type(z) # N: Revealed type is "Self`0"
3622 [builtins fixtures/primitives.pyi]
3623
3624 [case testTypeEqualsCheckUsingIs]
3625 # flags: --strict-equality --warn-unreachable
3626 from typing import Any
3627
3628 y: Any
3629 if type(y) is int:
3630 reveal_type(y) # N: Revealed type is "builtins.int"
3631
3632 [case testTypeEqualsCheckUsingIsNonOverlapping]
3633 # flags: --strict-equality --warn-unreachable
3634 from typing import Union
3635
3636 y: str
3637 if type(y) is int: # E: Non-overlapping identity check (left operand type: "type[str]", right operand type: "type[int]") \
3638 # E: Subclass of "str" and "int" cannot exist: would have incompatible method signatures
3639 y # E: Statement is unreachable
3640 else:
3641 reveal_type(y) # N: Revealed type is "builtins.str"
3642 [builtins fixtures/isinstance.pyi]
3643
3644 [case testTypeEqualsCheckUsingIsNonOverlappingChild]
3645 # flags: --strict-equality --warn-unreachable
3646 from typing import Union
3647
3648 class A: ...
3649 class B: ...
3650 class C(A): ...
3651 def main(x: Union[B, C]):
3652 # C instance cannot be exactly its parent A, we need reversed subtyping relationship
3653 # here (type(parent) is Child).
3654 if type(x) is A:
3655 reveal_type(x) # E: Statement is unreachable
3656 else:
3657 reveal_type(x) # N: Revealed type is "__main__.B | __main__.C"
3658 [builtins fixtures/isinstance.pyi]
3659
3660 [case testTypeEqualsCheckTypeVar]
3661 # flags: --strict-equality --warn-unreachable
3662 from typing import TypeVar
3663
3664 class A: ...
3665 class B: ...
3666
3667 T = TypeVar("T")
3668
3669 def forgets_about_subclasses(self, obj: T) -> T:
3670 if isinstance(obj, A):
3671 return A() # E: Incompatible return value type (got "A", expected "T")
3672 elif isinstance(obj, B):
3673 return B() # E: Incompatible return value type (got "B", expected "T")
3674 raise
3675
3676 def correct1(self, obj: T) -> T:
3677 # TODO: mypy should not error in this case
3678 if type(obj) == A:
3679 return A() # E: Incompatible return value type (got "A", expected "T")
3680 elif type(obj) == B:
3681 return B() # E: Incompatible return value type (got "B", expected "T")
3682 raise
3683
3684 T_value = TypeVar("T_value", A, B)
3685
3686 def forgets_about_multiple_inheritance(self, obj: T_value) -> T_value:
3687 # Note that it is a little confusing that mypy only errors in the first branch here, but this
3688 # is a branch that would be taken by a subclass of both A and B.
3689 # See also https://github.com/python/mypy/issues/10302#issuecomment-3832182574
3690 if isinstance(obj, A):
3691 return A() # E: Incompatible return value type (got "A", expected "B")
3692 elif isinstance(obj, B):
3693 return B()
3694 raise
3695
3696 def correct2(self, obj: T_value) -> T_value:
3697 if type(obj) == A:
3698 return A()
3699 elif type(obj) == B:
3700 return B()
3701 raise
3702 [builtins fixtures/primitives.pyi]
3703
3704 [case testTypeEqualsCheckUsingDifferentSpecializedTypes]
3705 # flags: --strict-equality --warn-unreachable
3706 from collections import defaultdict
3707
3708 x: defaultdict
3709 y: dict
3710 z: object
3711 if type(x) is type(y) is type(z):
3712 reveal_type(x) # N: Revealed type is "collections.defaultdict[Any, Any]"
3713 reveal_type(y) # N: Revealed type is "collections.defaultdict[Any, Any]"
3714 reveal_type(z) # N: Revealed type is "collections.defaultdict[Any, Any]"
3715
3716 [case testTypeEqualsTypeObjectUnion]
3717 # flags: --strict-equality --warn-unreachable
3718 from __future__ import annotations
3719 def f(x: object, y: type[int] | type[str]):
3720 if type(x) == y:
3721 reveal_type(x) # N: Revealed type is "builtins.int | builtins.str"
3722 reveal_type(y) # N: Revealed type is "type[builtins.int] | type[builtins.str]"
3723 [builtins fixtures/primitives.pyi]
3724
3725 [case testUnionTypeEquality]
3726 # flags: --strict-equality --warn-unreachable
3727 from typing import Any, reveal_type
3728
3729 def f(x: Any):
3730 if type(x) == (int, str): # E: Non-overlapping equality check (left operand type: "type[Any]", right operand type: "tuple[type[int], type[str]]")
3731 reveal_type(x) # E: Statement is unreachable
3732 [builtins fixtures/tuple.pyi]
3733
3734 [case testTypeIntersectionWithConcreteTypes]
3735 # flags: --strict-equality --warn-unreachable
3736 class X: x = 1
3737 class Y: y = 1
3738 class Z(X, Y): ...
3739
3740 z = Z()
3741 x: X = z
3742 y: Y = z
3743 if type(x) is type(y): # E: Non-overlapping identity check (left operand type: "type[X]", right operand type: "type[Y]")
3744 reveal_type(x) # N: Revealed type is "__main__.<subclass of "__main__.X" and "__main__.Y">"
3745 reveal_type(y) # N: Revealed type is "__main__.<subclass of "__main__.Y" and "__main__.X">"
3746 x.y + y.x
3747
3748 if isinstance(x, type(y)) and isinstance(y, type(x)):
3749 reveal_type(x) # N: Revealed type is "__main__.<subclass of "__main__.X" and "__main__.Y">"
3750 reveal_type(y) # N: Revealed type is "__main__.<subclass of "__main__.X" and "__main__.Y">"
3751 x.y + y.x
3752
3753 [builtins fixtures/isinstance.pyi]
3754
3755 [case testTypeEqualsNarrowingUnionWithElse]
3756 # flags: --strict-equality --warn-unreachable
3757 from typing import Union
3758
3759 x: Union[int, str]
3760 if type(x) is int:
3761 reveal_type(x) # N: Revealed type is "builtins.int"
3762 else:
3763 reveal_type(x) # N: Revealed type is "builtins.int | builtins.str"
3764
3765 [case testTypeEqualsMultipleTypesShouldntNarrow]
3766 # flags: --strict-equality --warn-unreachable
3767
3768 from typing import Union
3769
3770 x: Union[int, str]
3771 if type(x) == int == str: # E: Non-overlapping equality check (left operand type: "type[int]", right operand type: "type[str]")
3772 reveal_type(x) # E: Statement is unreachable
3773 else:
3774 reveal_type(x) # N: Revealed type is "builtins.int | builtins.str"
3775
3776 [builtins fixtures/primitives.pyi]
3777
3778 [case testTypeNotEqualsCheck]
3779 # flags: --strict-equality --warn-unreachable
3780 from typing import Union
3781
3782 x: Union[int, str]
3783 if type(x) != int:
3784 reveal_type(x) # N: Revealed type is "builtins.int | builtins.str"
3785 else:
3786 reveal_type(x) # N: Revealed type is "builtins.int"
3787
3788 # mypy thinks int isn't defined unless we include this
3789 [builtins fixtures/primitives.pyi]
3790
3791 [case testTypeNotEqualsCheckUsingIsNot]
3792 # flags: --strict-equality --warn-unreachable
3793 from typing import Union
3794
3795 x: Union[int, str]
3796 if type(x) is not int:
3797 reveal_type(x) # N: Revealed type is "builtins.int | builtins.str"
3798 else:
3799 reveal_type(x) # N: Revealed type is "builtins.int"
3800
3801 [case testTypeNarrowingAgainstType]
3802 # flags: --strict-equality --warn-unreachable
3803 class A:
3804 def foo(self, x: object) -> None:
3805 reveal_type(self) # N: Revealed type is "__main__.A"
3806 reveal_type(x) # N: Revealed type is "builtins.object"
3807 if type(self) is type(x):
3808 reveal_type(self) # N: Revealed type is "__main__.A"
3809 reveal_type(x) # N: Revealed type is "__main__.A"
3810 else:
3811 reveal_type(self) # N: Revealed type is "__main__.A"
3812 reveal_type(x) # N: Revealed type is "builtins.object"
3813 if type(self) == type(x):
3814 reveal_type(self) # N: Revealed type is "__main__.A"
3815 reveal_type(x) # N: Revealed type is "__main__.A"
3816 else:
3817 reveal_type(self) # N: Revealed type is "__main__.A"
3818 reveal_type(x) # N: Revealed type is "builtins.object"
3819
3820 class B:
3821 y: int
3822
3823 def __eq__(self, other: object) -> bool:
3824 return type(other) is type(self) and other.y == self.y
3825 [builtins fixtures/primitives.pyi]
3826
3827 [case testNarrowInElseCaseIfFinal]
3828 # flags: --strict-equality --warn-unreachable
3829 from typing import final, Union
3830 @final
3831 class C:
3832 pass
3833 class D:
3834 pass
3835
3836 x: Union[C, D]
3837 if type(x) is C:
3838 reveal_type(x) # N: Revealed type is "__main__.C"
3839 else:
3840 reveal_type(x) # N: Revealed type is "__main__.D"
3841
3842 [case testNarrowInIfCaseIfFinalUsingIsNot]
3843 # flags: --strict-equality --warn-unreachable
3844 from typing import final, Union
3845 @final
3846 class C:
3847 pass
3848 class D:
3849 pass
3850
3851 x: Union[C, D]
3852 if type(x) is not C:
3853 reveal_type(x) # N: Revealed type is "__main__.D"
3854 else:
3855 reveal_type(x) # N: Revealed type is "__main__.C"
3856
3857 [case testDunderClassNarrowing]
3858 # flags: --strict-equality --warn-unreachable
3859 from typing import Any
3860
3861 def foo(y: object):
3862 if y.__class__ == int:
3863 reveal_type(y) # N: Revealed type is "builtins.int"
3864 else:
3865 reveal_type(y) # N: Revealed type is "builtins.object"
3866
3867 if y.__class__ is int:
3868 reveal_type(y) # N: Revealed type is "builtins.int"
3869 else:
3870 reveal_type(y) # N: Revealed type is "builtins.object"
3871
3872
3873 def bar(y: Any):
3874 if y.__class__ == int:
3875 reveal_type(y) # N: Revealed type is "builtins.int"
3876 else:
3877 reveal_type(y) # N: Revealed type is "Any"
3878
3879 if y.__class__ is int:
3880 reveal_type(y) # N: Revealed type is "builtins.int"
3881 else:
3882 reveal_type(y) # N: Revealed type is "Any"
3883 [builtins fixtures/dict-full.pyi]
3884
3885
3886 [case testNarrowTypeVarType]
3887 # flags: --strict-equality --warn-unreachable
3888 from typing import TypeVar
3889
3890 T = TypeVar("T")
3891
3892 class A: ...
3893
3894 def foo(X: type[T]) -> T:
3895 if X == A:
3896 return X()
3897 raise
3898
3899 # It could be nice to make these two test cases consistent, but it would be tricky
3900 # The above case is much more common in real world code
3901 def bar(X: type[T]) -> T:
3902 if X == A:
3903 return A() # E: Incompatible return value type (got "A", expected "T")
3904 raise
3905 [builtins fixtures/type.pyi]
3906
3907 [case testNarrowingConstrainedTypeVarType]
3908 # flags: --strict-equality --warn-unreachable
3909 from typing import TypeVar, Any, Type
3910
3911 TargetType = TypeVar("TargetType", int, float, str)
3912
3913 def convert_type(target_type: Type[TargetType]) -> TargetType:
3914 if target_type == str:
3915 return str()
3916 if target_type == int:
3917 return int()
3918 if target_type == float:
3919 return float()
3920 raise
3921
3922
3923 [builtins fixtures/primitives.pyi]
3924
3925
3926 [case testNarrowingEqualityWithPromotions]
3927 # flags: --strict-equality --warn-unreachable
3928 from __future__ import annotations
3929 from typing import Literal
3930
3931 def f1(number: float, i: int):
3932 if number == i:
3933 reveal_type(number) # N: Revealed type is "builtins.float"
3934 reveal_type(i) # N: Revealed type is "builtins.int"
3935
3936 def f2(number: float, five: Literal[5]):
3937 if number == five:
3938 reveal_type(number) # N: Revealed type is "builtins.float"
3939 reveal_type(five) # N: Revealed type is "Literal[5]"
3940
3941 def f3(number: float | int, five: Literal[5]):
3942 if number == five:
3943 reveal_type(number) # N: Revealed type is "Literal[5] | builtins.float"
3944 reveal_type(five) # N: Revealed type is "Literal[5]"
3945
3946 def f8(number: float | Literal[5], five: Literal[5]):
3947 if number == five:
3948 reveal_type(number) # N: Revealed type is "builtins.float | Literal[5]"
3949 reveal_type(five) # N: Revealed type is "Literal[5]"
3950 else:
3951 reveal_type(number) # N: Revealed type is "builtins.float"
3952 reveal_type(five) # N: Revealed type is "Literal[5]"
3953
3954 def f4(number: float | None, i: int):
3955 if number == i:
3956 reveal_type(number) # N: Revealed type is "builtins.float"
3957 reveal_type(i) # N: Revealed type is "builtins.int"
3958
3959 def f5(number: float | int, i: int):
3960 if number == i:
3961 reveal_type(number) # N: Revealed type is "builtins.float | builtins.int"
3962 reveal_type(i) # N: Revealed type is "builtins.int"
3963
3964 def f6(number: float | complex, i: int):
3965 if number == i:
3966 reveal_type(number) # N: Revealed type is "builtins.float | builtins.complex"
3967 reveal_type(i) # N: Revealed type is "builtins.int"
3968
3969 class Custom:
3970 def __eq__(self, other: object) -> bool: return True
3971
3972 def f7(number: float, x: Custom | int):
3973 if number == x:
3974 reveal_type(number) # N: Revealed type is "builtins.float"
3975 reveal_type(x) # N: Revealed type is "__main__.Custom | builtins.int"
3976 [builtins fixtures/primitives.pyi]
3977
3978 [case testNarrowingAnyNegativeIntersection-xfail]
3979 # flags: --strict-equality --warn-unreachable
3980 # https://github.com/python/mypy/issues/20597
3981 from __future__ import annotations
3982 from typing import Any
3983
3984 class array: ...
3985
3986 def get_result() -> Any: ...
3987
3988 def foo(x: str | array) -> str:
3989 result = get_result()
3990 if isinstance(result, array):
3991 return "asdf"
3992 if result is x:
3993 reveal_type(result) # N: Revealed type is "Any"
3994 return result
3995 raise
3996 [builtins fixtures/tuple.pyi]
3997
3998 [case testNarrowingOptionalBytes]
3999 from __future__ import annotations
4000 def f(x: bytes | None):
4001 if x == b"asdf":
4002 reveal_type(x) # N: Revealed type is "builtins.bytes"
4003 else:
4004 reveal_type(x) # N: Revealed type is "builtins.bytes | None"
4005 [builtins fixtures/primitives.pyi]
4006
4007 [case testNarrowingBytesLikeWithPromotion]
4008 # flags: --strict-equality --warn-unreachable --strict-bytes
4009 from __future__ import annotations
4010 from typing import Any
4011
4012 def check_test(x: bytes) -> None: ...
4013 check_test(bytearray(b"asdf")) # E: Argument 1 to "check_test" has incompatible type "bytearray"; expected "bytes"
4014
4015 def main(
4016 v_bytes: bytes,
4017 v_bytearray: bytearray,
4018 v_memoryview: memoryview,
4019 v_all: bytes | bytearray | memoryview,
4020 v_object: object,
4021 v_any: Any,
4022 ) -> None:
4023 if v_bytes == v_bytearray:
4024 reveal_type(v_bytes) # N: Revealed type is "builtins.bytes"
4025 reveal_type(v_bytearray) # N: Revealed type is "builtins.bytearray"
4026 if v_bytes == v_memoryview:
4027 reveal_type(v_bytes) # N: Revealed type is "builtins.bytes"
4028 reveal_type(v_memoryview) # N: Revealed type is "builtins.memoryview"
4029 if v_bytearray == v_memoryview:
4030 reveal_type(v_bytearray) # N: Revealed type is "builtins.bytearray"
4031 reveal_type(v_memoryview) # N: Revealed type is "builtins.memoryview"
4032
4033 if v_all == v_bytes:
4034 reveal_type(v_all) # N: Revealed type is "builtins.bytes | builtins.bytearray | builtins.memoryview"
4035 reveal_type(v_bytes) # N: Revealed type is "builtins.bytes"
4036 if v_all == v_bytearray:
4037 reveal_type(v_all) # N: Revealed type is "builtins.bytes | builtins.bytearray | builtins.memoryview"
4038 reveal_type(v_bytearray) # N: Revealed type is "builtins.bytearray"
4039 if v_all == v_memoryview:
4040 reveal_type(v_all) # N: Revealed type is "builtins.bytes | builtins.bytearray | builtins.memoryview"
4041 reveal_type(v_memoryview) # N: Revealed type is "builtins.memoryview"
4042
4043 if v_object == v_bytes:
4044 reveal_type(v_object) # N: Revealed type is "builtins.bytes"
4045 if v_object == b"asdf":
4046 reveal_type(v_object) # N: Revealed type is "Literal[b'asdf']?"
4047 if v_any == v_bytes:
4048 reveal_type(v_any) # N: Revealed type is "Any"
4049 if v_any == b"asdf":
4050 reveal_type(v_any) # N: Revealed type is "Any"
4051 [builtins fixtures/primitives.pyi]
4052
4053 [case testNarrowingBytesLikeNoPromotion]
4054 # flags: --strict-equality --warn-unreachable --no-strict-bytes
4055 from __future__ import annotations
4056 from typing import Any
4057
4058 def check_test(x: bytes) -> None: ...
4059 check_test(bytearray(b"asdf"))
4060
4061 def main(
4062 v_bytes: bytes,
4063 v_bytearray: bytearray,
4064 v_memoryview: memoryview,
4065 v_all: bytes | bytearray | memoryview,
4066 v_object: object,
4067 v_any: Any,
4068 ) -> None:
4069 if v_bytes == v_bytearray:
4070 reveal_type(v_bytes) # N: Revealed type is "builtins.bytes"
4071 reveal_type(v_bytearray) # N: Revealed type is "builtins.bytearray"
4072 if v_bytes == v_memoryview:
4073 reveal_type(v_bytes) # N: Revealed type is "builtins.bytes"
4074 reveal_type(v_memoryview) # N: Revealed type is "builtins.memoryview"
4075 if v_bytearray == v_memoryview:
4076 reveal_type(v_bytearray) # N: Revealed type is "builtins.bytearray"
4077 reveal_type(v_memoryview) # N: Revealed type is "builtins.memoryview"
4078
4079 if v_all == v_bytes:
4080 reveal_type(v_all) # N: Revealed type is "builtins.bytes | builtins.bytearray | builtins.memoryview"
4081 reveal_type(v_bytes) # N: Revealed type is "builtins.bytes"
4082 if v_all == v_bytearray:
4083 reveal_type(v_all) # N: Revealed type is "builtins.bytes | builtins.bytearray | builtins.memoryview"
4084 reveal_type(v_bytearray) # N: Revealed type is "builtins.bytearray"
4085 if v_all == v_memoryview:
4086 reveal_type(v_all) # N: Revealed type is "builtins.bytes | builtins.bytearray | builtins.memoryview"
4087 reveal_type(v_memoryview) # N: Revealed type is "builtins.memoryview"
4088
4089 if v_object == v_bytes:
4090 reveal_type(v_object) # N: Revealed type is "builtins.bytes"
4091 if v_object == b"asdf":
4092 reveal_type(v_object) # N: Revealed type is "Literal[b'asdf']?"
4093 if v_any == v_bytes:
4094 reveal_type(v_any) # N: Revealed type is "Any"
4095 if v_any == b"asdf":
4096 reveal_type(v_any) # N: Revealed type is "Any"
4097 [builtins fixtures/primitives.pyi]
4098
4099
4100 [case testNarrowNewTypeVsSubclass]
4101 # mypy: strict-equality, warn-unreachable
4102 from typing import NewType
4103
4104 M1 = NewType("M1", int)
4105 M2 = NewType("M2", int)
4106
4107 def check_m(base: int, m1: M1, m2: M2):
4108 if m1 == m2: # E: Non-overlapping equality check (left operand type: "M1", right operand type: "M2")
4109 reveal_type(m1) # N: Revealed type is "__main__.M1"
4110 reveal_type(m2) # N: Revealed type is "__main__.M2"
4111
4112 if m1 == base:
4113 # We do not narrow base
4114 reveal_type(m1) # N: Revealed type is "__main__.M1"
4115 reveal_type(base) # N: Revealed type is "builtins.int"
4116 if m2 == base:
4117 reveal_type(m2) # N: Revealed type is "__main__.M2"
4118 reveal_type(base) # N: Revealed type is "builtins.int"
4119
4120 # We do narrow for subclasses! (assuming no custom equality)
4121 class A: ...
4122 class A1(A): ...
4123 class A2(A): ...
4124
4125 def check_a(base: A, a1: A1, a2: A2):
4126 if a1 == a2: # E: Non-overlapping equality check (left operand type: "A1", right operand type: "A2")
4127 reveal_type(a1) # E: Statement is unreachable
4128 reveal_type(a2)
4129
4130 if a1 == base:
4131 # We do narrow base
4132 reveal_type(a1) # N: Revealed type is "__main__.A1"
4133 reveal_type(base) # N: Revealed type is "__main__.A1"
4134 if a2 == base: # E: Non-overlapping equality check (left operand type: "A2", right operand type: "A1")
4135 reveal_type(a2) # E: Statement is unreachable
4136 reveal_type(base)
4137 [builtins fixtures/primitives.pyi]
4138
4139
4140 [case testNarrowNewTypeFromObject]
4141 # mypy: strict-equality, warn-unreachable
4142 from __future__ import annotations
4143 from typing import NewType
4144
4145 UserId = NewType("UserId", int)
4146
4147 def f1(whatever: object, uid: UserId):
4148 # The general principle is that we should not be able to produce a value of NewType
4149 # without there being explicit wrapping somewhere
4150 if whatever == uid:
4151 reveal_type(whatever) # N: Revealed type is "builtins.int"
4152 reveal_type(uid) # N: Revealed type is "__main__.UserId"
4153
4154 class Other: ...
4155
4156 def f2(whatever: object, uid: UserId | Other):
4157 if whatever == uid:
4158 reveal_type(whatever) # N: Revealed type is "builtins.int | __main__.Other"
4159 reveal_type(uid) # N: Revealed type is "__main__.UserId | __main__.Other"
4160 [builtins fixtures/primitives.pyi]
4161
4162
4163 [case testNarrowNewTypeNested]
4164 # mypy: strict-equality, warn-unreachable
4165 from typing import NewType, Final
4166
4167 Path = NewType("Path", str)
4168 NormPath = NewType("NormPath", Path)
4169
4170 def op(normpath: NormPath, path: Path):
4171 if normpath == path:
4172 # No narrowing
4173 reveal_type(normpath) # N: Revealed type is "__main__.NormPath"
4174 reveal_type(path) # N: Revealed type is "__main__.Path"
4175 [builtins fixtures/primitives.pyi]
4176
4177
4178 [case testNarrowNewTypeSharedValue]
4179 # mypy: strict-equality, warn-unreachable
4180 from typing import NewType, Final
4181
4182 UserId = NewType("UserId", int)
4183 TeamId = NewType("TeamId", int)
4184 INVALID = 123
4185
4186 def get_owner(uid: UserId, tid: TeamId):
4187 # No narrowing for INVALID
4188 if uid == INVALID:
4189 reveal_type(uid) # N: Revealed type is "__main__.UserId"
4190 reveal_type(tid) # N: Revealed type is "__main__.TeamId"
4191 reveal_type(INVALID) # N: Revealed type is "builtins.int"
4192 if tid == INVALID:
4193 reveal_type(uid) # N: Revealed type is "__main__.UserId"
4194 reveal_type(tid) # N: Revealed type is "__main__.TeamId"
4195 reveal_type(INVALID) # N: Revealed type is "builtins.int"
4196 return None
4197 [builtins fixtures/primitives.pyi]
4198
4199 [case testNarrowCallableTypeVarByEquality]
4200 from typing import Callable, TypeVar
4201
4202 T = TypeVar("T")
4203
4204 def remove(path: str) -> None: ...
4205 def unlink(path: str) -> None: ...
4206
4207 def f1(func: Callable[..., T], arg: str) -> T:
4208 if func == remove:
4209 reveal_type(func) # N: Revealed type is "def (path: builtins.str) -> T`-1"
4210 reveal_type(func(arg)) # N: Revealed type is "T`-1"
4211 return func(arg)
4212 return func(arg)
4213
4214 def f2(func: Callable[..., T], arg: str) -> T:
4215 if func in [unlink, remove]:
4216 reveal_type(func) # N: Revealed type is "def (path: builtins.str) -> T`-1"
4217 reveal_type(func(arg)) # N: Revealed type is "T`-1"
4218 return func(arg)
4219 return func(arg)
4220 [builtins fixtures/primitives.pyi]
4221
4222
4223 [case testNarrowGenericCallableEquality]
4224 # flags: --strict-equality --warn-unreachable
4225 from typing import Callable, TypeVar
4226
4227 S = TypeVar("S")
4228 T = TypeVar("T")
4229
4230 def identity(x: T) -> T:
4231 return x
4232
4233 def msg(cmp_property: Callable[[T], S]) -> None:
4234 if cmp_property == identity:
4235 # TODO: the swapping of these reveal's is not ideal
4236 reveal_type(cmp_property) # N: Revealed type is "def [T] (x: T`-1) -> T`-1"
4237 reveal_type(identity) # N: Revealed type is "def (T`-1) -> S`-2"
4238 return
4239 [builtins fixtures/primitives.pyi]
4240
4241
4242 [case testPropagatedParentNarrowingMeet]
4243 # flags: --strict-equality --warn-unreachable
4244 from __future__ import annotations
4245
4246 class A:
4247 tag: int
4248
4249 class B:
4250 tag: int
4251 name = "b"
4252
4253 class C:
4254 tag: str
4255
4256 def stringify(value: A | B | C) -> str:
4257 if isinstance(value.tag, int) and isinstance(value, B):
4258 reveal_type(value) # N: Revealed type is "__main__.B"
4259 return value.name
4260 return ""
4261 [builtins fixtures/tuple.pyi]
4262
4263 [case testTypeVariableBoundNarrowingSymmetric]
4264 from typing import TypeVar
4265
4266 class B: ...
4267 class C(B):
4268 x: int
4269
4270 H = TypeVar('H', bound=B)
4271
4272 def func(y: H) -> H:
4273 x: C
4274 assert x == y
4275 reveal_type(x) # N: Revealed type is "H`-1"
4276 reveal_type(y) # N: Revealed type is "H`-1"
4277 reveal_type(x.x) # N: Revealed type is "builtins.int"
4278 reveal_type(y.x) # N: Revealed type is "builtins.int"
4279 if bool():
4280 return x
4281 else:
4282 return y
4283 [builtins fixtures/primitives.pyi]