File: check-inference-context.test

package info (click to toggle)
mypy 1.19.1-5
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 22,464 kB
  • sloc: python: 114,757; ansic: 13,343; cpp: 11,380; makefile: 254; sh: 31
file content (1600 lines) | stat: -rw-r--r-- 39,588 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600


-- Basic test cases
-- ----------------


[case testBasicContextInference]
from typing import TypeVar, Generic
T = TypeVar('T')

def f() -> 'A[T]': pass

class A(Generic[T]): pass
class B: pass

ab: A[B]
ao: A[object]
b: B

if int():
    ao = f()
if int():
    ab = f()
if int():
    b = f() # E: Incompatible types in assignment (expression has type "A[Never]", variable has type "B")
[case testBasicContextInferenceForConstructor]
from typing import TypeVar, Generic
T = TypeVar('T')
class A(Generic[T]): pass
class B: pass
ab: A[B]
ao: A[object]
b: B

if int():
    ao = A()
if int():
    ab = A()
if int():
    b = A() # E: Incompatible types in assignment (expression has type "A[Never]", variable has type "B")
[case testIncompatibleContextInference]
from typing import TypeVar, Generic
T = TypeVar('T')
def f(a: T) -> 'A[T]':
    pass

class A(Generic[T]): pass

class B: pass
class C: pass
b: B
c: C
ab: A[B]
ao: A[object]
ac: A[C]

if int():
    ac = f(b) # E: Argument 1 to "f" has incompatible type "B"; expected "C"
if int():
    ab = f(c) # E: Argument 1 to "f" has incompatible type "C"; expected "B"

if int():
    ao = f(b)
if int():
    ab = f(b)
if int():
    ao = f(c)
if int():
    ac = f(c)


-- Local variables
-- ---------------


[case testInferGenericLocalVariableTypeWithEmptyContext]
from typing import TypeVar, Generic
T = TypeVar('T')
def g() -> None:
    ao: A[object]
    ab: A[B]
    o: object
    b: B

    x = f(o)
    if int():
        ab = x # E: Incompatible types in assignment (expression has type "A[object]", variable has type "A[B]")
        ao = x
    y = f(b)
    if int():
        ao = y # E: Incompatible types in assignment (expression has type "A[B]", variable has type "A[object]")
        ab = y

def f(a: T) -> 'A[T]': pass

class A(Generic[T]): pass
class B: pass
[out]

[case testInferLocalVariableTypeWithUnderspecifiedGenericType]
from typing import TypeVar, Generic
T = TypeVar('T')
def g() -> None:
    x = f() # E: Need type annotation for "x"

def f() -> 'A[T]': pass
class A(Generic[T]): pass
[out]

[case testInferMultipleLocalVariableTypesWithTupleRvalue]
from typing import TypeVar, Generic
T = TypeVar('T')
def g() -> None:
    ao: A[object]
    ab: A[B]
    b: B
    x, y = f(b), f(b)
    if int():
        ao = x # E: Incompatible types in assignment (expression has type "A[B]", variable has type "A[object]")
        ao = y # E: Incompatible types in assignment (expression has type "A[B]", variable has type "A[object]")
        ab = x
        ab = y

def f(a: T) -> 'A[T]': pass
class A(Generic[T]): pass
class B: pass
[out]

[case testInferMultipleLocalVariableTypesWithArrayRvalueAndNesting]
from typing import TypeVar, List, Generic
T = TypeVar('T')
def h() -> None:
    ao: A[object]
    ab: A[B]
    b: B
    x, y = g(f(b))
    if int():
        ao = x # E: Incompatible types in assignment (expression has type "A[B]", variable has type "A[object]")
        ao = y # E: Incompatible types in assignment (expression has type "A[B]", variable has type "A[object]")
        ab = x
        ab = y

def f(a: T) -> 'A[T]': pass
def g(a: T) -> List[T]: pass

class A(Generic[T]): pass
class B: pass
[builtins fixtures/for.pyi]
[out]


-- Return types with multiple tvar instances
-- -----------------------------------------


[case testInferenceWithTypeVariableTwiceInReturnType]
from typing import TypeVar, Tuple, Generic
T = TypeVar('T')

def f(a: T) -> 'Tuple[A[T], A[T]]': pass

class A(Generic[T]): pass
class B: pass

b: B
o: object
ab: A[B]
ao: A[object]

if int():
    ab, ao = f(b) # E: Incompatible types in assignment (expression has type "A[B]", variable has type "A[object]")
if int():
    ao, ab = f(b) # E: Incompatible types in assignment (expression has type "A[B]", variable has type "A[object]")

if int():
    ao, ao = f(b)
if int():
    ab, ab = f(b)
if int():
    ao, ao = f(o)
[builtins fixtures/tuple.pyi]

[case testInferenceWithTypeVariableTwiceInReturnTypeAndMultipleVariables]
from typing import TypeVar, Tuple, Generic
S = TypeVar('S')
T = TypeVar('T')

def f(a: S, b: T) -> 'Tuple[A[S], A[T], A[T]]': pass
def g(a: S, b: T) -> 'Tuple[A[S], A[S], A[T]]': pass
def h(a: S, b: T) -> 'Tuple[A[S], A[S], A[T], A[T]]': pass

class A(Generic[T]): pass
class B: pass

b: B
o: object
ab: A[B]
ao: A[object]

if int():
    ao, ao, ab = f(b, b)     # E: Incompatible types in assignment (expression has type "A[B]", variable has type "A[object]")
if int():
    ao, ab, ao = g(b, b)     # E: Incompatible types in assignment (expression has type "A[B]", variable has type "A[object]")
if int():
    ao, ab, ab, ab = h(b, b) # E: Incompatible types in assignment (expression has type "A[B]", variable has type "A[object]")
if int():
    ab, ab, ao, ab = h(b, b) # E: Incompatible types in assignment (expression has type "A[B]", variable has type "A[object]")

if int():
    ao, ab, ab = f(b, b)
if int():
    ab, ab, ao = g(b, b)
if int():
    ab, ab, ab, ab = h(b, b)
[builtins fixtures/tuple.pyi]


-- Multiple tvar instances in arguments
-- ------------------------------------


[case testMultipleTvatInstancesInArgs]
from typing import TypeVar, Generic
T = TypeVar('T')

def f(a: T, b: T) -> 'A[T]': pass

class A(Generic[T]): pass
class B: pass
class C(B): pass

ac: A[C]
ab: A[B]
ao: A[object]
b: B
c: C
o: object

if int():
    ab = f(b, o) # E: Argument 2 to "f" has incompatible type "object"; expected "B"
if int():
    ab = f(o, b) # E: Argument 1 to "f" has incompatible type "object"; expected "B"
if int():
    ac = f(b, c) # E: Argument 1 to "f" has incompatible type "B"; expected "C"
if int():
    ac = f(c, b) # E: Argument 2 to "f" has incompatible type "B"; expected "C"

if int():
    ao = f(b, c)
if int():
    ao = f(c, b)
if int():
    ab = f(c, b)


-- Nested generic function calls
-- -----------------------------


[case testNestedGenericFunctionCall1]
from typing import TypeVar, Generic
T = TypeVar('T')

def f(a: T) -> 'A[T]': pass

class A(Generic[T]): pass
class B: pass

aab: A[A[B]]
aao: A[A[object]]
ao: A[object]
b: B
o: object

if int():
    aab = f(f(o)) # E: Argument 1 to "f" has incompatible type "object"; expected "B"

if int():
    aab = f(f(b))
    aao = f(f(b))
    ao = f(f(b))

[case testNestedGenericFunctionCall2]
from typing import TypeVar, Generic
T = TypeVar('T')

def f(a: T) -> T: pass
def g(a: T) -> 'A[T]': pass

class A(Generic[T]): pass
class B: pass

ab: A[B]
ao: A[object]
b: B
o: object

if int():
    ab = f(g(o)) # E: Argument 1 to "g" has incompatible type "object"; expected "B"

if int():
    ab = f(g(b))
    ao = f(g(b))

[case testNestedGenericFunctionCall3]
from typing import TypeVar, Generic
T = TypeVar('T')
def f(a: T, b: T) -> T:
    pass

def g(a: T) -> 'A[T]': pass

class A(Generic[T]): pass
class B: pass
ab: A[B]
ao: A[object]
b: B
o: object

if int():
    ab = f(g(o), g(b)) # E: Argument 1 to "g" has incompatible type "object"; expected "B"
if int():
    ab = f(g(b), g(o)) # E: Argument 1 to "g" has incompatible type "object"; expected "B"

if int():
    ab = f(g(b), g(b))
    ao = f(g(b), g(o))
if int():
    ao = f(g(o), g(b))


-- Method calls
-- ------------


[case testMethodCallWithContextInference]
from typing import TypeVar, Generic
T = TypeVar('T')
o: object
b: B
c: C
def f(a: T) -> 'A[T]': pass

class A(Generic[T]):
    def g(self, a: 'A[T]') -> 'A[T]': pass

class B: pass
class C(B): pass
ao: A[object]
ab: A[B]
ac: A[C]

ab.g(f(o))        # E: Argument 1 to "f" has incompatible type "object"; expected "B"
if int():
    ac = f(b).g(f(c)) # E: Incompatible types in assignment (expression has type "A[B]", variable has type "A[C]")
if int():
    ac = f(c).g(f(b)) # E: Argument 1 to "f" has incompatible type "B"; expected "C"

if int():
    ab = f(b).g(f(c))
ab.g(f(c))


-- List expressions
-- ----------------


[case testEmptyListExpression]
from typing import List
aa: List[A]
ao: List[object]
a: A
def f(): a, aa, ao # Prevent redefinition

a = [] # E: Incompatible types in assignment (expression has type "list[Never]", variable has type "A")

aa = []
ao = []

class A: pass
[builtins fixtures/list.pyi]

[case testSingleItemListExpressions]
from typing import List, Optional
aa: List[Optional[A]]
ab: List[B]
ao: List[object]
a: A
b: B
def f(): aa, ab, ao # Prevent redefinition

aa = [b] # E: List item 0 has incompatible type "B"; expected "Optional[A]"
ab = [a] # E: List item 0 has incompatible type "A"; expected "B"

aa = [a]
ab = [b]
ao = [a]
aa = [None]
ao = [None]

class A: pass
class B: pass
[builtins fixtures/list.pyi]

[case testMultiItemListExpressions]
from typing import List
aa: List[A]
ab: List[B]
ao: List[object]
a: A
b: B
def f(): ab, aa, ao # Prevent redefinition

ab = [b, a] # E: List item 1 has incompatible type "A"; expected "B"
ab = [a, b] # E: List item 0 has incompatible type "A"; expected "B"

aa = [a, b, a]
ao = [a, b]

class A: pass
class B(A): pass
[builtins fixtures/list.pyi]

[case testLocalVariableInferenceFromEmptyList]
import typing
def f() -> None:
    a = []     # E: Need type annotation for "a" (hint: "a: list[<type>] = ...")
    b = [None]
    c = [B()]
    if int():
        c = [object()] # E: List item 0 has incompatible type "object"; expected "B"
        c = [B()]
class B: pass
[builtins fixtures/list.pyi]
[out]

[case testNestedListExpressions]
# flags: --no-strict-optional
from typing import List
aao = None # type: list[list[object]]
aab = None # type: list[list[B]]
ab = None # type: list[B]
b = None # type: B
o = None # type: object
def f(): aao, aab # Prevent redefinition

aao = [[o], ab] # E: List item 1 has incompatible type "list[B]"; expected "list[object]"
aab = [[], [o]] # E: List item 0 has incompatible type "object"; expected "B"

aao = [[None], [b], [], [o]]
aab = [[None], [b], []]
aab = [ab, []]

class B: pass
[builtins fixtures/list.pyi]


-- Complex context
-- ---------------


[case testParenthesesAndContext]
from typing import List
class A: pass
l = ([A()]) # type: List[object]
[builtins fixtures/list.pyi]

[case testComplexTypeInferenceWithTuple]
from typing import TypeVar, Tuple, Generic
k = TypeVar('k')
t = TypeVar('t')
v = TypeVar('v')

class A(Generic[t]): pass
class B: pass
class C: pass
class D(Generic[k, v]): pass

def f(x: Tuple[k]) -> 'A[k]': pass

d = f((A(),)) # type: A[A[B]]
[builtins fixtures/list.pyi]


-- Dictionary literals
-- -------------------


[case testDictionaryLiteralInContext]
from typing import Dict, TypeVar, Generic
t = TypeVar('t')
class A(Generic[t]): pass
class B: pass
class C: pass
a_b = A() # type: A[B]
a_c = A() # type: A[C]
d = {A() : a_c,
     a_b : A()} # type: Dict[A[B], A[C]]
[builtins fixtures/dict.pyi]


-- Special cases (regression tests etc.)
-- -------------------------------------


[case testInitializationWithInferredGenericType]
from typing import TypeVar, Generic
T = TypeVar('T')

def f(x: T) -> T: pass
class C(Generic[T]): pass
class A: pass

c = f(A()) # type: C[A] # E: Argument 1 to "f" has incompatible type "A"; expected "C[A]"
[case testInferredGenericTypeAsReturnValue]
from typing import TypeVar, Generic
T = TypeVar('T')
def t() -> 'A[B]':
    return f(D()) # E: Argument 1 to "f" has incompatible type "D"; expected "B"
    return A()
    return f(C())

def f(a: T) -> 'A[T]': pass
class A(Generic[T]): pass
class B: pass
class C(B): pass
class D: pass
[out]

[case testIntersectionWithInferredGenericArgument]
from foo import *
[file foo.pyi]
from typing import overload, TypeVar, Generic
T = TypeVar('T')
f(A())

@overload
def f(x: 'A[B]') -> None: pass
@overload
def f(x: 'B') -> None: pass
class A(Generic[T]): pass
class B: pass

[case testInferenceWithAbstractClassContext]
from typing import TypeVar, Generic
from abc import abstractmethod, ABCMeta
t = TypeVar('t')

class I(Generic[t]):
    @abstractmethod
    def f(self): pass
class A(I[t], Generic[t]):
    def f(self): pass

x = A() # type: I[int]
a_object = A() # type: A[object]
y = a_object # type: I[int] # E: Incompatible types in assignment (expression has type "A[object]", variable has type "I[int]")

[case testInferenceWithAbstractClassContext2]
from typing import TypeVar, Generic
from abc import abstractmethod, ABCMeta
t = TypeVar('t')
class I(Generic[t]): pass
class A(I[t], Generic[t]): pass
def f(i: I[t]) -> A[t]: pass
a = f(A()) # type: A[int]
a_int = A() # type: A[int]
aa = f(a_int)

[case testInferenceWithAbstractClassContext3]
from typing import TypeVar, Generic, Iterable
t = TypeVar('t')
class set(Generic[t]):
    def __init__(self, iterable: Iterable[t]) -> None: pass
b = bool()
l = set([b])
if int():
    l = set([object()]) # E: List item 0 has incompatible type "object"; expected "bool"
[builtins fixtures/for.pyi]


-- Infer generic type in 'Any' context
-- -----------------------------------


[case testInferGenericTypeInAnyContext]
from typing import Any, TypeVar, Generic
s = TypeVar('s')
t = TypeVar('t')
class C(Generic[s, t]): pass
x = [] # type: Any
y = C() # type: Any
[builtins fixtures/list.pyi]


-- Lambdas
-- -------


[case testInferLambdaArgumentTypeUsingContext]
from typing import Callable
f: Callable[[B], A]
if int():
    f = lambda x: x.o
    f = lambda x: x.x # E: "B" has no attribute "x"
class A: pass
class B:
  o: A

[case testInferLambdaReturnTypeUsingContext]
from typing import List, Callable
f: Callable[[], List[A]]
if int():
    f = lambda: []
    f = lambda: [B()]  # E: List item 0 has incompatible type "B"; expected "A"
class A: pass
class B: pass
[builtins fixtures/list.pyi]

[case testInferLambdaTypeUsingContext]
x : str = (lambda x: x + 1)(1)  # E: Incompatible types in assignment (expression has type "int", variable has type "str")
reveal_type((lambda x, y: x + y)(1, 2))  # N: Revealed type is "builtins.int"
(lambda x, y: x + y)(1, "")  # E: Unsupported operand types for + ("int" and "str")
(lambda *, x, y: x + y)(x=1, y="")  # E: Unsupported operand types for + ("int" and "str")
reveal_type((lambda s, i: s)(i=0, s='x')) # N: Revealed type is "Literal['x']?"
reveal_type((lambda s, i: i)(i=0, s='x')) # N: Revealed type is "Literal[0]?"
reveal_type((lambda x, s, i: x)(1.0, i=0, s='x')) # N: Revealed type is "builtins.float"
if object():
    (lambda x, s, i: x)() # E: Too few arguments
if object():
    (lambda: 0)(1) # E: Too many arguments
-- varargs are not handled, but it should not crash
reveal_type((lambda *k, s, i: i)(type, i=0, s='x')) # N: Revealed type is "Any"
reveal_type((lambda s, *k, i: i)(i=0, s='x')) # N: Revealed type is "Any"
reveal_type((lambda s, i, **k: i)(i=0, s='x')) # N: Revealed type is "Any"
[builtins fixtures/dict.pyi]

[case testInferLambdaAsGenericFunctionArgument]
from typing import TypeVar, List, Any, Callable
t = TypeVar('t')
class A:
  x = None # type: A
def f(a: List[t], fn: Callable[[t], Any]) -> None: pass
list_a = [] # type: List[A]
f(list_a, lambda a: a.x)
[builtins fixtures/list.pyi]

[case testLambdaWithoutContext]
reveal_type(lambda x: x)  # N: Revealed type is "def (x: Any) -> Any"
reveal_type(lambda x: 1)  # N: Revealed type is "def (x: Any) -> Literal[1]?"

[case testLambdaContextVararg]
from typing import Callable
def f(t: Callable[[str], str]) -> str: ''
f(lambda *_: '')
[builtins fixtures/tuple.pyi]

[case testInvalidContextForLambda]
from typing import Callable
f = lambda x: A() # type: Callable[[], A]
f2 = lambda: A() # type: Callable[[A], A]
class A: pass
[out]
main:2: error: Cannot infer type of lambda
main:2: error: Incompatible types in assignment (expression has type "Callable[[Any], A]", variable has type "Callable[[], A]")
main:3: error: Cannot infer type of lambda
main:3: error: Incompatible types in assignment (expression has type "Callable[[], A]", variable has type "Callable[[A], A]")

[case testEllipsisContextForLambda]
from typing import Callable
f1 = lambda x: 1 # type: Callable[..., int]
f2 = lambda: 1 # type: Callable[..., int]
f3 = lambda *args, **kwargs: 1 # type: Callable[..., int]
f4 = lambda x: x # type: Callable[..., int]
g = lambda x: 1 # type: Callable[..., str]
[builtins fixtures/dict.pyi]
[out]
main:6: error: Incompatible types in assignment (expression has type "Callable[[Any], int]", variable has type "Callable[..., str]")
main:6: error: Incompatible return value type (got "int", expected "str")

[case testEllipsisContextForLambda2]
from typing import TypeVar, Callable
T = TypeVar('T')
def foo(arg: Callable[..., T]) -> None: pass
foo(lambda: 1)

[case testLambdaNoneInContext]
# flags: --no-strict-optional
from typing import Callable
def f(x: Callable[[], None]) -> None: pass
def g(x: Callable[[], int]) -> None: pass
f(lambda: None)
g(lambda: None)

[case testIsinstanceInInferredLambda]
from typing import TypeVar, Callable, Optional
T = TypeVar('T')
S = TypeVar('S')
class A: pass
class B(A): pass
class C(A): pass
def f(func: Callable[[T], S], *z: T, r: Optional[S] = None) -> S: pass
reveal_type(f(lambda x: 0 if isinstance(x, B) else 1))  # N: Revealed type is "Union[Literal[0]?, Literal[1]?]"
f(lambda x: 0 if isinstance(x, B) else 1, A())() # E: "int" not callable
f(lambda x: x if isinstance(x, B) else B(), A(), r=B())() # E: "B" not callable
f(
    lambda x:  # E: Argument 1 to "f" has incompatible type "Callable[[A], A]"; expected "Callable[[A], B]"
        B() if isinstance(x, B) else x, # E: Incompatible return value type (got "A", expected "B")
    A(), r=B())
[builtins fixtures/isinstance.pyi]

[case testLambdaWithFastContainerType]
from collections.abc import Callable
from typing import Never, TypeVar

T = TypeVar("T")

def f(a: Callable[[], T]) -> None: ...

def foo(x: str) -> Never: ...

f(lambda: [foo(0)])  # E: Argument 1 to "foo" has incompatible type "int"; expected "str"
f(lambda: {"x": foo(0)})  # E: Argument 1 to "foo" has incompatible type "int"; expected "str"
[builtins fixtures/tuple.pyi]


-- Overloads + generic functions
-- -----------------------------


[case testMapWithOverloadedFunc]
from foo import *
[file foo.pyi]
from typing import TypeVar, Callable, List, overload, Any
t = TypeVar('t')
s = TypeVar('s')
def map(f: Callable[[t], s], seq: List[t]) -> List[s]: pass

@overload
def g(o: object) -> 'B': pass
@overload
def g(o: 'A', x: Any = None) -> 'B': pass

class A: pass
class B: pass

m = map(g, [A()])
b = m # type: List[B]
a = m # type: List[A] # E: Incompatible types in assignment (expression has type "list[B]", variable has type "list[A]")
[builtins fixtures/list.pyi]


-- Boolean operators
-- -----------------


[case testOrOperationInferredFromContext]
from typing import List
class A: pass
class B: pass
class C(B): pass
a: List[A]
b: List[B]
c: List[C]
if int():
    a = a or []
if int():
    a = [] or a
if int():
    b = b or [C()]
if int():
    a = a or b # E: Incompatible types in assignment (expression has type "Union[list[A], list[B]]", variable has type "list[A]")
if int():
    b = b or c # E: Incompatible types in assignment (expression has type "Union[list[B], list[C]]", variable has type "list[B]")
[builtins fixtures/list.pyi]


-- Special cases
-- -------------


[case testSomeTypeVarsInferredFromContext]
from typing import List, TypeVar
t = TypeVar('t')
s = TypeVar('s')
# Some type variables can be inferred using context, but not all of them.
a: List[A]
def f(a: s, b: t) -> List[s]: pass
class A: pass
class B: pass
if int():
    a = f(A(), B())
if int():
    a = f(B(), B()) # E: Argument 1 to "f" has incompatible type "B"; expected "A"
[builtins fixtures/list.pyi]

[case testSomeTypeVarsInferredFromContext2]
from typing import List, TypeVar
s = TypeVar('s')
t = TypeVar('t')
def f(a: s, b: t) -> List[s]: pass
class A: pass
class B: pass
# Like testSomeTypeVarsInferredFromContext, but tvars in different order.
a: List[A]
if int():
    a = f(A(), B())
if int():
    a = f(B(), B()) # E: Argument 1 to "f" has incompatible type "B"; expected "A"
[builtins fixtures/list.pyi]

[case testLambdaInListAndHigherOrderFunction]
from typing import TypeVar, Callable, List
t = TypeVar('t')
s = TypeVar('s')
def map(f: List[Callable[[t], s]], a: List[t]) -> List[s]: pass
class A: pass
map(
  [lambda x: x], [])
[builtins fixtures/list.pyi]
[out]

[case testChainedAssignmentInferenceContexts]
from typing import List
i: List[int]
s: List[str]
if int():
    i = i = []
if int():
    i = s = [] # E: Incompatible types in assignment (expression has type "list[str]", variable has type "list[int]")
[builtins fixtures/list.pyi]

[case testContextForAttributeDeclaredInInit]
from typing import List
class A:
  def __init__(self):
    self.x = [] # type: List[int]  # N: By default the bodies of untyped functions are not checked, consider using --check-untyped-defs
a = A()
a.x = []
a.x = [1]
a.x = [''] # E: List item 0 has incompatible type "str"; expected "int"
[builtins fixtures/list.pyi]

[case testListMultiplyInContext]
from typing import List
a: List[int]
if int():
    a = [None] * 3  # E: List item 0 has incompatible type "None"; expected "int"
    a = [''] * 3  # E: List item 0 has incompatible type "str"; expected "int"
[builtins fixtures/list.pyi]

[case testUnionTypeContext]
from typing import Union, List, TypeVar
T = TypeVar('T')
def f(x: Union[List[T], str]) -> None: pass
f([1])
f('')
f(1) # E: Argument 1 to "f" has incompatible type "int"; expected "Union[list[Never], str]"
[builtins fixtures/isinstancelist.pyi]

[case testIgnoringInferenceContext]
from typing import TypeVar, List
T = TypeVar('T')
def f(x: List[T]) -> T: pass
def g(y: object) -> None: pass
a = [1]
g(f(a))
[builtins fixtures/list.pyi]

[case testStar2Context]
from typing import Any, Dict, Tuple, Iterable
def f1(iterable: Iterable[Tuple[str, Any]] = ()) -> None:
    f2(**dict(iterable))
def f2(iterable: Iterable[Tuple[str, Any]], **kw: Any) -> None:
    pass
[builtins fixtures/dict.pyi]
[out]

[case testInferenceInGenericFunction]
from typing import TypeVar, List
T = TypeVar('T')
def f(a: T) -> None:
    l = []  # type: List[T]
    l.append(a)
    l.append(1) # E: Argument 1 to "append" of "list" has incompatible type "int"; expected "T"
[builtins fixtures/list.pyi]
[out]

[case testInferenceInGenericClass]
from typing import TypeVar, Generic, List
S = TypeVar('S')
T = TypeVar('T')
class A(Generic[S]):
    def f(self, a: T, b: S) -> None:
        l = []  # type: List[T]
        l.append(a)
        l.append(b) # E: Argument 1 to "append" of "list" has incompatible type "S"; expected "T"
[builtins fixtures/list.pyi]
[out]

[case testLambdaInGenericFunction]
from typing import TypeVar, Callable
T = TypeVar('T')
S = TypeVar('S')
def f(a: T, b: S) -> None:
    c = lambda x: x  # type: Callable[[T], S]
[out]
main:5: error: Incompatible types in assignment (expression has type "Callable[[T], T]", variable has type "Callable[[T], S]")
main:5: error: Incompatible return value type (got "T", expected "S")

[case testLambdaInGenericClass]
from typing import TypeVar, Callable, Generic
T = TypeVar('T')
S = TypeVar('S')
class A(Generic[T]):
    def f(self, b: S) -> None:
        c = lambda x: x  # type: Callable[[T], S]
[out]
main:6: error: Incompatible types in assignment (expression has type "Callable[[T], T]", variable has type "Callable[[T], S]")
main:6: error: Incompatible return value type (got "T", expected "S")

[case testRevealTypeContext]
from typing import TypeVar, Callable, Generic
T = TypeVar('T')
class A(Generic[T]):
    pass
reveal_type(A()) # N: Revealed type is "__main__.A[Never]"
b = reveal_type(A())  # type: A[int] # N: Revealed type is "__main__.A[builtins.int]"

[case testUnionWithGenericTypeItemContext]
from typing import TypeVar, Union, List

T = TypeVar('T')

def f(x: Union[T, List[int]]) -> Union[T, List[int]]: pass
reveal_type(f(1)) # N: Revealed type is "Union[builtins.int, builtins.list[builtins.int]]"
reveal_type(f([])) # N: Revealed type is "builtins.list[builtins.int]"
reveal_type(f(None)) # N: Revealed type is "Union[None, builtins.list[builtins.int]]"
[builtins fixtures/list.pyi]

[case testUnionWithGenericTypeItemContextAndStrictOptional]
from typing import TypeVar, Union, List

T = TypeVar('T')

def f(x: Union[T, List[int]]) -> Union[T, List[int]]: pass
reveal_type(f(1)) # N: Revealed type is "Union[builtins.int, builtins.list[builtins.int]]"
reveal_type(f([])) # N: Revealed type is "builtins.list[builtins.int]"
reveal_type(f(None)) # N: Revealed type is "Union[None, builtins.list[builtins.int]]"
[builtins fixtures/list.pyi]

[case testUnionWithGenericTypeItemContextInMethod]
from typing import TypeVar, Union, List, Generic

T = TypeVar('T')
S = TypeVar('S')

class C(Generic[T]):
    def f(self, x: Union[T, S]) -> Union[T, S]: pass

c = C[List[int]]()
reveal_type(c.f('')) # N: Revealed type is "Union[builtins.list[builtins.int], builtins.str]"
reveal_type(c.f([1])) # N: Revealed type is "builtins.list[builtins.int]"
reveal_type(c.f([])) # N: Revealed type is "builtins.list[builtins.int]"
reveal_type(c.f(None)) # N: Revealed type is "Union[builtins.list[builtins.int], None]"
[builtins fixtures/list.pyi]

[case testGenericMethodCalledInGenericContext]
from typing import TypeVar, Generic

_KT = TypeVar('_KT')
_VT = TypeVar('_VT')
_T = TypeVar('_T')

class M(Generic[_KT, _VT]):
    def get(self, k: _KT, default: _T) -> _T: ...

def f(d: M[_KT, _VT], k: _KT) -> _VT:
    return d.get(k, None)  # E: Incompatible return value type (got "None", expected "_VT")

[case testGenericMethodCalledInGenericContext2]
from typing import TypeVar, Generic, Union

_KT = TypeVar('_KT')
_VT = TypeVar('_VT')
_T = TypeVar('_T')

class M(Generic[_KT, _VT]):
    def get(self, k: _KT, default: _T) -> Union[_VT, _T]: ...

def f(d: M[_KT, _VT], k: _KT) -> Union[_VT, None]:
    return d.get(k, None)

[case testLambdaDeferredCrash]
from typing import Callable

class C:
    def f(self) -> None:
        g: Callable[[], int] = lambda: 1 or self.x
        self.x = int()

[case testInferTypeVariableFromTwoGenericTypes1]
from typing import TypeVar, List, Sequence

T = TypeVar('T')

class C: ...
class D(C): ...

def f(x: Sequence[T], y: Sequence[T]) -> List[T]: ...

reveal_type(f([C()], [D()])) # N: Revealed type is "builtins.list[__main__.C]"
[builtins fixtures/list.pyi]

[case testInferTypeVariableFromTwoGenericTypes2]
from typing import TypeVar, List

T = TypeVar('T')

class C: ...
class D(C): ...

def f(x: List[T], y: List[T]) -> List[T]: ...

f([C()], [D()]) # E: Cannot infer value of type parameter "T" of "f"
[builtins fixtures/list.pyi]

[case testInferTypeVariableFromTwoGenericTypes3]
from typing import Generic, TypeVar

T = TypeVar('T')
T_contra = TypeVar('T_contra', contravariant=True)

class A(Generic[T_contra]): pass
class B(A[T]): pass

class C: ...
class D(C): ...

def f(x: A[T], y: A[T]) -> B[T]: ...

c: B[C]
d: B[D]
reveal_type(f(c, d)) # N: Revealed type is "__main__.B[__main__.D]"

[case testInferTypeVariableFromTwoGenericTypes4]
from typing import Generic, TypeVar, Callable, List

T = TypeVar('T')
T_contra = TypeVar('T_contra', contravariant=True)

class A(Generic[T_contra]): pass
class B(A[T_contra]): pass

class C: ...
class D(C): ...

def f(x: Callable[[B[T]], None],
      y: Callable[[B[T]], None]) -> List[T]: ...

def gc(x: A[C]) -> None: pass  # B[C]
def gd(x: A[D]) -> None: pass  # B[C]

reveal_type(f(gc, gd)) # N: Revealed type is "builtins.list[__main__.C]"
[builtins fixtures/list.pyi]

[case testWideOuterContextSubClassBound]
from typing import TypeVar

class A: ...
class B(A): ...

T = TypeVar('T', bound=B)
def f(x: T) -> T: ...
def outer(x: A) -> None: ...

outer(f(B()))
x: A = f(B())

[case testWideOuterContextSubClassBoundGenericReturn]
from typing import TypeVar, Iterable, List

class A: ...
class B(A): ...

T = TypeVar('T', bound=B)
def f(x: T) -> List[T]: ...
def outer(x: Iterable[A]) -> None: ...

outer(f(B()))
x: Iterable[A] = f(B())
[builtins fixtures/list.pyi]

[case testWideOuterContextSubClassValues]
from typing import TypeVar

class A: ...
class B(A): ...

T = TypeVar('T', B, int)
def f(x: T) -> T: ...
def outer(x: A) -> None: ...

outer(f(B()))
x: A = f(B())

[case testWideOuterContextSubClassValuesGenericReturn]
from typing import TypeVar, Iterable, List

class A: ...
class B(A): ...

T = TypeVar('T', B, int)
def f(x: T) -> List[T]: ...
def outer(x: Iterable[A]) -> None: ...

outer(f(B()))
x: Iterable[A] = f(B())
[builtins fixtures/list.pyi]

[case testWideOuterContextSubclassBoundGeneric]
from typing import TypeVar, Generic

S = TypeVar('S')
class A(Generic[S]): ...
class B(A[S]): ...

T = TypeVar('T', bound=B[int])
def f(x: T) -> T: ...
def outer(x: A[int]) -> None: ...

y: B[int]
outer(f(y))
x: A[int] = f(y)

[case testWideOuterContextSubclassBoundGenericCovariant]
from typing import TypeVar, Generic

S_co = TypeVar('S_co', covariant=True)
class A(Generic[S_co]): ...
class B(A[S_co]): ...

T = TypeVar('T', bound=B[int])
def f(x: T) -> T: ...
def outer(x: A[int]) -> None: ...

y: B[int]
outer(f(y))
x: A[int] = f(y)

[case testWideOuterContextSubclassValuesGeneric]
from typing import TypeVar, Generic

S = TypeVar('S')
class A(Generic[S]): ...
class B(A[S]): ...

T = TypeVar('T', B[int], int)
def f(x: T) -> T: ...
def outer(x: A[int]) -> None: ...

y: B[int]
outer(f(y))
x: A[int] = f(y)

[case testWideOuterContextSubclassValuesGenericCovariant]
from typing import TypeVar, Generic

S_co = TypeVar('S_co', covariant=True)
class A(Generic[S_co]): ...
class B(A[S_co]): ...

T = TypeVar('T', B[int], int)
def f(x: T) -> T: ...
def outer(x: A[int]) -> None: ...

y: B[int]
outer(f(y))
x: A[int] = f(y)

[case testWideOuterContextUnionBound]
from typing import TypeVar, Union

class A: ...
class B: ...

T = TypeVar('T', bound=B)
def f(x: T) -> T: ...
def outer(x: Union[A, B]) -> None: ...

outer(f(B()))
x: Union[A, B] = f(B())

[case testWideOuterContextUnionBoundGenericReturn]
from typing import TypeVar, Union, Iterable, List

class A: ...
class B: ...

T = TypeVar('T', bound=B)
def f(x: T) -> List[T]: ...
def outer(x: Iterable[Union[A, B]]) -> None: ...

outer(f(B()))
x: Iterable[Union[A, B]] = f(B())
[builtins fixtures/list.pyi]

[case testWideOuterContextUnionValues]
from typing import TypeVar, Union

class A: ...
class B: ...

T = TypeVar('T', B, int)
def f(x: T) -> T: ...
def outer(x: Union[A, B]) -> None: ...

outer(f(B()))
x: Union[A, B] = f(B())

[case testWideOuterContextUnionValuesGenericReturn]
from typing import TypeVar, Union, Iterable, List

class A: ...
class B: ...

T = TypeVar('T', B, int)
def f(x: T) -> List[T]: ...
def outer(x: Iterable[Union[A, B]]) -> None: ...

outer(f(B()))
x: Iterable[Union[A, B]] = f(B())
[builtins fixtures/list.pyi]

[case testWideOuterContextOptional]
from typing import Optional, Type, TypeVar

class Custom:
    pass

T = TypeVar('T', bound=Custom)

def a(x: T) -> Optional[T]: ...

def b(x: T) -> Optional[T]:
    return a(x)

[case testWideOuterContextOptionalGenericReturn]
from typing import Optional, Type, TypeVar, Iterable

class Custom:
    pass

T = TypeVar('T', bound=Custom)

def a(x: T) -> Iterable[Optional[T]]: ...

def b(x: T) -> Iterable[Optional[T]]:
    return a(x)

[case testWideOuterContextOptionalMethod]
from typing import Optional, Type, TypeVar

class A: pass
class B: pass

T = TypeVar('T', A, B)
class C:
    def meth_a(self) -> Optional[A]:
        return self.meth(A)

    def meth(self, cls: Type[T]) -> Optional[T]: ...

[case testWideOuterContextValuesOverlapping]
from typing import TypeVar, List

class A:
    pass
class B(A):
    pass
class C:
    pass

T = TypeVar('T', A, B, C)
def foo(xs: List[T]) -> T: ...

S = TypeVar('S', B, C)
def bar(xs: List[S]) -> S:
    foo(xs)
    return xs[0]
[builtins fixtures/list.pyi]

[case testWideOuterContextOptionalTypeVarReturn]
from typing import Callable, Iterable, List, Optional, TypeVar

class C:
    x: str

T = TypeVar('T')
def f(i: Iterable[T], c: Callable[[T], str]) -> Optional[T]: ...

def g(l: List[C], x: str) -> Optional[C]:
    def pred(c: C) -> str:
        return c.x
    return f(l, pred)
[builtins fixtures/list.pyi]

[case testWideOuterContextOptionalTypeVarReturnLambda]
from typing import Callable, Iterable, List, Optional, TypeVar

class C:
    x: str

T = TypeVar('T')
def f(i: Iterable[T], c: Callable[[T], str]) -> Optional[T]: ...

def g(l: List[C], x: str) -> Optional[C]:
    return f(l, lambda c: reveal_type(c).x)  # N: Revealed type is "__main__.C"
[builtins fixtures/list.pyi]

[case testPartialTypeContextWithTwoLambdas]
from typing import Any, Generic, TypeVar, Callable

def int_to_any(x: int) -> Any: ...
def any_to_int(x: Any) -> int: ...
def any_to_str(x: Any) -> str: ...

T = TypeVar("T")
class W(Generic[T]):
    def __init__(
        self, serialize: Callable[[T], Any], deserialize: Callable[[Any], T]
    ) -> None:
        ...
reveal_type(W(lambda x: int_to_any(x), lambda x: any_to_int(x)))  # N: Revealed type is "__main__.W[builtins.int]"
W(
    lambda x: int_to_any(x),  # E: Argument 1 to "int_to_any" has incompatible type "str"; expected "int"
    lambda x: any_to_str(x)
)

[case testWideOuterContextEmpty]
from typing import List, TypeVar

T = TypeVar('T', bound=int)
def f(x: List[T]) -> T: ...

# mypy infers List[Never] here, and Never is a subtype of str
y: str = f([])
[builtins fixtures/list.pyi]

[case testWideOuterContextEmptyError]
from typing import List, TypeVar

T = TypeVar('T', bound=int)
def f(x: List[T]) -> List[T]: ...

y: List[str] = f([])
[builtins fixtures/list.pyi]

[case testWideOuterContextNoArgs]
from typing import TypeVar, Optional

T = TypeVar('T', bound=int)
def f(x: Optional[T] = None) -> T: ...

y: str = f()

[case testWideOuterContextNoArgsError]
from typing import TypeVar, Optional, List

T = TypeVar('T', bound=int)
def f(x: Optional[T] = None) -> List[T]: ...

y: List[str] = f()
[builtins fixtures/list.pyi]

[case testUseCovariantGenericOuterContext]
from typing import TypeVar, Callable, Tuple

T = TypeVar('T')

def f(x: Callable[..., T]) -> T:
    return x()

x: Tuple[str, ...] = f(tuple)
[builtins fixtures/tuple.pyi]
[out]

[case testUseCovariantGenericOuterContextUserDefined]
from typing import TypeVar, Callable, Generic

T_co = TypeVar('T_co', covariant=True)
T = TypeVar('T')

class G(Generic[T_co]): ...

def f(x: Callable[..., T]) -> T:
    return x()

x: G[str] = f(G)
[out]

[case testConditionalExpressionWithEmptyListAndUnionWithAny]
from typing import Union, List, Any

def f(x: Union[List[str], Any]) -> None:
    a = x if x else []
    reveal_type(a)  # N: Revealed type is "Union[builtins.list[builtins.str], Any, builtins.list[Union[builtins.str, Any]]]"
[builtins fixtures/list.pyi]

[case testConditionalExpressionWithEmptyIteableAndUnionWithAny]
from typing import Union, Iterable, Any

def f(x: Union[Iterable[str], Any]) -> None:
    a = x if x else []
    reveal_type(a)  # N: Revealed type is "Union[typing.Iterable[builtins.str], Any, builtins.list[Union[builtins.str, Any]]]"
[builtins fixtures/list.pyi]

[case testInferMultipleAnyUnionCovariant]
from typing import Any, Mapping, Sequence, Union

def foo(x: Union[Mapping[Any, Any], Mapping[Any, Sequence[Any]]]) -> None:
    ...
foo({1: 2})
[builtins fixtures/dict.pyi]

[case testInferMultipleAnyUnionInvariant]
from typing import Any, Dict, Sequence, Union

def foo(x: Union[Dict[Any, Any], Dict[Any, Sequence[Any]]]) -> None:
    ...
foo({1: 2})
[builtins fixtures/dict.pyi]

[case testInferMultipleAnyUnionDifferentVariance]
from typing import Any, Dict, Mapping, Sequence, Union

def foo(x: Union[Dict[Any, Any], Mapping[Any, Sequence[Any]]]) -> None:
    ...
foo({1: 2})

def bar(x: Union[Mapping[Any, Any], Dict[Any, Sequence[Any]]]) -> None:
    ...
bar({1: 2})
[builtins fixtures/dict.pyi]

[case testOptionalTypeNarrowedByGenericCall]
from typing import Dict, Optional

d: Dict[str, str] = {}

def foo(arg: Optional[str] = None) -> None:
    if arg is None:
        arg = d.get("a", "b")
    reveal_type(arg)  # N: Revealed type is "builtins.str"
[builtins fixtures/dict.pyi]

[case testOptionalTypeNarrowedByGenericCall2]
from typing import Dict, Optional

d: Dict[str, str] = {}
x: Optional[str]
if x:
    reveal_type(x)  # N: Revealed type is "builtins.str"
    x = d.get(x, x)
    reveal_type(x)  # N: Revealed type is "builtins.str"
[builtins fixtures/dict.pyi]

[case testOptionalTypeNarrowedByGenericCall3]
from typing import Generic, TypeVar, Union

T = TypeVar("T")
def bar(arg: Union[str, T]) -> Union[str, T]: ...

def foo(arg: Union[str, int]) -> None:
    if isinstance(arg, int):
        arg = bar("default")
    reveal_type(arg)  # N: Revealed type is "builtins.str"
[builtins fixtures/isinstance.pyi]

[case testOptionalTypeNarrowedByGenericCall4]
from typing import Optional, List, Generic, TypeVar

T = TypeVar("T", covariant=True)
class C(Generic[T]): ...

x: Optional[C[int]] = None
y = x = C()
reveal_type(y)  # N: Revealed type is "__main__.C[builtins.int]"

[case testOptionalTypeNarrowedByGenericCall5]
from typing import Any, Tuple, Union

i: Union[Tuple[Any, ...], int]
b: Any
i = i if isinstance(i, int) else b
reveal_type(i)  # N: Revealed type is "Union[Any, builtins.int]"
[builtins fixtures/isinstance.pyi]

[case testLambdaInferenceUsesNarrowedTypes]
from typing import Optional, Callable

def f1(key: Callable[[], str]) -> None: ...
def f2(key: object) -> None: ...

def g(b: Optional[str]) -> None:
    if b:
        f1(lambda: reveal_type(b))  # N: Revealed type is "builtins.str"
        z: Callable[[], str] = lambda: reveal_type(b)  # N: Revealed type is "builtins.str"
        f2(lambda: reveal_type(b))  # N: Revealed type is "builtins.str"
        lambda: reveal_type(b)  # N: Revealed type is "builtins.str"

[case testInferenceContextReturningTypeVarUnion]
from collections.abc import Callable, Iterable
from typing import TypeVar, Union

_T1 = TypeVar("_T1")
_T2 = TypeVar("_T2")

def mymin(
    iterable: Iterable[_T1], /, *, key: Callable[[_T1], int], default: _T2
) -> Union[_T1, _T2]: ...

def check(paths: Iterable[str], key: Callable[[str], int]) -> Union[str, None]:
    return mymin(paths, key=key, default=None)
[builtins fixtures/tuple.pyi]

[case testBinaryOpInferenceContext]
from typing import Literal, TypeVar

T = TypeVar("T")

def identity(x: T) -> T:
    return x

def check1(use: bool, val: str) -> "str | Literal[True]":
    return use or identity(val)

def check2(use: bool, val: str) -> "str | bool":
    return use or identity(val)

def check3(use: bool, val: str) -> "str | Literal[False]":
    return use and identity(val)

def check4(use: bool, val: str) -> "str | bool":
    return use and identity(val)
[builtins fixtures/tuple.pyi]

[case testDictAnyOrLiteralInContext]
from typing import Union, Optional, Any

def f(x: dict[str, Union[str, None, int]]) -> None:
    pass

def g(x: Optional[dict[str, Any]], s: Optional[str]) -> None:
    f(x or {'x': s})
[builtins fixtures/dict.pyi]

[case testReturnFallbackInferenceTuple]
from typing import TypeVar, Union

T = TypeVar("T")
def foo(x: list[T]) -> tuple[T, ...]: ...

def bar(x: list[int]) -> tuple[Union[str, int], ...]:
    return foo(x)

def bar2(x: list[int]) -> tuple[Union[str, int], ...]:
    y = foo(x)
    return y
[builtins fixtures/tuple.pyi]

[case testReturnFallbackInferenceUnion]
from typing import Generic, TypeVar, Union

T = TypeVar("T")

class Cls(Generic[T]):
    pass

def inner(c: Cls[T]) -> Union[T, int]:
    return 1

def outer(c: Cls[T]) -> Union[T, int]:
    return inner(c)

[case testReturnFallbackInferenceAsync]
from typing import Generic, TypeVar, Optional

T = TypeVar("T")

class Cls(Generic[T]):
    pass

async def inner(c: Cls[T]) -> Optional[T]:
    return None

async def outer(c: Cls[T]) -> Optional[T]:
    return await inner(c)
[builtins fixtures/async_await.pyi]
[typing fixtures/typing-async.pyi]