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 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683
|
-- This test file checks Enum
[case testEnumBasics]
from enum import Enum
class Medal(Enum):
gold = 1
silver = 2
bronze = 3
reveal_type(Medal.bronze) # N: Revealed type is "Literal[__main__.Medal.bronze]?"
m = Medal.gold
if int():
m = 1 # E: Incompatible types in assignment (expression has type "int", variable has type "Medal")
[builtins fixtures/enum.pyi]
-- Creation from Enum call
-- -----------------------
[case testEnumCreatedFromStringLiteral]
from enum import Enum
from typing import Literal
x: Literal['ANT BEE CAT DOG'] = 'ANT BEE CAT DOG'
Animal = Enum('Animal', x)
reveal_type(Animal.ANT) # N: Revealed type is "Literal[__main__.Animal.ANT]?"
reveal_type(Animal.BEE) # N: Revealed type is "Literal[__main__.Animal.BEE]?"
reveal_type(Animal.CAT) # N: Revealed type is "Literal[__main__.Animal.CAT]?"
reveal_type(Animal.DOG) # N: Revealed type is "Literal[__main__.Animal.DOG]?"
[builtins fixtures/tuple.pyi]
[case testEnumCreatedFromFinalValue]
from enum import Enum
from typing import Final
x: Final['str'] = 'ANT BEE CAT DOG'
Animal = Enum('Animal', x)
reveal_type(Animal.ANT) # N: Revealed type is "Literal[__main__.Animal.ANT]?"
reveal_type(Animal.BEE) # N: Revealed type is "Literal[__main__.Animal.BEE]?"
reveal_type(Animal.CAT) # N: Revealed type is "Literal[__main__.Animal.CAT]?"
reveal_type(Animal.DOG) # N: Revealed type is "Literal[__main__.Animal.DOG]?"
[builtins fixtures/tuple.pyi]
-- Creation from EnumMeta
-- ----------------------
[case testEnumFromEnumMetaBasics]
from enum import EnumMeta
class Medal(metaclass=EnumMeta):
gold = 1
silver = "hello"
bronze = None
# Without __init__ the definition fails at runtime, but we want to verify that mypy
# uses `enum.EnumMeta` and not `enum.Enum` as the definition of what is enum.
def __init__(self, *args): pass
reveal_type(Medal.bronze) # N: Revealed type is "Literal[__main__.Medal.bronze]?"
m = Medal.gold
if int():
m = 1 # E: Incompatible types in assignment (expression has type "int", variable has type "Medal")
[builtins fixtures/tuple.pyi]
[case testEnumFromEnumMetaSubclass]
from enum import EnumMeta
class Achievement(metaclass=EnumMeta): pass
class Medal(Achievement):
gold = 1
silver = "hello"
bronze = None
# See comment in testEnumFromEnumMetaBasics
def __init__(self, *args): pass
reveal_type(Medal.bronze) # N: Revealed type is "Literal[__main__.Medal.bronze]?"
m = Medal.gold
if int():
m = 1 # E: Incompatible types in assignment (expression has type "int", variable has type "Medal")
[builtins fixtures/tuple.pyi]
[case testEnumFromEnumMetaGeneric]
from enum import EnumMeta
from typing import Generic, TypeVar
T = TypeVar("T")
class Medal(Generic[T], metaclass=EnumMeta): # E: Enum class cannot be generic
q = None
[builtins fixtures/enum.pyi]
[case testEnumNameAndValue]
from enum import Enum
class Truth(Enum):
true = True
false = False
x = ''
x = Truth.true.name
reveal_type(Truth.true.name) # N: Revealed type is "Literal['true']?"
reveal_type(Truth.false.value) # N: Revealed type is "Literal[False]?"
[builtins fixtures/bool.pyi]
[case testEnumValueExtended]
from enum import Enum
class Truth(Enum):
true = True
false = False
def infer_truth(truth: Truth) -> None:
reveal_type(truth.value) # N: Revealed type is "Union[Literal[True]?, Literal[False]?]"
[builtins fixtures/bool.pyi]
[case testEnumValueAllAuto]
from enum import Enum, auto
class Truth(Enum):
true = auto()
false = auto()
def infer_truth(truth: Truth) -> None:
reveal_type(truth.value) # N: Revealed type is "builtins.int"
[builtins fixtures/primitives.pyi]
[case testEnumValueSomeAuto]
from enum import Enum, auto
class Truth(Enum):
true = 8675309
false = auto()
def infer_truth(truth: Truth) -> None:
reveal_type(truth.value) # N: Revealed type is "builtins.int"
[builtins fixtures/primitives.pyi]
[case testEnumValueExtraMethods]
from enum import Enum
class Truth(Enum):
true = True
false = False
def foo(self) -> str:
return 'bar'
def infer_truth(truth: Truth) -> None:
reveal_type(truth.value) # N: Revealed type is "Union[Literal[True]?, Literal[False]?]"
[builtins fixtures/bool.pyi]
[case testEnumValueCustomAuto]
from enum import Enum, auto
class AutoName(Enum):
# In `typeshed`, this is a staticmethod and has more arguments,
# but I have lied a bit to keep the test stubs lean.
def _generate_next_value_(self) -> str:
return "name"
class Truth(AutoName):
true = auto()
false = auto()
def infer_truth(truth: Truth) -> None:
reveal_type(truth.value) # N: Revealed type is "builtins.str"
[builtins fixtures/primitives.pyi]
[case testEnumValueInhomogeneous]
from enum import Enum
class Truth(Enum):
true = 'True'
false = 0
def cannot_infer_truth(truth: Truth) -> None:
reveal_type(truth.value) # N: Revealed type is "Any"
[builtins fixtures/bool.pyi]
[case testEnumValueSameType]
from enum import Enum
def newbool() -> bool:
...
class Truth(Enum):
true = newbool()
false = newbool()
def infer_truth(truth: Truth) -> None:
reveal_type(truth.value) # N: Revealed type is "builtins.bool"
[builtins fixtures/bool.pyi]
[case testEnumTruthyness]
# mypy: warn-unreachable
import enum
from typing import Literal
class E(enum.Enum):
zero = 0
one = 1
def print(s: str) -> None: ...
if E.zero:
print("zero is true")
if not E.zero:
print("zero is false") # E: Statement is unreachable
if E.one:
print("one is true")
if not E.one:
print("one is false") # E: Statement is unreachable
def main(zero: Literal[E.zero], one: Literal[E.one]) -> None:
if zero:
print("zero is true")
if not zero:
print("zero is false") # E: Statement is unreachable
if one:
print("one is true")
if not one:
print("one is false") # E: Statement is unreachable
[builtins fixtures/tuple.pyi]
[case testEnumTruthynessCustomDunderBool]
# mypy: warn-unreachable
import enum
from typing import Literal
class E(enum.Enum):
zero = 0
one = 1
def __bool__(self) -> Literal[False]:
return False
def print(s: str) -> None: ...
if E.zero:
print("zero is true") # E: Statement is unreachable
if not E.zero:
print("zero is false")
if E.one:
print("one is true") # E: Statement is unreachable
if not E.one:
print("one is false")
def main(zero: Literal[E.zero], one: Literal[E.one]) -> None:
if zero:
print("zero is true") # E: Statement is unreachable
if not zero:
print("zero is false")
if one:
print("one is true") # E: Statement is unreachable
if not one:
print("one is false")
[builtins fixtures/enum.pyi]
[case testEnumTruthynessStrEnum]
# mypy: warn-unreachable
import enum
from typing import Literal
class E(enum.StrEnum):
empty = ""
not_empty = "asdf"
def print(s: str) -> None: ...
if E.empty:
print("empty is true")
if not E.empty:
print("empty is false")
if E.not_empty:
print("not_empty is true")
if not E.not_empty:
print("not_empty is false")
def main(empty: Literal[E.empty], not_empty: Literal[E.not_empty]) -> None:
if empty:
print("empty is true")
if not empty:
print("empty is false")
if not_empty:
print("not_empty is true")
if not not_empty:
print("not_empty is false")
[builtins fixtures/enum.pyi]
[case testEnumUnique]
import enum
@enum.unique
class E(enum.Enum):
x = 1
y = 1 # NOTE: This duplicate value is not detected by mypy at the moment
x = 1
x = E.x
[builtins fixtures/enum.pyi]
[out]
main:7: error: Incompatible types in assignment (expression has type "E", variable has type "int")
[case testIntEnum_assignToIntVariable]
from enum import IntEnum
class N(IntEnum):
x = 1
y = 1
n = 1
if int():
n = N.x # Subclass of int, so it's okay
s = ''
if int():
s = N.y # E: Incompatible types in assignment (expression has type "N", variable has type "str")
[builtins fixtures/enum.pyi]
[case testIntEnum_functionTakingIntEnum]
from enum import IntEnum
class SomeIntEnum(IntEnum):
x = 1
def takes_some_int_enum(n: SomeIntEnum):
pass
takes_some_int_enum(SomeIntEnum.x)
takes_some_int_enum(1) # Error
takes_some_int_enum(SomeIntEnum(1)) # How to deal with the above
[builtins fixtures/enum.pyi]
[out]
main:7: error: Argument 1 to "takes_some_int_enum" has incompatible type "int"; expected "SomeIntEnum"
[case testIntEnum_functionTakingInt]
from enum import IntEnum
class SomeIntEnum(IntEnum):
x = 1
def takes_int(i: int):
pass
takes_int(SomeIntEnum.x)
takes_int(2)
[builtins fixtures/enum.pyi]
[case testIntEnum_functionReturningIntEnum]
from enum import IntEnum
class SomeIntEnum(IntEnum):
x = 1
def returns_some_int_enum() -> SomeIntEnum:
return SomeIntEnum.x
an_int = 1
an_int = returns_some_int_enum()
an_enum = SomeIntEnum.x
an_enum = returns_some_int_enum()
[builtins fixtures/enum.pyi]
[out]
[case testStrEnumCreation]
# flags: --python-version 3.11
from enum import StrEnum
class MyStrEnum(StrEnum):
x = 'x'
y = 'y'
reveal_type(MyStrEnum.x) # N: Revealed type is "Literal[__main__.MyStrEnum.x]?"
reveal_type(MyStrEnum.x.value) # N: Revealed type is "Literal['x']?"
reveal_type(MyStrEnum.y) # N: Revealed type is "Literal[__main__.MyStrEnum.y]?"
reveal_type(MyStrEnum.y.value) # N: Revealed type is "Literal['y']?"
[builtins fixtures/enum.pyi]
[out]
[case testEnumMethods]
from enum import Enum
class Color(Enum):
red = 1
green = 2
def m(self, x: int): pass
@staticmethod
def m2(x: int): pass
Color.red.m('')
Color.m2('')
[builtins fixtures/staticmethod.pyi]
[out]
main:11: error: Argument 1 to "m" of "Color" has incompatible type "str"; expected "int"
main:12: error: Argument 1 to "m2" of "Color" has incompatible type "str"; expected "int"
[case testIntEnum_ExtendedIntEnum_functionTakingExtendedIntEnum]
from enum import IntEnum
class ExtendedIntEnum(IntEnum):
pass
class SomeExtIntEnum(ExtendedIntEnum):
x = 1
def takes_int(i: int):
pass
takes_int(SomeExtIntEnum.x)
def takes_some_ext_int_enum(s: SomeExtIntEnum):
pass
takes_some_ext_int_enum(SomeExtIntEnum.x)
[builtins fixtures/enum.pyi]
[case testNamedTupleEnum]
from typing import NamedTuple
from enum import Enum
N = NamedTuple('N', [('bar', int)])
class E(N, Enum):
X = N(1)
def f(x: E) -> None: pass
f(E.X)
[builtins fixtures/tuple.pyi]
[case testEnumCall]
from enum import IntEnum
class E(IntEnum):
a = 1
x: int
reveal_type(E(x))
[builtins fixtures/tuple.pyi]
[out]
main:5: note: Revealed type is "__main__.E"
[case testEnumIndex]
from enum import IntEnum
class E(IntEnum):
a = 1
s: str
reveal_type(E[s])
[builtins fixtures/enum.pyi]
[out]
main:5: note: Revealed type is "__main__.E"
[case testEnumIndexError]
from enum import IntEnum
class E(IntEnum):
a = 1
E[1] # E: Enum index should be a string (actual index type "int")
x = E[1] # E: Enum index should be a string (actual index type "int")
[builtins fixtures/enum.pyi]
[case testEnumIndexIsNotAnAlias]
from enum import Enum
class E(Enum):
a = 1
b = 2
reveal_type(E['a']) # N: Revealed type is "__main__.E"
E['a']
x = E['a']
reveal_type(x) # N: Revealed type is "__main__.E"
def get_member(name: str) -> E:
val = E[name]
return val
reveal_type(get_member('a')) # N: Revealed type is "__main__.E"
[builtins fixtures/enum.pyi]
[case testGenericEnum]
from enum import Enum
from typing import Generic, TypeVar
T = TypeVar('T')
class F(Generic[T], Enum): # E: Enum class cannot be generic
x: T
y: T
reveal_type(F[int].x) # N: Revealed type is "__main__.F[builtins.int]"
[builtins fixtures/enum.pyi]
[case testEnumFlag]
from enum import Flag
class C(Flag):
a = 1
b = 2
x = C.a
if int():
x = 1 # E: Incompatible types in assignment (expression has type "int", variable has type "C")
if int():
x = x | C.b
[builtins fixtures/enum.pyi]
[case testEnumIntFlag]
from enum import IntFlag
class C(IntFlag):
a = 1
b = 2
x = C.a
if int():
x = 1 # E: Incompatible types in assignment (expression has type "int", variable has type "C")
if int():
x = x | C.b
[builtins fixtures/enum.pyi]
[case testAnonymousEnum]
from enum import Enum
class A:
def f(self) -> None:
class E(Enum):
a = 1
self.x = E.a
a = A()
reveal_type(a.x)
[builtins fixtures/enum.pyi]
[out]
main:8: note: Revealed type is "__main__.E@4"
[case testEnumInClassBody]
from enum import Enum
class A:
class E(Enum):
a = 1
class B:
class E(Enum):
a = 1
x = A.E.a
y = B.E.a
if int():
x = y # E: Incompatible types in assignment (expression has type "__main__.B.E", variable has type "__main__.A.E")
[builtins fixtures/enum.pyi]
[case testFunctionalEnumString]
from enum import Enum, IntEnum
E = Enum('E', 'foo bar')
I = IntEnum('I', ' bar, baz ')
reveal_type(E.foo)
reveal_type(E.bar.value)
reveal_type(I.bar)
reveal_type(I.baz.value)
[builtins fixtures/enum.pyi]
[out]
main:4: note: Revealed type is "Literal[__main__.E.foo]?"
main:5: note: Revealed type is "Any"
main:6: note: Revealed type is "Literal[__main__.I.bar]?"
main:7: note: Revealed type is "builtins.int"
[case testFunctionalEnumListOfStrings]
from enum import Enum, IntEnum
E = Enum('E', ('foo', 'bar'))
F = IntEnum('F', ['bar', 'baz'])
reveal_type(E.foo)
reveal_type(F.baz)
[builtins fixtures/enum.pyi]
[out]
main:4: note: Revealed type is "Literal[__main__.E.foo]?"
main:5: note: Revealed type is "Literal[__main__.F.baz]?"
[case testFunctionalEnumListOfPairs]
from enum import Enum, IntEnum
E = Enum('E', [('foo', 1), ['bar', 2]])
F = IntEnum('F', (['bar', 1], ('baz', 2)))
reveal_type(E.foo)
reveal_type(F.baz)
reveal_type(E.foo.value)
reveal_type(F.bar.name)
[builtins fixtures/enum.pyi]
[out]
main:4: note: Revealed type is "Literal[__main__.E.foo]?"
main:5: note: Revealed type is "Literal[__main__.F.baz]?"
main:6: note: Revealed type is "Literal[1]?"
main:7: note: Revealed type is "Literal['bar']?"
[case testFunctionalEnumDict]
from enum import Enum, IntEnum
E = Enum('E', {'foo': 1, 'bar': 2})
F = IntEnum('F', {'bar': 1, 'baz': 2})
reveal_type(E.foo)
reveal_type(F.baz)
reveal_type(E.foo.value)
reveal_type(F.bar.name)
[builtins fixtures/enum.pyi]
[out]
main:4: note: Revealed type is "Literal[__main__.E.foo]?"
main:5: note: Revealed type is "Literal[__main__.F.baz]?"
main:6: note: Revealed type is "Literal[1]?"
main:7: note: Revealed type is "Literal['bar']?"
[case testEnumKeywordsArgs]
from enum import Enum, IntEnum
PictureSize = Enum('PictureSize', 'P0 P1 P2 P3 P4 P5 P6 P7 P8', type=str, module=__name__)
fake_enum1 = Enum('fake_enum1', ['a', 'b'])
fake_enum2 = Enum('fake_enum2', names=['a', 'b'])
fake_enum3 = Enum(value='fake_enum3', names=['a', 'b'])
fake_enum4 = Enum(value='fake_enum4', names=['a', 'b'] , module=__name__)
[builtins fixtures/enum.pyi]
[case testFunctionalEnumErrors]
from enum import Enum, IntEnum
A = Enum('A') # E: Too few arguments for Enum()
B = Enum('B', 42) # E: Second argument of Enum() must be string, tuple, list or dict literal for mypy to determine Enum members
C = Enum('C', 'a b', 'x', 'y', 'z', 'p', 'q') # E: Too many arguments for Enum()
D = Enum('D', foo) # E: Second argument of Enum() must be string, tuple, list or dict literal for mypy to determine Enum members \
# E: Name "foo" is not defined
bar = 'x y z'
E = Enum('E', bar) # E: Second argument of Enum() must be string, tuple, list or dict literal for mypy to determine Enum members
I = IntEnum('I') # E: Too few arguments for IntEnum()
J = IntEnum('I', 42) # E: Second argument of IntEnum() must be string, tuple, list or dict literal for mypy to determine Enum members
K = IntEnum('I', 'p q', 'x', 'y', 'z', 'p', 'q') # E: Too many arguments for IntEnum()
L = Enum('L', ' ') # E: Enum() needs at least one item
M = Enum('M', ()) # E: Enum() needs at least one item
N = IntEnum('M', []) # E: IntEnum() needs at least one item
P = Enum('P', [42]) # E: Enum() with tuple or list expects strings or (name, value) pairs
Q = Enum('Q', [('a', 42, 0)]) # E: Enum() with tuple or list expects strings or (name, value) pairs
R = IntEnum('R', [[0, 42]]) # E: IntEnum() with tuple or list expects strings or (name, value) pairs
S = Enum('S', {1: 1}) # E: Enum() with dict literal requires string literals
T = Enum('T', keyword='a b') # E: Unexpected keyword argument "keyword"
U = Enum('U', *['a']) # E: Unexpected arguments to Enum()
V = Enum('U', **{'a': 1}) # E: Unexpected arguments to Enum()
W = Enum('W', 'a b')
W.c # E: "type[W]" has no attribute "c"
X = Enum('Something', 'a b') # E: String argument 1 "Something" to enum.Enum(...) does not match variable name "X"
reveal_type(X.a) # N: Revealed type is "Literal[__main__.Something@23.a]?"
X.asdf # E: "type[Something@23]" has no attribute "asdf"
[builtins fixtures/tuple.pyi]
[typing fixtures/typing-medium.pyi]
[case testFunctionalEnumFlag]
from enum import Flag, IntFlag
A = Flag('A', 'x y')
B = IntFlag('B', 'a b')
reveal_type(A.x) # N: Revealed type is "Literal[__main__.A.x]?"
reveal_type(B.a) # N: Revealed type is "Literal[__main__.B.a]?"
reveal_type(A.x.name) # N: Revealed type is "Literal['x']?"
reveal_type(B.a.name) # N: Revealed type is "Literal['a']?"
reveal_type(A.x.value) # N: Revealed type is "builtins.int"
reveal_type(B.a.value) # N: Revealed type is "builtins.int"
[builtins fixtures/enum.pyi]
[case testAnonymousFunctionalEnum]
from enum import Enum
class A:
def f(self) -> None:
E = Enum('E', 'a b')
self.x = E.a
a = A()
reveal_type(a.x)
[builtins fixtures/enum.pyi]
[out]
main:7: note: Revealed type is "__main__.A.E@4"
[case testFunctionalEnumInClassBody]
from enum import Enum
class A:
E = Enum('E', 'a b')
class B:
E = Enum('E', 'a b')
x = A.E.a
y = B.E.a
if int():
x = y # E: Incompatible types in assignment (expression has type "__main__.B.E", variable has type "__main__.A.E")
[builtins fixtures/enum.pyi]
[case testFunctionalEnumProtocols]
from enum import IntEnum
Color = IntEnum('Color', 'red green blue')
reveal_type(Color['green']) # N: Revealed type is "__main__.Color"
for c in Color:
reveal_type(c) # N: Revealed type is "__main__.Color"
reveal_type(list(Color)) # N: Revealed type is "builtins.list[__main__.Color]"
[builtins fixtures/list.pyi]
[case testEnumWorkWithForward]
from enum import Enum
a: E = E.x # type: ignore[used-before-def]
class E(Enum):
x = 1
y = 2
[builtins fixtures/enum.pyi]
[out]
[case testEnumWorkWithForward2]
from enum import Enum
b: F
F = Enum('F', {'x': 1, 'y': 2})
def fn(x: F) -> None:
pass
fn(b)
[builtins fixtures/enum.pyi]
[out]
[case testFunctionalEnum]
# TODO: Needs to have enum34 stubs somehow
from enum import Enum
Eu = Enum(u'Eu', u'a b')
Eb = Enum(b'Eb', b'a b') # E: Enum() expects a string literal as the first argument
Gu = Enum(u'Gu', {u'a': 1})
Gb = Enum(b'Gb', {b'a': 1}) # E: Enum() expects a string literal as the first argument
Hu = Enum(u'Hu', [u'a'])
Hb = Enum(b'Hb', [b'a']) # E: Enum() expects a string literal as the first argument
Eu.a
Eb.a
Gu.a
Gb.a
Hu.a
Hb.a
[builtins fixtures/enum.pyi]
[out]
[case testEnumIncremental]
import m
reveal_type(m.E.a)
reveal_type(m.F.b)
[file m.py]
from enum import Enum
class E(Enum):
a = 1
b = 2
F = Enum('F', 'a b')
[builtins fixtures/enum.pyi]
[rechecked]
[stale]
[out1]
main:2: note: Revealed type is "Literal[m.E.a]?"
main:3: note: Revealed type is "Literal[m.F.b]?"
[out2]
main:2: note: Revealed type is "Literal[m.E.a]?"
main:3: note: Revealed type is "Literal[m.F.b]?"
[case testEnumAuto]
from enum import Enum, auto
class Test(Enum):
a = auto()
b = auto()
reveal_type(Test.a) # N: Revealed type is "Literal[__main__.Test.a]?"
[builtins fixtures/primitives.pyi]
[case testEnumAttributeAccessMatrix]
from enum import Enum, IntEnum, IntFlag, Flag, EnumMeta, auto
from typing import Literal
def is_x(val: Literal['x']) -> None: pass
A1 = Enum('A1', 'x')
class A2(Enum):
x = auto()
class A3(Enum):
x = 1
is_x(reveal_type(A1.x.name)) # N: Revealed type is "Literal['x']"
is_x(reveal_type(A1.x._name_)) # N: Revealed type is "Literal['x']"
reveal_type(A1.x.value) # N: Revealed type is "Any"
reveal_type(A1.x._value_) # N: Revealed type is "Any"
is_x(reveal_type(A2.x.name)) # N: Revealed type is "Literal['x']"
is_x(reveal_type(A2.x._name_)) # N: Revealed type is "Literal['x']"
reveal_type(A2.x.value) # N: Revealed type is "builtins.int"
reveal_type(A2.x._value_) # N: Revealed type is "builtins.int"
is_x(reveal_type(A3.x.name)) # N: Revealed type is "Literal['x']"
is_x(reveal_type(A3.x._name_)) # N: Revealed type is "Literal['x']"
reveal_type(A3.x.value) # N: Revealed type is "Literal[1]?"
reveal_type(A3.x._value_) # N: Revealed type is "Literal[1]?"
B1 = IntEnum('B1', 'x')
class B2(IntEnum):
x = auto()
class B3(IntEnum):
x = 1
is_x(reveal_type(B1.x.name)) # N: Revealed type is "Literal['x']"
is_x(reveal_type(B1.x._name_)) # N: Revealed type is "Literal['x']"
reveal_type(B1.x.value) # N: Revealed type is "builtins.int"
reveal_type(B1.x._value_) # N: Revealed type is "builtins.int"
is_x(reveal_type(B2.x.name)) # N: Revealed type is "Literal['x']"
is_x(reveal_type(B2.x._name_)) # N: Revealed type is "Literal['x']"
reveal_type(B2.x.value) # N: Revealed type is "builtins.int"
reveal_type(B2.x._value_) # N: Revealed type is "builtins.int"
is_x(reveal_type(B3.x.name)) # N: Revealed type is "Literal['x']"
is_x(reveal_type(B3.x._name_)) # N: Revealed type is "Literal['x']"
reveal_type(B3.x.value) # N: Revealed type is "Literal[1]?"
reveal_type(B3.x._value_) # N: Revealed type is "Literal[1]?"
C1 = IntFlag('C1', 'x')
class C2(IntFlag):
x = auto()
class C3(IntFlag):
x = 1
is_x(reveal_type(C1.x.name)) # N: Revealed type is "Literal['x']"
is_x(reveal_type(C1.x._name_)) # N: Revealed type is "Literal['x']"
reveal_type(C1.x.value) # N: Revealed type is "builtins.int"
reveal_type(C1.x._value_) # N: Revealed type is "builtins.int"
is_x(reveal_type(C2.x.name)) # N: Revealed type is "Literal['x']"
is_x(reveal_type(C2.x._name_)) # N: Revealed type is "Literal['x']"
reveal_type(C2.x.value) # N: Revealed type is "builtins.int"
reveal_type(C2.x._value_) # N: Revealed type is "builtins.int"
is_x(reveal_type(C3.x.name)) # N: Revealed type is "Literal['x']"
is_x(reveal_type(C3.x._name_)) # N: Revealed type is "Literal['x']"
reveal_type(C3.x.value) # N: Revealed type is "Literal[1]?"
reveal_type(C3.x._value_) # N: Revealed type is "Literal[1]?"
D1 = Flag('D1', 'x')
class D2(Flag):
x = auto()
class D3(Flag):
x = 1
is_x(reveal_type(D1.x.name)) # N: Revealed type is "Literal['x']"
is_x(reveal_type(D1.x._name_)) # N: Revealed type is "Literal['x']"
reveal_type(D1.x.value) # N: Revealed type is "builtins.int"
reveal_type(D1.x._value_) # N: Revealed type is "builtins.int"
is_x(reveal_type(D2.x.name)) # N: Revealed type is "Literal['x']"
is_x(reveal_type(D2.x._name_)) # N: Revealed type is "Literal['x']"
reveal_type(D2.x.value) # N: Revealed type is "builtins.int"
reveal_type(D2.x._value_) # N: Revealed type is "builtins.int"
is_x(reveal_type(D3.x.name)) # N: Revealed type is "Literal['x']"
is_x(reveal_type(D3.x._name_)) # N: Revealed type is "Literal['x']"
reveal_type(D3.x.value) # N: Revealed type is "Literal[1]?"
reveal_type(D3.x._value_) # N: Revealed type is "Literal[1]?"
# TODO: Generalize our enum functional API logic to work with subclasses of Enum
# See https://github.com/python/mypy/issues/6037
class Parent(Enum): pass
# E1 = Parent('E1', 'x') # See above TODO
class E2(Parent):
x = auto()
class E3(Parent):
x = 1
is_x(reveal_type(E2.x.name)) # N: Revealed type is "Literal['x']"
is_x(reveal_type(E2.x._name_)) # N: Revealed type is "Literal['x']"
reveal_type(E2.x.value) # N: Revealed type is "builtins.int"
reveal_type(E2.x._value_) # N: Revealed type is "builtins.int"
is_x(reveal_type(E3.x.name)) # N: Revealed type is "Literal['x']"
is_x(reveal_type(E3.x._name_)) # N: Revealed type is "Literal['x']"
reveal_type(E3.x.value) # N: Revealed type is "Literal[1]?"
reveal_type(E3.x._value_) # N: Revealed type is "Literal[1]?"
# TODO: Figure out if we can construct enums using EnumMetas using the functional API.
# Also figure out if we even care about supporting that use case.
class F2(metaclass=EnumMeta):
x = auto()
class F3(metaclass=EnumMeta):
x = 1
F2.x.name # E: "F2" has no attribute "name"
F2.x._name_ # E: "F2" has no attribute "_name_"
F2.x.value # E: "F2" has no attribute "value"
F2.x._value_ # E: "F2" has no attribute "_value_"
F3.x.name # E: "F3" has no attribute "name"
F3.x._name_ # E: "F3" has no attribute "_name_"
F3.x.value # E: "F3" has no attribute "value"
F3.x._value_ # E: "F3" has no attribute "_value_"
[builtins fixtures/primitives.pyi]
[case testEnumAttributeChangeIncremental]
from a import SomeEnum
reveal_type(SomeEnum.a.value)
[file a.py]
from b import SomeEnum
[file b.py]
from enum import Enum
class SomeEnum(Enum):
a = 1
[file b.py.2]
from enum import Enum
class SomeEnum(Enum):
a = "foo"
[builtins fixtures/enum.pyi]
[out]
main:2: note: Revealed type is "Literal[1]?"
[out2]
main:2: note: Revealed type is "Literal['foo']?"
[case testEnumReachabilityChecksBasic]
from enum import Enum
from typing import Literal
class Foo(Enum):
A = 1
B = 2
C = 3
x: Literal[Foo.A, Foo.B, Foo.C]
if x is Foo.A:
reveal_type(x) # N: Revealed type is "Literal[__main__.Foo.A]"
elif x is Foo.B:
reveal_type(x) # N: Revealed type is "Literal[__main__.Foo.B]"
elif x is Foo.C:
reveal_type(x) # N: Revealed type is "Literal[__main__.Foo.C]"
else:
reveal_type(x) # No output here: this branch is unreachable
reveal_type(x) # N: Revealed type is "Union[Literal[__main__.Foo.A], Literal[__main__.Foo.B], Literal[__main__.Foo.C]]"
if Foo.A is x:
reveal_type(x) # N: Revealed type is "Literal[__main__.Foo.A]"
elif Foo.B is x:
reveal_type(x) # N: Revealed type is "Literal[__main__.Foo.B]"
elif Foo.C is x:
reveal_type(x) # N: Revealed type is "Literal[__main__.Foo.C]"
else:
reveal_type(x) # No output here: this branch is unreachable
reveal_type(x) # N: Revealed type is "Union[Literal[__main__.Foo.A], Literal[__main__.Foo.B], Literal[__main__.Foo.C]]"
y: Foo
if y is Foo.A:
reveal_type(y) # N: Revealed type is "Literal[__main__.Foo.A]"
elif y is Foo.B:
reveal_type(y) # N: Revealed type is "Literal[__main__.Foo.B]"
elif y is Foo.C:
reveal_type(y) # N: Revealed type is "Literal[__main__.Foo.C]"
else:
reveal_type(y) # No output here: this branch is unreachable
reveal_type(y) # N: Revealed type is "__main__.Foo"
if Foo.A is y:
reveal_type(y) # N: Revealed type is "Literal[__main__.Foo.A]"
elif Foo.B is y:
reveal_type(y) # N: Revealed type is "Literal[__main__.Foo.B]"
elif Foo.C is y:
reveal_type(y) # N: Revealed type is "Literal[__main__.Foo.C]"
else:
reveal_type(y) # No output here: this branch is unreachable
reveal_type(y) # N: Revealed type is "__main__.Foo"
[builtins fixtures/bool.pyi]
[case testEnumReachabilityChecksWithOrdering]
from enum import Enum
from typing import Literal
class Foo(Enum):
_order_ = "A B"
A = 1
B = 2
Foo._order_ # E: "type[Foo]" has no attribute "_order_"
x: Literal[Foo.A, Foo.B]
if x is Foo.A:
reveal_type(x) # N: Revealed type is "Literal[__main__.Foo.A]"
elif x is Foo.B:
reveal_type(x) # N: Revealed type is "Literal[__main__.Foo.B]"
else:
reveal_type(x) # No output here: this branch is unreachable
class Bar(Enum):
__order__ = "A B"
A = 1
B = 2
Bar.__order__ # E: "type[Bar]" has no attribute "__order__"
y: Literal[Bar.A, Bar.B]
if y is Bar.A:
reveal_type(y) # N: Revealed type is "Literal[__main__.Bar.A]"
elif y is Bar.B:
reveal_type(y) # N: Revealed type is "Literal[__main__.Bar.B]"
else:
reveal_type(y) # No output here: this branch is unreachable
x2: Foo
if x2 is Foo.A:
reveal_type(x2) # N: Revealed type is "Literal[__main__.Foo.A]"
elif x2 is Foo.B:
reveal_type(x2) # N: Revealed type is "Literal[__main__.Foo.B]"
else:
reveal_type(x2) # No output here: this branch is unreachable
y2: Bar
if y2 is Bar.A:
reveal_type(y2) # N: Revealed type is "Literal[__main__.Bar.A]"
elif y2 is Bar.B:
reveal_type(y2) # N: Revealed type is "Literal[__main__.Bar.B]"
else:
reveal_type(y2) # No output here: this branch is unreachable
[builtins fixtures/tuple.pyi]
[case testEnumReachabilityChecksIndirect]
from enum import Enum
from typing import Final, Literal
class Foo(Enum):
A = 1
B = 2
C = 3
def accepts_foo_a(x: Literal[Foo.A]) -> None: ...
x: Foo
y: Literal[Foo.A]
z: Final = Foo.A
if x is y:
reveal_type(x) # N: Revealed type is "Literal[__main__.Foo.A]"
reveal_type(y) # N: Revealed type is "Literal[__main__.Foo.A]"
else:
reveal_type(x) # N: Revealed type is "Union[Literal[__main__.Foo.B], Literal[__main__.Foo.C]]"
reveal_type(y) # N: Revealed type is "Literal[__main__.Foo.A]"
reveal_type(x) # N: Revealed type is "__main__.Foo"
if y is x:
reveal_type(x) # N: Revealed type is "Literal[__main__.Foo.A]"
reveal_type(y) # N: Revealed type is "Literal[__main__.Foo.A]"
else:
reveal_type(x) # N: Revealed type is "Union[Literal[__main__.Foo.B], Literal[__main__.Foo.C]]"
reveal_type(y) # N: Revealed type is "Literal[__main__.Foo.A]"
reveal_type(x) # N: Revealed type is "__main__.Foo"
if x is z:
reveal_type(x) # N: Revealed type is "Literal[__main__.Foo.A]"
reveal_type(z) # N: Revealed type is "Literal[__main__.Foo.A]?"
accepts_foo_a(z)
else:
reveal_type(x) # N: Revealed type is "Union[Literal[__main__.Foo.B], Literal[__main__.Foo.C]]"
reveal_type(z) # N: Revealed type is "Literal[__main__.Foo.A]?"
accepts_foo_a(z)
reveal_type(x) # N: Revealed type is "__main__.Foo"
if z is x:
reveal_type(x) # N: Revealed type is "Literal[__main__.Foo.A]"
reveal_type(z) # N: Revealed type is "Literal[__main__.Foo.A]?"
accepts_foo_a(z)
else:
reveal_type(x) # N: Revealed type is "Union[Literal[__main__.Foo.B], Literal[__main__.Foo.C]]"
reveal_type(z) # N: Revealed type is "Literal[__main__.Foo.A]?"
accepts_foo_a(z)
reveal_type(x) # N: Revealed type is "__main__.Foo"
if y is z:
reveal_type(y) # N: Revealed type is "Literal[__main__.Foo.A]"
reveal_type(z) # N: Revealed type is "Literal[__main__.Foo.A]?"
accepts_foo_a(z)
else:
reveal_type(y) # No output: this branch is unreachable
reveal_type(z) # No output: this branch is unreachable
if z is y:
reveal_type(y) # N: Revealed type is "Literal[__main__.Foo.A]"
reveal_type(z) # N: Revealed type is "Literal[__main__.Foo.A]?"
accepts_foo_a(z)
else:
reveal_type(y) # No output: this branch is unreachable
reveal_type(z) # No output: this branch is unreachable
[builtins fixtures/bool.pyi]
[case testEnumReachabilityNoNarrowingForUnionMessiness]
from enum import Enum
from typing import Literal
class Foo(Enum):
A = 1
B = 2
C = 3
x: Foo
y: Literal[Foo.A, Foo.B]
z: Literal[Foo.B, Foo.C]
# For the sake of simplicity, no narrowing is done when the narrower type is a Union.
if x is y:
reveal_type(x) # N: Revealed type is "__main__.Foo"
reveal_type(y) # N: Revealed type is "Union[Literal[__main__.Foo.A], Literal[__main__.Foo.B]]"
else:
reveal_type(x) # N: Revealed type is "__main__.Foo"
reveal_type(y) # N: Revealed type is "Union[Literal[__main__.Foo.A], Literal[__main__.Foo.B]]"
if y is z:
reveal_type(y) # N: Revealed type is "Union[Literal[__main__.Foo.A], Literal[__main__.Foo.B]]"
reveal_type(z) # N: Revealed type is "Union[Literal[__main__.Foo.B], Literal[__main__.Foo.C]]"
else:
reveal_type(y) # N: Revealed type is "Union[Literal[__main__.Foo.A], Literal[__main__.Foo.B]]"
reveal_type(z) # N: Revealed type is "Union[Literal[__main__.Foo.B], Literal[__main__.Foo.C]]"
[builtins fixtures/bool.pyi]
[case testEnumReachabilityWithNone]
from enum import Enum
from typing import Optional
class Foo(Enum):
A = 1
B = 2
C = 3
x: Optional[Foo]
if x:
reveal_type(x) # N: Revealed type is "__main__.Foo"
else:
reveal_type(x) # N: Revealed type is "None"
if x is not None:
reveal_type(x) # N: Revealed type is "__main__.Foo"
else:
reveal_type(x) # N: Revealed type is "None"
if x is Foo.A:
reveal_type(x) # N: Revealed type is "Literal[__main__.Foo.A]"
else:
reveal_type(x) # N: Revealed type is "Union[Literal[__main__.Foo.B], Literal[__main__.Foo.C], None]"
reveal_type(x) # N: Revealed type is "Union[__main__.Foo, None]"
[builtins fixtures/enum.pyi]
[case testEnumReachabilityWithMultipleEnums]
from enum import Enum
from typing import Literal, Union
class Foo(Enum):
A = 1
B = 2
class Bar(Enum):
A = 1
B = 2
x1: Union[Foo, Bar]
if x1 is Foo.A:
reveal_type(x1) # N: Revealed type is "Literal[__main__.Foo.A]"
else:
reveal_type(x1) # N: Revealed type is "Union[Literal[__main__.Foo.B], __main__.Bar]"
reveal_type(x1) # N: Revealed type is "Union[__main__.Foo, __main__.Bar]"
x2: Union[Foo, Bar]
if x2 is Bar.A:
reveal_type(x2) # N: Revealed type is "Literal[__main__.Bar.A]"
else:
reveal_type(x2) # N: Revealed type is "Union[__main__.Foo, Literal[__main__.Bar.B]]"
reveal_type(x2) # N: Revealed type is "Union[__main__.Foo, __main__.Bar]"
x3: Union[Foo, Bar]
if x3 is Foo.A or x3 is Bar.A:
reveal_type(x3) # N: Revealed type is "Union[Literal[__main__.Foo.A], Literal[__main__.Bar.A]]"
else:
reveal_type(x3) # N: Revealed type is "Union[Literal[__main__.Foo.B], Literal[__main__.Bar.B]]"
reveal_type(x3) # N: Revealed type is "Union[__main__.Foo, __main__.Bar]"
[builtins fixtures/bool.pyi]
[case testEnumReachabilityPEP484ExampleWithFinal]
from typing import Final, Union
from enum import Enum
class Empty(Enum):
token = 0
_empty: Final = Empty.token
def func(x: Union[int, None, Empty] = _empty) -> int:
boom = x + 42 # E: Unsupported left operand type for + ("None") \
# E: Unsupported left operand type for + ("Empty") \
# N: Left operand is of type "Union[int, Empty, None]"
if x is _empty:
reveal_type(x) # N: Revealed type is "Literal[__main__.Empty.token]"
return 0
elif x is None:
reveal_type(x) # N: Revealed type is "None"
return 1
else: # At this point typechecker knows that x can only have type int
reveal_type(x) # N: Revealed type is "builtins.int"
return x + 2
[builtins fixtures/primitives.pyi]
[case testEnumReachabilityPEP484ExampleWithMultipleValues]
from typing import Union
from enum import Enum
class Reason(Enum):
timeout = 1
error = 2
def process(response: Union[str, Reason] = '') -> str:
if response is Reason.timeout:
reveal_type(response) # N: Revealed type is "Literal[__main__.Reason.timeout]"
return 'TIMEOUT'
elif response is Reason.error:
reveal_type(response) # N: Revealed type is "Literal[__main__.Reason.error]"
return 'ERROR'
else:
# response can be only str, all other possible values exhausted
reveal_type(response) # N: Revealed type is "builtins.str"
return 'PROCESSED: ' + response
[builtins fixtures/primitives.pyi]
[case testEnumReachabilityPEP484ExampleSingleton]
from typing import Final, Union
from enum import Enum
class Empty(Enum):
token = 0
_empty = Empty.token
def func(x: Union[int, None, Empty] = _empty) -> int:
boom = x + 42 # E: Unsupported left operand type for + ("None") \
# E: Unsupported left operand type for + ("Empty") \
# N: Left operand is of type "Union[int, Empty, None]"
if x is _empty:
reveal_type(x) # N: Revealed type is "Literal[__main__.Empty.token]"
return 0
elif x is None:
reveal_type(x) # N: Revealed type is "None"
return 1
else: # At this point typechecker knows that x can only have type int
reveal_type(x) # N: Revealed type is "builtins.int"
return x + 2
[builtins fixtures/primitives.pyi]
[case testEnumReachabilityPEP484ExampleSingletonWithMethod]
# flags: --python-version 3.11
from typing import Final, Union
from enum import Enum, member
class Empty(Enum):
# note, that without `member` we cannot tell that `token` is a member:
token = member(lambda x: x)
def f(self) -> int:
return 1
_empty = Empty.token
reveal_type(_empty) # N: Revealed type is "__main__.Empty"
reveal_type(Empty.f) # N: Revealed type is "def (self: __main__.Empty) -> builtins.int"
def func(x: Union[int, None, Empty] = _empty) -> int:
boom = x + 42 # E: Unsupported left operand type for + ("None") \
# E: Unsupported left operand type for + ("Empty") \
# N: Left operand is of type "Union[int, Empty, None]"
if x is _empty:
reveal_type(x) # N: Revealed type is "Literal[__main__.Empty.token]"
return 0
elif x is None:
reveal_type(x) # N: Revealed type is "None"
return 1
else: # At this point typechecker knows that x can only have type int
reveal_type(x) # N: Revealed type is "builtins.int"
return x + 2
[builtins fixtures/primitives.pyi]
[case testAssignEnumAsAttribute]
from enum import Enum
class A:
def __init__(self) -> None:
self.b = Enum("b", [("foo", "bar")]) # E: Enum type as attribute is not supported
reveal_type(A().b) # N: Revealed type is "Any"
[builtins fixtures/enum.pyi]
[case testEnumReachabilityWithChaining]
from enum import Enum
class Foo(Enum):
A = 1
B = 2
x: Foo
y: Foo
# We can't narrow anything in the else cases -- what if
# x is Foo.A and y is Foo.B or vice versa, for example?
if x is y is Foo.A:
reveal_type(x) # N: Revealed type is "Literal[__main__.Foo.A]"
reveal_type(y) # N: Revealed type is "Literal[__main__.Foo.A]"
elif x is y is Foo.B:
reveal_type(x) # N: Revealed type is "Literal[__main__.Foo.B]"
reveal_type(y) # N: Revealed type is "Literal[__main__.Foo.B]"
else:
reveal_type(x) # N: Revealed type is "__main__.Foo"
reveal_type(y) # N: Revealed type is "__main__.Foo"
reveal_type(x) # N: Revealed type is "__main__.Foo"
reveal_type(y) # N: Revealed type is "__main__.Foo"
if x is Foo.A is y:
reveal_type(x) # N: Revealed type is "Literal[__main__.Foo.A]"
reveal_type(y) # N: Revealed type is "Literal[__main__.Foo.A]"
elif x is Foo.B is y:
reveal_type(x) # N: Revealed type is "Literal[__main__.Foo.B]"
reveal_type(y) # N: Revealed type is "Literal[__main__.Foo.B]"
else:
reveal_type(x) # N: Revealed type is "__main__.Foo"
reveal_type(y) # N: Revealed type is "__main__.Foo"
reveal_type(x) # N: Revealed type is "__main__.Foo"
reveal_type(y) # N: Revealed type is "__main__.Foo"
if Foo.A is x is y:
reveal_type(x) # N: Revealed type is "Literal[__main__.Foo.A]"
reveal_type(y) # N: Revealed type is "Literal[__main__.Foo.A]"
elif Foo.B is x is y:
reveal_type(x) # N: Revealed type is "Literal[__main__.Foo.B]"
reveal_type(y) # N: Revealed type is "Literal[__main__.Foo.B]"
else:
reveal_type(x) # N: Revealed type is "__main__.Foo"
reveal_type(y) # N: Revealed type is "__main__.Foo"
reveal_type(x) # N: Revealed type is "__main__.Foo"
reveal_type(y) # N: Revealed type is "__main__.Foo"
[builtins fixtures/primitives.pyi]
[case testEnumReachabilityWithChainingDisjoint]
# flags: --warn-unreachable
from enum import Enum
class Foo(Enum):
A = 1
B = 2
# Used to divide up a chained comparison into multiple identity groups
def __lt__(self, other: object) -> bool: return True
x: Foo
y: Foo
# No conflict
if x is Foo.A < y is Foo.B:
reveal_type(x) # N: Revealed type is "Literal[__main__.Foo.A]"
reveal_type(y) # N: Revealed type is "Literal[__main__.Foo.B]"
else:
# Note: we can't narrow in this case. What if both x and y
# are Foo.A, for example?
reveal_type(x) # N: Revealed type is "__main__.Foo"
reveal_type(y) # N: Revealed type is "__main__.Foo"
reveal_type(x) # N: Revealed type is "__main__.Foo"
reveal_type(y) # N: Revealed type is "__main__.Foo"
# The standard output when we end up inferring two disjoint facts about the same expr
if x is Foo.A and x is Foo.B:
reveal_type(x) # E: Statement is unreachable
else:
reveal_type(x) # N: Revealed type is "__main__.Foo"
reveal_type(x) # N: Revealed type is "__main__.Foo"
# ..and we get the same result if we have two disjoint groups within the same comp expr
if x is Foo.A < x is Foo.B:
reveal_type(x) # E: Statement is unreachable
else:
reveal_type(x) # N: Revealed type is "__main__.Foo"
reveal_type(x) # N: Revealed type is "__main__.Foo"
[builtins fixtures/primitives.pyi]
[case testEnumReachabilityWithChainingDirectConflict]
# flags: --warn-unreachable
from enum import Enum
from typing import Final, Literal
class Foo(Enum):
A = 1
B = 2
C = 3
x: Foo
if x is Foo.A is Foo.B:
reveal_type(x) # E: Statement is unreachable
else:
reveal_type(x) # N: Revealed type is "__main__.Foo"
reveal_type(x) # N: Revealed type is "__main__.Foo"
literal_a: Literal[Foo.A]
literal_b: Literal[Foo.B]
if x is literal_a is literal_b:
reveal_type(x) # E: Statement is unreachable
else:
reveal_type(x) # N: Revealed type is "__main__.Foo"
reveal_type(x) # N: Revealed type is "__main__.Foo"
final_a: Final = Foo.A
final_b: Final = Foo.B
if x is final_a is final_b:
reveal_type(x) # E: Statement is unreachable
else:
reveal_type(x) # N: Revealed type is "__main__.Foo"
reveal_type(x) # N: Revealed type is "__main__.Foo"
[builtins fixtures/primitives.pyi]
[case testEnumReachabilityWithChainingBigDisjoints]
# flags: --warn-unreachable
from enum import Enum
from typing import Final, Literal
class Foo(Enum):
A = 1
B = 2
C = 3
def __lt__(self, other: object) -> bool: return True
x0: Foo
x1: Foo
x2: Foo
x3: Foo
x4: Foo
x5: Foo
if x0 is x1 is Foo.A is x2 < x3 is Foo.B is x4 is x5:
reveal_type(x0) # N: Revealed type is "Literal[__main__.Foo.A]"
reveal_type(x1) # N: Revealed type is "Literal[__main__.Foo.A]"
reveal_type(x2) # N: Revealed type is "Literal[__main__.Foo.A]"
reveal_type(x3) # N: Revealed type is "Literal[__main__.Foo.B]"
reveal_type(x4) # N: Revealed type is "Literal[__main__.Foo.B]"
reveal_type(x5) # N: Revealed type is "Literal[__main__.Foo.B]"
else:
# We unfortunately can't narrow away anything. For example,
# what if x0 == Foo.A and x1 == Foo.B or vice versa?
reveal_type(x0) # N: Revealed type is "__main__.Foo"
reveal_type(x1) # N: Revealed type is "__main__.Foo"
reveal_type(x2) # N: Revealed type is "__main__.Foo"
reveal_type(x3) # N: Revealed type is "__main__.Foo"
reveal_type(x4) # N: Revealed type is "__main__.Foo"
reveal_type(x5) # N: Revealed type is "__main__.Foo"
[builtins fixtures/primitives.pyi]
[case testPrivateAttributeNotAsEnumMembers]
import enum
class Comparator(enum.Enum):
LessThan = "<"
LessThanOrEqualTo = "<="
EqualTo = "=="
NotEqualTo = "!="
GreaterThanOrEqualTo = ">="
GreaterThan = ">"
__foo__ = {
LessThan: 1,
LessThanOrEqualTo: 2,
EqualTo: 3,
NotEqualTo: 4,
GreaterThanOrEqualTo: 5,
GreaterThan: 6,
}
def foo(self) -> int:
return Comparator.__foo__[self.value]
reveal_type(Comparator.__foo__) # N: Revealed type is "builtins.dict[builtins.str, builtins.int]"
[builtins fixtures/dict.pyi]
[case testEnumWithInstanceAttributes]
from enum import Enum
class Foo(Enum):
def __init__(self, value: int) -> None:
self.foo = "bar"
A = 1
B = 2
a = Foo.A
reveal_type(a.value) # N: Revealed type is "Union[Literal[1]?, Literal[2]?]"
reveal_type(a._value_) # N: Revealed type is "Union[Literal[1]?, Literal[2]?]"
[builtins fixtures/enum.pyi]
[case testNewSetsUnexpectedValueType]
from enum import Enum
class bytes:
def __new__(cls): pass
class Foo(bytes, Enum):
def __new__(cls, value: int) -> 'Foo':
obj = bytes.__new__(cls)
obj._value_ = "Number %d" % value
return obj
A = 1
B = 2
a = Foo.A
reveal_type(a.value) # N: Revealed type is "Any"
reveal_type(a._value_) # N: Revealed type is "Any"
[builtins fixtures/tuple.pyi]
[typing fixtures/typing-medium.pyi]
[case testValueTypeWithNewInParentClass]
from enum import Enum
class bytes:
def __new__(cls): pass
class Foo(bytes, Enum):
def __new__(cls, value: int) -> 'Foo':
obj = bytes.__new__(cls)
obj._value_ = "Number %d" % value
return obj
class Bar(Foo):
A = 1
B = 2
a = Bar.A
reveal_type(a.value) # N: Revealed type is "Any"
reveal_type(a._value_) # N: Revealed type is "Any"
[builtins fixtures/primitives.pyi]
[typing fixtures/typing-medium.pyi]
[case testEnumNarrowedToTwoLiterals]
# Regression test: two literals of an enum would be joined
# as the full type, regardless of the amount of elements
# the enum contains.
from enum import Enum
from typing import Literal, Union
class Foo(Enum):
A = 1
B = 2
C = 3
def f(x: Foo):
if x is Foo.A:
return x
if x is Foo.B:
pass
reveal_type(x) # N: Revealed type is "Union[Literal[__main__.Foo.B], Literal[__main__.Foo.C]]"
[builtins fixtures/bool.pyi]
[case testEnumTypeCompatibleWithLiteralUnion]
from enum import Enum
from typing import Literal
class E(Enum):
A = 1
B = 2
C = 3
e: E
a: Literal[E.A, E.B, E.C] = e
b: Literal[E.A, E.B] = e # E: Incompatible types in assignment (expression has type "E", variable has type "Literal[E.A, E.B]")
c: Literal[E.A, E.C] = e # E: Incompatible types in assignment (expression has type "E", variable has type "Literal[E.A, E.C]")
b = a # E: Incompatible types in assignment (expression has type "Literal[E.A, E.B, E.C]", variable has type "Literal[E.A, E.B]")
[builtins fixtures/bool.pyi]
[case testIntEnumWithNewTypeValue]
from typing import NewType
from enum import IntEnum
N = NewType("N", int)
class E(IntEnum):
A = N(0)
reveal_type(E.A.value) # N: Revealed type is "__main__.N"
[builtins fixtures/enum.pyi]
[case testEnumFinalValues]
from enum import Enum
class Medal(Enum):
gold = 1
silver = 2
# Another value:
Medal.gold = 0 # E: Cannot assign to final attribute "gold"
# Same value:
Medal.silver = 2 # E: Cannot assign to final attribute "silver"
[builtins fixtures/enum.pyi]
[case testEnumFinalValuesCannotRedefineValueProp]
from enum import Enum
class Types(Enum):
key = 0
value = 1
[builtins fixtures/enum.pyi]
[case testEnumReusedKeys]
# https://github.com/python/mypy/issues/11248
from enum import Enum
class Correct(Enum):
x = 'y'
y = 'x'
class Correct2(Enum):
x = 'y'
__z = 'y'
__z = 'x'
class Foo(Enum):
A = 1
A = 'a' # E: Attempted to reuse member name "A" in Enum definition "Foo" \
# E: Incompatible types in assignment (expression has type "str", variable has type "int")
reveal_type(Foo.A.value) # N: Revealed type is "Literal[1]?"
class Bar(Enum):
A = 1
B = A = 2 # E: Attempted to reuse member name "A" in Enum definition "Bar"
class Baz(Enum):
A = 1
B, A = (1, 2) # E: Attempted to reuse member name "A" in Enum definition "Baz"
[builtins fixtures/tuple.pyi]
[case testEnumReusedKeysOverlapWithLocalVar]
from enum import Enum
x = 1
class Foo(Enum):
x = 2
def method(self) -> None:
x = 3
x = 4
[builtins fixtures/bool.pyi]
[case testEnumImplicitlyFinalForSubclassing]
from enum import Enum, IntEnum, Flag, IntFlag
class NonEmptyEnum(Enum):
x = 1
class NonEmptyIntEnum(IntEnum):
x = 1
class NonEmptyFlag(Flag):
x = 1
class NonEmptyIntFlag(IntFlag):
x = 1
class ErrorEnumWithValue(NonEmptyEnum): # E: Cannot extend enum with existing members: "NonEmptyEnum"
x = 1 # E: Cannot override final attribute "x" (previously declared in base class "NonEmptyEnum")
class ErrorIntEnumWithValue(NonEmptyIntEnum): # E: Cannot extend enum with existing members: "NonEmptyIntEnum"
x = 1 # E: Cannot override final attribute "x" (previously declared in base class "NonEmptyIntEnum")
class ErrorFlagWithValue(NonEmptyFlag): # E: Cannot extend enum with existing members: "NonEmptyFlag"
x = 1 # E: Cannot override final attribute "x" (previously declared in base class "NonEmptyFlag")
class ErrorIntFlagWithValue(NonEmptyIntFlag): # E: Cannot extend enum with existing members: "NonEmptyIntFlag"
x = 1 # E: Cannot override final attribute "x" (previously declared in base class "NonEmptyIntFlag")
class ErrorEnumWithoutValue(NonEmptyEnum): # E: Cannot extend enum with existing members: "NonEmptyEnum"
pass
class ErrorIntEnumWithoutValue(NonEmptyIntEnum): # E: Cannot extend enum with existing members: "NonEmptyIntEnum"
pass
class ErrorFlagWithoutValue(NonEmptyFlag): # E: Cannot extend enum with existing members: "NonEmptyFlag"
pass
class ErrorIntFlagWithoutValue(NonEmptyIntFlag): # E: Cannot extend enum with existing members: "NonEmptyIntFlag"
pass
[builtins fixtures/bool.pyi]
[case testEnumImplicitlyFinalForSubclassingWithCallableMember]
# flags: --python-version 3.11
from enum import Enum, IntEnum, Flag, IntFlag, member
class NonEmptyEnum(Enum):
@member
def call(self) -> None: ...
class NonEmptyIntEnum(IntEnum):
@member
def call(self) -> None: ...
class NonEmptyFlag(Flag):
@member
def call(self) -> None: ...
class NonEmptyIntFlag(IntFlag):
@member
def call(self) -> None: ...
class ErrorEnumWithoutValue(NonEmptyEnum): # E: Cannot extend enum with existing members: "NonEmptyEnum"
pass
class ErrorIntEnumWithoutValue(NonEmptyIntEnum): # E: Cannot extend enum with existing members: "NonEmptyIntEnum"
pass
class ErrorFlagWithoutValue(NonEmptyFlag): # E: Cannot extend enum with existing members: "NonEmptyFlag"
pass
class ErrorIntFlagWithoutValue(NonEmptyIntFlag): # E: Cannot extend enum with existing members: "NonEmptyIntFlag"
pass
[builtins fixtures/bool.pyi]
[case testEnumCanExtendEnumsWithNonMembers]
# flags: --python-version 3.11
from enum import Enum, IntEnum, Flag, IntFlag, nonmember
class NonEmptyEnum(Enum):
x = nonmember(1)
class NonEmptyIntEnum(IntEnum):
x = nonmember(1)
class NonEmptyFlag(Flag):
x = nonmember(1)
class NonEmptyIntFlag(IntFlag):
x = nonmember(1)
class ErrorEnumWithoutValue(NonEmptyEnum):
pass
class ErrorIntEnumWithoutValue(NonEmptyIntEnum):
pass
class ErrorFlagWithoutValue(NonEmptyFlag):
pass
class ErrorIntFlagWithoutValue(NonEmptyIntFlag):
pass
[builtins fixtures/bool.pyi]
[case testLambdaIsNotEnumMember]
from enum import Enum
class My(Enum):
x = lambda a: a
class Other(My): ...
[builtins fixtures/bool.pyi]
[case testSubclassingNonFinalEnums]
from enum import Enum, IntEnum, Flag, IntFlag, EnumMeta
def decorator(func):
return func
class EmptyEnum(Enum):
pass
class EmptyIntEnum(IntEnum):
pass
class EmptyFlag(Flag):
pass
class EmptyIntFlag(IntFlag):
pass
class EmptyEnumMeta(EnumMeta):
pass
class NonEmptyEnumSub(EmptyEnum):
x = 1
class NonEmptyIntEnumSub(EmptyIntEnum):
x = 1
class NonEmptyFlagSub(EmptyFlag):
x = 1
class NonEmptyIntFlagSub(EmptyIntFlag):
x = 1
class NonEmptyEnumMetaSub(EmptyEnumMeta):
x = 1
class EmptyEnumSub(EmptyEnum):
def method(self) -> None: pass
@decorator
def other(self) -> None: pass
class EmptyIntEnumSub(EmptyIntEnum):
def method(self) -> None: pass
class EmptyFlagSub(EmptyFlag):
def method(self) -> None: pass
class EmptyIntFlagSub(EmptyIntFlag):
def method(self) -> None: pass
class EmptyEnumMetaSub(EmptyEnumMeta):
def method(self) -> None: pass
class NestedEmptyEnumSub(EmptyEnumSub):
x = 1
class NestedEmptyIntEnumSub(EmptyIntEnumSub):
x = 1
class NestedEmptyFlagSub(EmptyFlagSub):
x = 1
class NestedEmptyIntFlagSub(EmptyIntFlagSub):
x = 1
class NestedEmptyEnumMetaSub(EmptyEnumMetaSub):
x = 1
[builtins fixtures/bool.pyi]
[case testEnumExplicitlyAndImplicitlyFinal]
from typing import final
from enum import Enum, IntEnum, Flag, IntFlag, EnumMeta
@final
class EmptyEnum(Enum):
pass
@final
class EmptyIntEnum(IntEnum):
pass
@final
class EmptyFlag(Flag):
pass
@final
class EmptyIntFlag(IntFlag):
pass
@final
class EmptyEnumMeta(EnumMeta):
pass
class EmptyEnumSub(EmptyEnum): # E: Cannot inherit from final class "EmptyEnum"
pass
class EmptyIntEnumSub(EmptyIntEnum): # E: Cannot inherit from final class "EmptyIntEnum"
pass
class EmptyFlagSub(EmptyFlag): # E: Cannot inherit from final class "EmptyFlag"
pass
class EmptyIntFlagSub(EmptyIntFlag): # E: Cannot inherit from final class "EmptyIntFlag"
pass
class EmptyEnumMetaSub(EmptyEnumMeta): # E: Cannot inherit from final class "EmptyEnumMeta"
pass
@final
class NonEmptyEnum(Enum):
x = 1
@final
class NonEmptyIntEnum(IntEnum):
x = 1
@final
class NonEmptyFlag(Flag):
x = 1
@final
class NonEmptyIntFlag(IntFlag):
x = 1
@final
class NonEmptyEnumMeta(EnumMeta):
x = 1
class ErrorEnumWithoutValue(NonEmptyEnum): # E: Cannot inherit from final class "NonEmptyEnum" \
# E: Cannot extend enum with existing members: "NonEmptyEnum"
pass
class ErrorIntEnumWithoutValue(NonEmptyIntEnum): # E: Cannot inherit from final class "NonEmptyIntEnum" \
# E: Cannot extend enum with existing members: "NonEmptyIntEnum"
pass
class ErrorFlagWithoutValue(NonEmptyFlag): # E: Cannot inherit from final class "NonEmptyFlag" \
# E: Cannot extend enum with existing members: "NonEmptyFlag"
pass
class ErrorIntFlagWithoutValue(NonEmptyIntFlag): # E: Cannot inherit from final class "NonEmptyIntFlag" \
# E: Cannot extend enum with existing members: "NonEmptyIntFlag"
pass
class ErrorEnumMetaWithoutValue(NonEmptyEnumMeta): # E: Cannot inherit from final class "NonEmptyEnumMeta"
pass
[builtins fixtures/bool.pyi]
[case testEnumFinalSubtypingEnumMetaSpecialCase]
from enum import EnumMeta
# `EnumMeta` types are not `Enum`s
class SubMeta(EnumMeta):
x = 1
class SubSubMeta(SubMeta):
x = 2
[builtins fixtures/bool.pyi]
[case testEnumFinalSubtypingOverloadedSpecialCase]
from typing import overload
from enum import Enum, IntEnum, Flag, IntFlag, EnumMeta
class EmptyEnum(Enum):
@overload
def method(self, arg: int) -> int:
pass
@overload
def method(self, arg: str) -> str:
pass
def method(self, arg):
pass
class EmptyIntEnum(IntEnum):
@overload
def method(self, arg: int) -> int:
pass
@overload
def method(self, arg: str) -> str:
pass
def method(self, arg):
pass
class EmptyFlag(Flag):
@overload
def method(self, arg: int) -> int:
pass
@overload
def method(self, arg: str) -> str:
pass
def method(self, arg):
pass
class EmptyIntFlag(IntFlag):
@overload
def method(self, arg: int) -> int:
pass
@overload
def method(self, arg: str) -> str:
pass
def method(self, arg):
pass
class EmptyEnumMeta(EnumMeta):
@overload
def method(self, arg: int) -> int:
pass
@overload
def method(self, arg: str) -> str:
pass
def method(self, arg):
pass
class NonEmptyEnumSub(EmptyEnum):
x = 1
class NonEmptyIntEnumSub(EmptyIntEnum):
x = 1
class NonEmptyFlagSub(EmptyFlag):
x = 1
class NonEmptyIntFlagSub(EmptyIntFlag):
x = 1
class NonEmptyEnumMetaSub(EmptyEnumMeta):
x = 1
[builtins fixtures/bool.pyi]
[case testEnumFinalSubtypingMethodAndValueSpecialCase]
from enum import Enum, IntEnum, Flag, IntFlag, EnumMeta
def decorator(func):
return func
class NonEmptyEnum(Enum):
x = 1
def method(self) -> None: pass
@decorator
def other(self) -> None: pass
class NonEmptyIntEnum(IntEnum):
x = 1
def method(self) -> None: pass
class NonEmptyFlag(Flag):
x = 1
def method(self) -> None: pass
class NonEmptyIntFlag(IntFlag):
x = 1
def method(self) -> None: pass
class ErrorEnumWithoutValue(NonEmptyEnum): # E: Cannot extend enum with existing members: "NonEmptyEnum"
pass
class ErrorIntEnumWithoutValue(NonEmptyIntEnum): # E: Cannot extend enum with existing members: "NonEmptyIntEnum"
pass
class ErrorFlagWithoutValue(NonEmptyFlag): # E: Cannot extend enum with existing members: "NonEmptyFlag"
pass
class ErrorIntFlagWithoutValue(NonEmptyIntFlag): # E: Cannot extend enum with existing members: "NonEmptyIntFlag"
pass
[builtins fixtures/bool.pyi]
[case testFinalEnumWithClassDef]
from enum import Enum
class A(Enum):
class Inner: pass
class B(A): pass # E: Cannot extend enum with existing members: "A"
class A1(Enum):
class __Inner: pass
class B1(A1): pass
[builtins fixtures/bool.pyi]
[case testEnumFinalSpecialProps]
# https://github.com/python/mypy/issues/11699
# https://github.com/python/mypy/issues/11820
from enum import Enum, IntEnum
class BaseWithSpecials:
__slots__ = ()
__doc__ = 'doc'
__module__ = 'module'
__annotations__ = {'a': int}
__dict__ = {'a': 1}
class E(BaseWithSpecials, Enum):
name = 'a'
value = 'b'
_name_ = 'a1'
_value_ = 'b2'
_order_ = 'X Y'
__order__ = 'X Y'
__slots__ = ()
__doc__ = 'doc'
__module__ = 'module'
__annotations__ = {'a': int}
__dict__ = {'a': 1}
class EI(IntEnum):
name = 'a'
value = 1
_name_ = 'a1'
_value_ = 2
_order_ = 'X Y'
__order__ = 'X Y'
__slots__ = ()
__doc__ = 'doc'
__module__ = 'module'
__annotations__ = {'a': int}
__dict__ = {'a': 1}
E._order_ = 'a' # E: Cannot assign to final attribute "_order_"
EI.value = 2 # E: Cannot assign to final attribute "value"
[builtins fixtures/dict.pyi]
[case testEnumNotFinalWithMethodsAndUninitializedValues]
# https://github.com/python/mypy/issues/11578
from enum import Enum
from typing import Final
class A(Enum):
x: int
def method(self) -> int: pass
class B(A):
x = 1 # E: Cannot override writable attribute "x" with a final one \
# E: Incompatible types in assignment (expression has type "B", base class "A" defined the type as "int")
class A1(Enum):
x: int = 1 # E: Enum members must be left unannotated \
# N: See https://typing.readthedocs.io/en/latest/spec/enums.html#defining-members
class B1(A1): # E: Cannot extend enum with existing members: "A1"
pass
class A2(Enum):
x = 2
class B2(A2): # E: Cannot extend enum with existing members: "A2"
pass
# We leave this `Final` without a value,
# because we need to test annotation only mode:
class A3(Enum):
x: Final[int] # type: ignore
class B3(A3):
x = 1 # E: Cannot override final attribute "x" (previously declared in base class "A3") \
# E: Incompatible types in assignment (expression has type "B3", base class "A3" defined the type as "int")
[builtins fixtures/bool.pyi]
[case testEnumNotFinalWithMethodsAndUninitializedValuesStub]
import lib
[file lib.pyi]
from enum import Enum
class A(Enum): # E: Detected enum "lib.A" in a type stub with zero members. There is a chance this is due to a recent change in the semantics of enum membership. If so, use `member = value` to mark an enum member, instead of `member: type` \
# N: See https://typing.readthedocs.io/en/latest/spec/enums.html#defining-members
x: int
class B(A):
x = 1 # E: Cannot override writable attribute "x" with a final one \
# E: Incompatible types in assignment (expression has type "B", base class "A" defined the type as "int")
class C(Enum):
x = 1
class D(C): # E: Cannot extend enum with existing members: "C" \
# E: Detected enum "lib.D" in a type stub with zero members. There is a chance this is due to a recent change in the semantics of enum membership. If so, use `member = value` to mark an enum member, instead of `member: type` \
# N: See https://typing.readthedocs.io/en/latest/spec/enums.html#defining-members
x: int # E: Incompatible types in assignment (expression has type "int", base class "C" defined the type as "C") \
# E: Cannot assign to final name "x"
[builtins fixtures/bool.pyi]
[case testEnumNotFinalWithMethodsAndUninitializedValuesStubMember]
# flags: --python-version 3.11
# This was added in 3.11
import lib
[file lib.pyi]
from enum import Enum, member
class A(Enum):
@member
def x(self) -> None: ...
[builtins fixtures/bool.pyi]
[case testEnumLiteralValues]
from enum import Enum
class A(Enum):
str = "foo"
int = 1
bool = False
tuple = (1,)
reveal_type(A.str.value) # N: Revealed type is "Literal['foo']?"
reveal_type(A.int.value) # N: Revealed type is "Literal[1]?"
reveal_type(A.bool.value) # N: Revealed type is "Literal[False]?"
reveal_type(A.tuple.value) # N: Revealed type is "tuple[Literal[1]?]"
[builtins fixtures/tuple.pyi]
[case testFinalWithPrivateAssignment]
import enum
class Some(enum.Enum):
__priv = 1
class Other(Some): # Should pass
pass
[builtins fixtures/tuple.pyi]
[case testFinalWithDunderAssignment]
import enum
class Some(enum.Enum):
__some__ = 1
class Other(Some): # Should pass
pass
[builtins fixtures/tuple.pyi]
[case testFinalWithSunderAssignment]
import enum
class Some(enum.Enum):
_some_ = 1
class Other(Some): # Should pass
pass
[builtins fixtures/tuple.pyi]
[case testFinalWithMethodAssignment]
import enum
from typing import overload
class Some(enum.Enum):
def lor(self, other) -> bool:
pass
ror = lor
class Other(Some): # Should pass
pass
class WithOverload(enum.IntEnum):
@overload
def meth(self, arg: int) -> int: pass
@overload
def meth(self, arg: str) -> str: pass
def meth(self, arg): pass
alias = meth
class SubWithOverload(WithOverload): # Should pass
pass
[builtins fixtures/tuple.pyi]
[case testEnumBaseClassesOrder]
import enum
# Base types:
class First:
def __new__(cls, val):
pass
class Second:
def __new__(cls, val):
pass
class Third:
def __new__(cls, val):
pass
class Mixin:
pass
class EnumWithCustomNew(enum.Enum):
def __new__(cls, val):
pass
class SecondEnumWithCustomNew(enum.Enum):
def __new__(cls, val):
pass
# Correct Enums:
class Correct0(enum.Enum):
pass
class Correct1(Mixin, First, enum.Enum):
pass
class Correct2(First, enum.Enum):
pass
class Correct3(Mixin, enum.Enum):
pass
class RegularClass(Mixin, First, Second):
pass
class Correct5(enum.Enum):
pass
# Correct inheritance:
class _InheritingDataAndMixin(Correct1):
pass
class _CorrectWithData(First, Correct0):
pass
class _CorrectWithDataAndMixin(Mixin, First, Correct0):
pass
class _CorrectWithMixin(Mixin, Correct2):
pass
class _CorrectMultipleEnumBases(Correct0, Correct5):
pass
class _MultipleEnumBasesAndMixin(int, Correct0, enum.Flag):
pass
class _MultipleEnumBasesWithCustomNew(int, EnumWithCustomNew, SecondEnumWithCustomNew):
pass
# Wrong Enums:
class TwoDataTypesViaInheritance(Second, Correct2): # E: Only a single data type mixin is allowed for Enum subtypes, found extra "__main__.Correct2"
pass
class TwoDataTypesViaInheritanceAndMixin(Second, Correct2, Mixin): # E: No non-enum mixin classes are allowed after "__main__.Correct2" \
# E: Only a single data type mixin is allowed for Enum subtypes, found extra "__main__.Correct2"
pass
class MixinAfterEnum1(enum.Enum, Mixin): # E: No non-enum mixin classes are allowed after "enum.Enum"
pass
class MixinAfterEnum2(First, enum.Enum, Mixin): # E: No non-enum mixin classes are allowed after "enum.Enum"
pass
class TwoDataTypes(First, Second, enum.Enum): # E: Only a single data type mixin is allowed for Enum subtypes, found extra "__main__.Second"
pass
class TwoDataTypesAndIntEnumMixin(First, Second, enum.IntEnum, Mixin): # E: No non-enum mixin classes are allowed after "enum.IntEnum" \
# E: Only a single data type mixin is allowed for Enum subtypes, found extra "__main__.Second"
pass
class ThreeDataTypes(First, Second, Third, enum.Enum): # E: Only a single data type mixin is allowed for Enum subtypes, found extra "__main__.Second" \
# E: Only a single data type mixin is allowed for Enum subtypes, found extra "__main__.Third"
pass
class ThreeDataTypesAndMixin(First, Second, Third, enum.Enum, Mixin): # E: No non-enum mixin classes are allowed after "enum.Enum" \
# E: Only a single data type mixin is allowed for Enum subtypes, found extra "__main__.Second" \
# E: Only a single data type mixin is allowed for Enum subtypes, found extra "__main__.Third"
pass
class FromEnumAndOther1(Correct2, Second, enum.Enum): # E: No non-enum mixin classes are allowed after "__main__.Correct2" \
# E: Only a single data type mixin is allowed for Enum subtypes, found extra "__main__.Second"
pass
class FromEnumAndOther2(Correct2, Second): # E: No non-enum mixin classes are allowed after "__main__.Correct2" \
# E: Only a single data type mixin is allowed for Enum subtypes, found extra "__main__.Second"
pass
[builtins fixtures/tuple.pyi]
[case testRegression12258]
from enum import Enum
class MyEnum(Enum): ...
class BytesEnum(bytes, MyEnum): ... # Should be ok
[builtins fixtures/tuple.pyi]
[case testEnumWithNewHierarchy]
import enum
class A:
def __new__(cls, val): ...
class B(A):
def __new__(cls, val): ...
class C:
def __new__(cls, val): ...
class E1(A, enum.Enum): ...
class E2(B, enum.Enum): ...
# Errors:
class W1(C, E1): ... # E: Only a single data type mixin is allowed for Enum subtypes, found extra "__main__.E1"
class W2(C, E2): ... # E: Only a single data type mixin is allowed for Enum subtypes, found extra "__main__.E2"
[builtins fixtures/tuple.pyi]
[case testEnumValueUnionSimplification]
from enum import IntEnum
from typing import Any
class C(IntEnum):
X = 0
Y = 1
Z = 2
def f1(c: C) -> None:
x = {'x': c.value}
reveal_type(x) # N: Revealed type is "builtins.dict[builtins.str, builtins.int]"
def f2(c: C, a: Any) -> None:
x = {'x': c.value, 'y': a}
reveal_type(x) # N: Revealed type is "builtins.dict[builtins.str, Any]"
y = {'y': a, 'x': c.value}
reveal_type(y) # N: Revealed type is "builtins.dict[builtins.str, Any]"
[builtins fixtures/dict.pyi]
[case testEnumIgnoreIsDeleted]
from enum import Enum
class C(Enum):
_ignore_ = 'X'
C._ignore_ # E: "type[C]" has no attribute "_ignore_"
[builtins fixtures/enum.pyi]
[case testCanOverrideDunderAttributes]
import typing
from enum import Enum, Flag
class BaseEnum(Enum):
__dunder__ = 1
__labels__: typing.Dict[int, str]
class Override(BaseEnum):
__dunder__ = 2
__labels__ = {1: "1"}
Override.__dunder__ = 3
BaseEnum.__dunder__ = 3
Override.__labels__ = {2: "2"}
class FlagBase(Flag):
__dunder__ = 1
__labels__: typing.Dict[int, str]
class FlagOverride(FlagBase):
__dunder__ = 2
__labels = {1: "1"}
FlagOverride.__dunder__ = 3
FlagBase.__dunder__ = 3
FlagOverride.__labels__ = {2: "2"}
[builtins fixtures/dict.pyi]
[case testCanNotInitialize__members__]
import typing
from enum import Enum
class WritingMembers(Enum):
__members__: typing.Dict[Enum, Enum] = {} # E: Assigned "__members__" will be overridden by "Enum" internally
class OnlyAnnotatedMembers(Enum):
__members__: typing.Dict[Enum, Enum]
[builtins fixtures/dict.pyi]
[case testCanOverrideDunderOnNonFirstBaseEnum]
import typing
from enum import Enum
class Some:
__labels__: typing.Dict[int, str]
class A(Some, Enum):
__labels__ = {1: "1"}
[builtins fixtures/dict.pyi]
[case testEnumWithPartialTypes]
from enum import Enum
class Mixed(Enum):
a = [] # E: Need type annotation for "a" (hint: "a: list[<type>] = ...")
b = None
def check(self) -> None:
reveal_type(Mixed.a.value) # N: Revealed type is "builtins.list[Any]"
reveal_type(Mixed.b.value) # N: Revealed type is "None"
# Inferring Any here instead of a union seems to be a deliberate
# choice; see the testEnumValueInhomogeneous case above.
reveal_type(self.value) # N: Revealed type is "Any"
for field in Mixed:
reveal_type(field.value) # N: Revealed type is "Any"
if field.value is None:
pass
class AllPartialList(Enum):
a = [] # E: Need type annotation for "a" (hint: "a: list[<type>] = ...")
b = [] # E: Need type annotation for "b" (hint: "b: list[<type>] = ...")
def check(self) -> None:
reveal_type(self.value) # N: Revealed type is "builtins.list[Any]"
[builtins fixtures/tuple.pyi]
[case testEnumPrivateAttributeNotMember]
from enum import Enum
class MyEnum(Enum):
A = 1
B = 2
__my_dict = {A: "ham", B: "spam"}
# TODO: change the next line to use MyEnum._MyEnum__my_dict when mypy implements name mangling
x: MyEnum = MyEnum.__my_dict # E: Incompatible types in assignment (expression has type "dict[int, str]", variable has type "MyEnum")
[builtins fixtures/enum.pyi]
[case testEnumWithPrivateAttributeReachability]
# flags: --warn-unreachable
from enum import Enum
class MyEnum(Enum):
A = 1
B = 2
__my_dict = {A: "ham", B: "spam"}
e: MyEnum
if e == MyEnum.A:
reveal_type(e) # N: Revealed type is "Literal[__main__.MyEnum.A]"
elif e == MyEnum.B:
reveal_type(e) # N: Revealed type is "Literal[__main__.MyEnum.B]"
else:
reveal_type(e) # E: Statement is unreachable
[builtins fixtures/dict.pyi]
[case testEnumNonMemberSupport]
# flags: --python-version 3.11
# This was added in 3.11
from enum import Enum, nonmember
class My(Enum):
a = 1
b = 2
c = nonmember(3)
reveal_type(My.a) # N: Revealed type is "Literal[__main__.My.a]?"
reveal_type(My.b) # N: Revealed type is "Literal[__main__.My.b]?"
reveal_type(My.c) # N: Revealed type is "builtins.int"
def accepts_my(my: My):
reveal_type(my.value) # N: Revealed type is "Union[Literal[1]?, Literal[2]?]"
class Other(Enum):
a = 1
@nonmember
class Support:
b = 2
reveal_type(Other.a) # N: Revealed type is "Literal[__main__.Other.a]?"
reveal_type(Other.Support.b) # N: Revealed type is "builtins.int"
[builtins fixtures/dict.pyi]
[case testEnumMemberSupport]
# flags: --python-version 3.11
# This was added in 3.11
from enum import Enum, member
class A(Enum):
x = member(1)
y = 2
reveal_type(A.x) # N: Revealed type is "Literal[__main__.A.x]?"
reveal_type(A.x.value) # N: Revealed type is "Literal[1]?"
reveal_type(A.y) # N: Revealed type is "Literal[__main__.A.y]?"
reveal_type(A.y.value) # N: Revealed type is "Literal[2]?"
def some_a(a: A):
reveal_type(a.value) # N: Revealed type is "Union[Literal[1]?, Literal[2]?]"
[builtins fixtures/dict.pyi]
[case testEnumMemberAndNonMemberSupport]
# flags: --python-version 3.11 --warn-unreachable
# This was added in 3.11
from enum import Enum, member, nonmember
class A(Enum):
x = 1
y = member(2)
z = nonmember(3)
def some_a(a: A):
if a is not A.x and a is not A.z:
reveal_type(a) # N: Revealed type is "Literal[__main__.A.y]"
if a is not A.y and a is not A.z:
reveal_type(a) # N: Revealed type is "Literal[__main__.A.x]"
if a is not A.x:
reveal_type(a) # N: Revealed type is "Literal[__main__.A.y]"
if a is not A.y:
reveal_type(a) # N: Revealed type is "Literal[__main__.A.x]"
[builtins fixtures/dict.pyi]
[case testEnumAccessFromInstance]
# flags: --python-version 3.11 --warn-unreachable
# This was added in 3.11
from enum import Enum, member, nonmember
class A(Enum):
x = 1
y = member(2)
z = nonmember(3)
reveal_type(A.x) # N: Revealed type is "Literal[__main__.A.x]?"
reveal_type(A.y) # N: Revealed type is "Literal[__main__.A.y]?"
reveal_type(A.z) # N: Revealed type is "builtins.int"
reveal_type(A.x.x) # N: Revealed type is "Literal[__main__.A.x]?"
reveal_type(A.x.x.x) # N: Revealed type is "Literal[__main__.A.x]?"
reveal_type(A.x.y) # N: Revealed type is "Literal[__main__.A.y]?"
reveal_type(A.x.y.y) # N: Revealed type is "Literal[__main__.A.y]?"
reveal_type(A.x.z) # N: Revealed type is "builtins.int"
reveal_type(A.y.x) # N: Revealed type is "Literal[__main__.A.x]?"
reveal_type(A.y.y) # N: Revealed type is "Literal[__main__.A.y]?"
reveal_type(A.y.z) # N: Revealed type is "builtins.int"
A.z.x # E: "int" has no attribute "x"
class B(Enum):
x = 1
value = 2
reveal_type(B.x) # N: Revealed type is "Literal[__main__.B.x]?"
reveal_type(B.x.value) # N: Revealed type is "Literal[2]?"
reveal_type(B.x.x.value) # N: Revealed type is "Literal[2]?"
B.x.value.value # E: "int" has no attribute "value"
B.x.value.value.value # E: "int" has no attribute "value"
reveal_type(B.value) # N: Revealed type is "Literal[__main__.B.value]?"
reveal_type(B.value.x) # N: Revealed type is "Literal[__main__.B.x]?"
reveal_type(B.value.x.x) # N: Revealed type is "Literal[__main__.B.x]?"
reveal_type(B.value.x.value) # N: Revealed type is "Literal[2]?"
B.value.x.value.value # E: "int" has no attribute "value"
B.value.value.value # E: "int" has no attribute "value"
[builtins fixtures/dict.pyi]
[case testErrorOnAnnotatedMember]
from enum import Enum
class Medal(Enum):
gold: int = 1 # E: Enum members must be left unannotated \
# N: See https://typing.readthedocs.io/en/latest/spec/enums.html#defining-members
silver: str = 2 # E: Enum members must be left unannotated \
# N: See https://typing.readthedocs.io/en/latest/spec/enums.html#defining-members \
# E: Incompatible types in assignment (expression has type "int", variable has type "str")
bronze = 3
[builtins fixtures/enum.pyi]
[case testEnumMemberWithPlaceholder]
from enum import Enum
class Pet(Enum):
CAT = ...
DOG: str = ... # E: Enum members must be left unannotated \
# N: See https://typing.readthedocs.io/en/latest/spec/enums.html#defining-members \
# E: Incompatible types in assignment (expression has type "ellipsis", variable has type "str")
[builtins fixtures/enum.pyi]
[case testEnumValueWithPlaceholderNodeType]
# https://github.com/python/mypy/issues/11971
from enum import Enum
from typing import Any, Callable, Dict
class Foo(Enum):
Bar: Foo = Callable[[str], None] # E: Enum members must be left unannotated \
# N: See https://typing.readthedocs.io/en/latest/spec/enums.html#defining-members \
# E: Incompatible types in assignment (expression has type "<typing special form>", variable has type "Foo")
Baz: Any = Callable[[Dict[str, "Missing"]], None] # E: Enum members must be left unannotated \
# N: See https://typing.readthedocs.io/en/latest/spec/enums.html#defining-members \
# E: Type application targets a non-generic function or class \
# E: Name "Missing" is not defined
reveal_type(Foo.Bar) # N: Revealed type is "Literal[__main__.Foo.Bar]?"
reveal_type(Foo.Bar.value) # N: Revealed type is "__main__.Foo"
reveal_type(Foo.Baz) # N: Revealed type is "Literal[__main__.Foo.Baz]?"
reveal_type(Foo.Baz.value) # N: Revealed type is "Any"
[builtins fixtures/tuple.pyi]
[typing fixtures/typing-full.pyi]
[case testEnumWithOnlyImplicitMembersUsingAnnotationOnly]
# flags: --warn-unreachable
import enum
class E(enum.IntEnum):
A: int
B: int
def do_check(value: E) -> None:
reveal_type(value) # N: Revealed type is "__main__.E"
# this is a nonmember check, not an emum member check, and it should not narrow the value
if value is E.A:
return
reveal_type(value) # N: Revealed type is "__main__.E"
"should be reachable"
[builtins fixtures/primitives.pyi]
[typing fixtures/typing-full.pyi]
[case testStrEnumClassCorrectIterable]
from enum import StrEnum
from typing import Type, TypeVar
class Choices(StrEnum):
LOREM = "lorem"
IPSUM = "ipsum"
var = list(Choices)
reveal_type(var) # N: Revealed type is "builtins.list[__main__.Choices]"
e: type[StrEnum]
reveal_type(list(e)) # N: Revealed type is "builtins.list[enum.StrEnum]"
T = TypeVar("T", bound=StrEnum)
def list_vals(e: Type[T]) -> list[T]:
reveal_type(list(e)) # N: Revealed type is "builtins.list[T`-1]"
return list(e)
reveal_type(list_vals(Choices)) # N: Revealed type is "builtins.list[__main__.Choices]"
[builtins fixtures/enum.pyi]
[case testEnumAsClassMemberNoCrash]
# https://github.com/python/mypy/issues/18736
from enum import Enum
class Base:
def __init__(self, namespace: tuple[str, ...]) -> None:
# Not a bug: trigger defer
names = [name for name in namespace if fail] # E: Name "fail" is not defined
self.o = Enum("o", names) # E: Enum type as attribute is not supported \
# E: Second argument of Enum() must be string, tuple, list or dict literal for mypy to determine Enum members
[builtins fixtures/tuple.pyi]
[case testSingleUnderscoreNameEnumMember]
# flags: --warn-unreachable
# https://github.com/python/mypy/issues/19271
from enum import Enum
class Things(Enum):
_ = "under score"
def check(thing: Things) -> None:
if thing is Things._:
return None
return None # E: Statement is unreachable
[builtins fixtures/enum.pyi]
[case testSunderValueTypeEllipsis]
from foo.bar import (
Basic, FromStub, InheritedInt, InheritedStr, InheritedFlag,
InheritedIntFlag, Wrapper
)
reveal_type(Basic.FOO) # N: Revealed type is "Literal[foo.bar.Basic.FOO]?"
reveal_type(Basic.FOO.value) # N: Revealed type is "Literal[1]?"
reveal_type(Basic.FOO._value_) # N: Revealed type is "builtins.int"
reveal_type(FromStub.FOO) # N: Revealed type is "Literal[foo.bar.FromStub.FOO]?"
reveal_type(FromStub.FOO.value) # N: Revealed type is "builtins.int"
reveal_type(FromStub.FOO._value_) # N: Revealed type is "builtins.int"
reveal_type(Wrapper.Nested.FOO) # N: Revealed type is "Literal[foo.bar.Wrapper.Nested.FOO]?"
reveal_type(Wrapper.Nested.FOO.value) # N: Revealed type is "builtins.int"
reveal_type(Wrapper.Nested.FOO._value_) # N: Revealed type is "builtins.int"
reveal_type(InheritedInt.FOO) # N: Revealed type is "Literal[foo.bar.InheritedInt.FOO]?"
reveal_type(InheritedInt.FOO.value) # N: Revealed type is "builtins.int"
reveal_type(InheritedInt.FOO._value_) # N: Revealed type is "builtins.int"
reveal_type(InheritedStr.FOO) # N: Revealed type is "Literal[foo.bar.InheritedStr.FOO]?"
reveal_type(InheritedStr.FOO.value) # N: Revealed type is "builtins.str"
reveal_type(InheritedStr.FOO._value_) # N: Revealed type is "builtins.str"
reveal_type(InheritedFlag.FOO) # N: Revealed type is "Literal[foo.bar.InheritedFlag.FOO]?"
reveal_type(InheritedFlag.FOO.value) # N: Revealed type is "builtins.int"
reveal_type(InheritedFlag.FOO._value_) # N: Revealed type is "builtins.int"
reveal_type(InheritedIntFlag.FOO) # N: Revealed type is "Literal[foo.bar.InheritedIntFlag.FOO]?"
reveal_type(InheritedIntFlag.FOO.value) # N: Revealed type is "builtins.int"
reveal_type(InheritedIntFlag.FOO._value_) # N: Revealed type is "builtins.int"
[file foo/__init__.pyi]
[file foo/bar/__init__.pyi]
from enum import Enum, IntEnum, StrEnum, Flag, IntFlag
class Basic(Enum):
_value_: int
FOO = 1
class FromStub(Enum):
_value_: int
FOO = ...
class Wrapper:
class Nested(Enum):
_value_: int
FOO = ...
class InheritedInt(IntEnum):
FOO = ...
class InheritedStr(StrEnum):
FOO = ...
class InheritedFlag(Flag):
FOO = ...
class InheritedIntFlag(IntFlag):
FOO = ...
[builtins fixtures/enum.pyi]
[case testSunderValueTypeEllipsisNonStub]
from enum import Enum, StrEnum
class Basic(Enum):
_value_: int
FOO = 1
reveal_type(Basic.FOO) # N: Revealed type is "Literal[__main__.Basic.FOO]?"
reveal_type(Basic.FOO.value) # N: Revealed type is "Literal[1]?"
reveal_type(Basic.FOO._value_) # N: Revealed type is "builtins.int"
# TODO: this and below should produce diagnostics, Ellipsis is not assignable to int
# Now we do not check members against _value_ at all.
class FromStub(Enum):
_value_: int
FOO = ...
reveal_type(FromStub.FOO) # N: Revealed type is "Literal[__main__.FromStub.FOO]?"
reveal_type(FromStub.FOO.value) # N: Revealed type is "builtins.ellipsis"
reveal_type(FromStub.FOO._value_) # N: Revealed type is "builtins.int"
class InheritedStr(StrEnum):
FOO = ...
reveal_type(InheritedStr.FOO) # N: Revealed type is "Literal[__main__.InheritedStr.FOO]?"
reveal_type(InheritedStr.FOO.value) # N: Revealed type is "builtins.ellipsis"
reveal_type(InheritedStr.FOO._value_) # N: Revealed type is "builtins.ellipsis"
class Wrapper:
class Nested(StrEnum):
FOO = ...
reveal_type(Wrapper.Nested.FOO) # N: Revealed type is "Literal[__main__.Wrapper.Nested.FOO]?"
reveal_type(Wrapper.Nested.FOO.value) # N: Revealed type is "builtins.ellipsis"
reveal_type(Wrapper.Nested.FOO._value_) # N: Revealed type is "builtins.ellipsis"
[builtins fixtures/enum.pyi]
|