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
|
<!--
Autogenerated! Do not modify!
See the "Updating Documentation" section of the README file for more info.
-->
# Available Checks
## FURB100: `use-pathlib-with-suffix`
Categories: `pathlib`
A common operation is changing the extension of a file. If you have an
existing `Path` object, you don't need to convert it to a string, slice
it, and append a new extension. Instead, use the `with_suffix()` method:
Bad:
```python
new_filepath = str(Path("file.txt"))[:4] + ".md"
```
Good:
```python
new_filepath = Path("file.txt").with_suffix(".md")
```
## FURB101: `use-pathlib-read-text-read-bytes`
Categories: `pathlib`
When you just want to save the contents of a file to a variable, using a
`with` block is a bit overkill. A simpler alternative is to use pathlib's
`read_text()` function:
Bad:
```python
with open(filename) as f:
contents = f.read()
```
Good:
```python
contents = Path(filename).read_text()
```
## FURB102: `use-startswith-endswith-tuple`
Categories: `string`
`startswith()` and `endswith()` both take a tuple, so instead of calling
`startswith()` multiple times on the same string, you can check them all
at once:
Bad:
```python
name = "bob"
if name.startswith("b") or name.startswith("B"):
pass
```
Good:
```python
name = "bob"
if name.startswith(("b", "B")):
pass
```
## FURB103: `use-pathlib-write-text-write-bytes`
Categories: `pathlib`
When you just want to save some contents to a file, using a `with` block is
a bit overkill. Instead you can use pathlib's `write_text()` method:
Bad:
```python
with open(filename, "w") as f:
f.write("hello world")
```
Good:
```python
Path(filename).write_text("hello world")
```
## FURB104: `use-pathlib-cwd`
Categories: `pathlib`
A modern alternative to `os.getcwd()` is the `Path.cwd()` method:
Bad:
```python
cwd = os.getcwd()
```
Good:
```python
cwd = Path.cwd()
```
## FURB105: `simplify-print`
Categories: `builtin` `readability`
`print("")` can be simplified to just `print()`.
## FURB106: `use-expandtabs`
Categories: `string`
If you want to expand the tabs at the start of a string, don't use
`.replace("\t", " " * 8)`, use `.expandtabs()` instead. Note that this
only works if the tabs are at the start of the string, since `expandtabs()`
will expand each tab to the nearest tab column.
Bad:
```python
spaces_8 = "\thello world".replace("\t", " " * 8)
spaces_4 = "\thello world".replace("\t", " ")
```
Good:
```python
spaces_8 = "\thello world".expandtabs()
spaces_4 = "\thello world".expandtabs(4)
```
## FURB107: `use-with-suppress`
Categories: `contextlib` `readability`
Often times you want to handle an exception and just ignore it. You can do
this with a `try`/`except` block with a single `pass` in the `except`
block, but there is a simpler and more concise way using the `suppress()`
function from `contextlib`:
Bad:
```python
try:
f()
except FileNotFoundError:
pass
```
Good:
```python
with suppress(FileNotFoundError):
f()
```
Note: `suppress()` is slower than using `try`/`except`, so for performance
critical code you might consider ignoring this check.
## FURB108: `use-in-oper`
Categories: `logical` `readability`
When comparing a value to multiple possible options, don't `or` multiple
comparison checks, use a single `in` expr:
Bad:
```python
if x == "abc" or x == "def":
pass
```
Good:
```python
if x in ("abc", "def"):
pass
```
Note: This should not be used if the operands depend on boolean short
circuiting, since the operands will be eagerly evaluated. This is primarily
useful for comparing against a range of constant values.
## FURB109: `use-consistent-in-bracket`
Categories: `iterable` `readability`
Since tuple, list, and set literals can be used with the `in` operator, it
is best to pick one and stick with it.
Bad:
```python
for x in (1, 2, 3):
pass
nums = [str(x) for x in [1, 2, 3]]
```
Good:
```python
for x in (1, 2, 3):
pass
nums = [str(x) for x in (1, 2, 3)]
```
## FURB110: `use-or-oper`
Categories: `logical` `readability`
Sometimes the ternary operator (aka, inline if statements) can be
simplified to a single `or` expression.
Bad:
```python
z = x if x else y
```
Good:
```python
z = x or y
```
Note: if `x` depends on side-effects, then this check should be ignored.
## FURB111: `use-func-name`
Categories: `readability`
Don't use a lambda if it is just forwarding its arguments to a
function verbatim:
Bad:
```python
predicate = lambda x: bool(x)
some_func(lambda x, y: print(x, y))
```
Good:
```python
predicate = bool
some_func(print)
```
## FURB112: `use-literal`
Categories: `pythonic` `readability`
Using `list` and `dict` without any arguments is slower, and not Pythonic.
Use `[]` and `{}` instead:
Bad:
```python
nums = list()
books = dict()
```
Good:
```python
nums = []
books = {}
```
## FURB113: `use-list-extend`
Categories: `list`
When appending multiple values to a list, you can use the `.extend()`
method to add an iterable to the end of an existing list. This way, you
don't have to call `.append()` on every element:
Bad:
```python
nums = [1, 2, 3]
nums.append(4)
nums.append(5)
nums.append(6)
```
Good:
```python
nums = [1, 2, 3]
nums.extend((4, 5, 6))
```
## FURB114: `no-double-not`
Categories: `builtin` `readability` `truthy`
Double negatives are confusing, so use `bool(x)` instead of `not not x`.
Bad:
```python
if not not value:
pass
```
Good:
```python
if value:
pass
```
## FURB115: `no-len-compare`
Categories: `iterable` `truthy`
Don't check a container's length to determine if it is empty or not, use
a truthiness check instead:
Bad:
```python
name = "bob"
if len(name) == 0:
pass
nums = [1, 2, 3]
if len(nums) >= 1:
pass
```
Good:
```python
name = "bob"
if not name:
pass
nums = [1, 2, 3]
if nums:
pass
```
## FURB116: `use-fstring-number-format`
Categories: `builtin` `fstring`
The `bin()`, `oct()`, and `hex()` functions return the string
representation of a number but with a prefix attached. If you don't want
the prefix, you might be tempted to just slice it off, but using an
f-string will give you more flexibility and let you work with negative
numbers:
Bad:
```python
print(bin(1337)[2:])
```
Good:
```python
print(f"{1337:b}")
```
## FURB117: `use-pathlib-open`
Categories: `pathlib`
When you want to open a Path object, don't pass it to `open()`, just call
`.open()` on the Path object itself:
Bad:
```python
path = Path("filename")
with open(path) as f:
pass
```
Good:
```python
path = Path("filename")
with path.open() as f:
pass
```
## FURB118: `use-operator`
Categories: `operator`
Don't write lambdas/functions to wrap builtin operators, use the `operator`
module instead:
Bad:
```python
from functools import reduce
nums = [1, 2, 3]
print(reduce(lambda x, y: x + y, nums)) # 6
```
Good:
```python
from functools import reduce
from operator import add
nums = [1, 2, 3]
print(reduce(add, nums)) # 6
```
## FURB119: `use-fstring-format`
Categories: `builtin` `fstring`
Certain expressions which are passed to f-strings are redundant because
the f-string itself is capable of formatting it. For example:
Bad:
```python
print(f"{bin(1337)}")
print(f"{ascii(input())}")
print(f"{str(123)}")
```
Good:
```python
print(f"{1337:#b}")
print(f"{input()!a}")
print(f"{123}")
```
## FURB120: `use-implicit-default`
Categories:
Don't pass an argument if it is the same as the default value:
Bad:
```python
def greet(name: str = "bob") -> None:
print(f"Hello {name}")
greet("bob")
{}.get("some key", None)
```
Good:
```python
def greet(name: str = "bob") -> None:
print(f"Hello {name}")
greet()
{}.get("some key")
```
## FURB121: `use-isinstance-issubclass-tuple`
Categories: `python310` `readability`
`isinstance()` and `issubclass()` both take tuple arguments, so instead of
calling them multiple times for the same object, you can check all of them
at once:
Bad:
```python
if isinstance(num, float) or isinstance(num, int):
pass
```
Good:
```python
if isinstance(num, (float, int)):
pass
```
Note: In Python 3.10+, you can also pass type unions as the second param to
these functions:
```python
if isinstance(num, float | int):
pass
```
## FURB122: `use-writelines`
Categories: `builtin` `readability`
When you want to write a list of lines to a file, don't call `.write()`
for every line, use `.writelines()` instead:
Bad:
```python
lines = ["line 1\n", "line 2\n", "line 3\n"]
with open("file") as f:
for line in lines:
f.write(line)
```
Good:
```python
lines = ["line 1\n", "line 2\n", "line 3\n"]
with open("file") as f:
f.writelines(lines)
```
Note: If you have a more complex expression then just `lines`, you may
need to use a list comprehension instead. For example:
```python
f.writelines(f"{line}\n" for line in lines)
```
## FURB123: `no-redundant-cast`
Categories: `readability`
Don't cast a variable or literal if it is already of that type. This
usually is the result of not realizing a type is already the type you want,
or artifacts of some debugging code. One example of where this might be
intentional is when using container types like `dict` or `list`, which
will create a shallow copy. If that is the case, it might be preferable
to use `.copy()` instead, since it makes it more explicit that a copy
is taking place.
Examples:
Bad:
```python
name = str("bob")
num = int(123)
ages = {"bob": 123}
copy = dict(ages)
```
Good:
```python
name = "bob"
num = 123
ages = {"bob": 123}
copy = ages.copy()
```
## FURB124: `use-comparison-chain`
Categories: `logical` `readability`
When checking that multiple objects are equal to each other, don't use
an `and` expression. Use a comparison chain instead, for example:
Bad:
```python
if x == y and x == z:
pass
# and
if x is None and y is None
pass
```
Good:
```python
if x == y == z:
pass
# and
if x is y is None:
pass
```
Note: if `x` depends on side-effects, then this check should be ignored.
## FURB125: `no-redundant-return`
Categories: `control-flow` `readability`
Don't explicitly return if you are already at the end of the control flow
for the current function:
Bad:
```python
def func():
print("hello world!")
return
def func2(x):
if x == 1:
print("x is 1")
else:
print("x is not 1")
return
```
Good:
```python
def func():
print("hello world!")
def func2(x):
if x == 1:
print("x is 1")
else:
print("x is not 1")
```
## FURB126: `simplify-return`
Categories: `control-flow` `readability`
Sometimes a return statement can be written more succinctly:
Bad:
```python
def index_or_default(nums: list[Any], index: int, default: Any):
if index >= len(nums):
return default
else:
return nums[index]
def is_on_axis(position: tuple[int, int]) -> bool:
match position:
case (0, _) | (_, 0):
return True
case _:
return False
```
Good:
```python
def index_or_default(nums: list[Any], index: int, default: Any):
if index >= len(nums):
return default
return nums[index]
def is_on_axis(position: tuple[int, int]) -> bool:
match position:
case (0, _) | (_, 0):
return True
return False
```
## FURB127: `no-with-assign`
Categories: `readability` `scoping`
Due to Python's scoping rules, you can use a variable that has gone "out
of scope" so long as all previous code paths can bind to it. Long story
short, you don't need to declare a variable before you assign it in a
`with` statement:
Bad:
```python
x = ""
with open("file.txt") as f:
x = f.read()
```
Good:
```python
with open("file.txt") as f:
x = f.read()
```
## FURB128: `use-tuple-unpack-swap`
Categories: `readability`
You don't need to use a temporary variable to swap 2 variables, you can use
tuple unpacking instead:
Bad:
```python
temp = x
x = y
y = temp
```
Good:
```python
x, y = y, x
```
## FURB129: `simplify-readlines`
Categories: `builtin` `readability`
When iterating over a file object line-by-line you don't need to add
`.readlines()`, simply iterate over the object itself. This assumes you
aren't passing an argument to readlines().
Bad:
```python
with open("file.txt") as f:
for line in f.readlines():
...
```
Good:
```python
with open("file.txt") as f:
for line in f:
...
```
## FURB130: `no-in-dict-keys`
Categories: `dict` `readability`
If you only want to check if a key exists in a dictionary, you don't need
to call `.keys()` first, just use `in` on the dictionary itself:
Bad:
```python
d = {"key": "value"}
if "key" in d.keys():
...
```
Good:
```python
d = {"key": "value"}
if "key" in d:
...
```
## FURB131: `no-del`
Categories: `builtin` `readability`
The `del` statement is commonly used for popping single elements from dicts
and lists, though a slice can be used to remove a range of elements
instead. When removing all elements via a slice, use the faster and more
succinct `.clear()` method instead.
Bad:
```python
names = {"key": "value"}
nums = [1, 2, 3]
del names[:]
del nums[:]
```
Good:
```python
names = {"key": "value"}
nums = [1, 2, 3]
names.clear()
nums.clear()
```
## FURB132: `use-set-discard`
Categories: `readability` `set`
If you want to remove a value from a set regardless of whether it exists or
not, use the `discard()` method instead of `remove()`:
Bad:
```python
nums = {123, 456}
if 123 in nums:
nums.remove(123)
```
Good:
```python
nums = {123, 456}
nums.discard(123)
```
## FURB133: `no-redundant-continue`
Categories: `control-flow` `readability`
Don't explicitly continue if you are already at the end of the control flow
for the current for/while loop:
Bad:
```python
def func():
for _ in range(10):
print("hello world!")
continue
def func2(x):
for x in range(10):
if x == 1:
print("x is 1")
else:
print("x is not 1")
continue
```
Good:
```python
def func():
for _ in range(10):
print("hello world!")
def func2(x):
for x in range(10):
if x == 1:
print("x is 1")
else:
print("x is not 1")
```
## FURB134: `use-cache`
Categories: `functools` `python39` `readability`
Python 3.9 introduces the `@cache` decorator which can be used as a
short-hand for `@lru_cache(maxsize=None)`.
Bad:
```python
from functools import lru_cache
@lru_cache(maxsize=None)
def f(x: int) -> int:
return x + 1
```
Good:
```python
from functools import cache
@cache
def f(x: int) -> int:
return x + 1
```
## FURB135: `no-ignored-dict-items`
Categories: `dict`
Don't use `.items()` on a `dict` if you only care about the keys or the
values, but not both:
Bad:
```python
books = {"Frank Herbert": "Dune"}
for author, _ in books.items():
print(author)
for _, book in books.items():
print(book)
```
Good:
```python
books = {"Frank Herbert": "Dune"}
for author in books:
print(author)
for book in books.values():
print(book)
```
## FURB136: `use-min-max`
Categories: `builtin` `logical` `readability`
Certain ternary expressions can be written more succinctly using the
builtin `min`/`max` functions:
Bad:
```python
score1 = 90
score2 = 99
highest_score = score1 if score1 > score2 else score2
```
Good:
```python
score1 = 90
score2 = 99
highest_score = max(score1, score2)
```
## FURB137: `simplify-comprehension`
Categories: `builtin` `iterable` `readability`
Often times generator expressions and list/set/dict comprehensions can be
written more succinctly. For example, passing a list comprehension to a
function when a generator expression would suffice, or using the shorthand
notation in the case of `list` and `set`. For example:
Bad:
```python
nums = [1, 1, 2, 3]
nums_times_10 = list(num * 10 for num in nums)
unique_squares = set(num ** 2 for num in nums)
number_tuple = tuple([num ** 2 for num in nums])
```
Good:
```python
nums = [1, 1, 2, 3]
nums_times_10 = [num * 10 for num in nums]
unique_squares = {num ** 2 for num in nums}
number_tuple = tuple(num ** 2 for num in nums)
```
## FURB138: `use-list-comprehension`
Categories: `performance` `readability`
When constructing a new list it is usually more performant to use a list
comprehension, and in some cases, it can be more readable.
Bad:
```python
nums = [1, 2, 3, 4]
odds = []
for num in nums:
if num % 2:
odds.append(num)
```
Good:
```python
nums = [1, 2, 3, 4]
odds = [num for num in nums if num % 2]
```
## FURB139: `no-multiline-strip`
Categories: `readability`
If you want to define a multi-line string but don't want a leading/trailing
newline, use a continuation character ('\') instead of calling `lstrip()`,
`rstrip()`, or `strip()`.
Bad:
```python
"""
This is some docstring
""".lstrip()
"""
This is another docstring
""".strip()
```
Good:
```python
"""\
This is some docstring
"""
"""\
This is another docstring\
"""
```
## FURB140: `use-starmap`
Categories: `itertools` `performance`
If you only want to iterate and unpack values so that you can pass them
to a function (in the same order and with no modifications), you should
use the more performant `starmap` function:
Bad:
```python
scores = [85, 100, 60]
passing_scores = [60, 80, 70]
def passed_test(score: int, passing_score: int) -> bool:
return score >= passing_score
passed_all_tests = all(
passed_test(score, passing_score)
for score, passing_score
in zip(scores, passing_scores)
)
```
Good:
```python
from itertools import starmap
scores = [85, 100, 60]
passing_scores = [60, 80, 70]
def passed_test(score: int, passing_score: int) -> bool:
return score >= passing_score
passed_all_tests = all(starmap(passed_test, zip(scores, passing_scores)))
```
## FURB141: `use-pathlib-exists`
Categories: `pathlib`
When checking whether a file exists or not, try and use the more modern
`pathlib` module instead of `os.path`.
Bad:
```python
import os
if os.path.exists("filename"):
pass
```
Good:
```python
from pathlib import Path
if Path("filename").exists():
pass
```
## FURB142: `no-set-for-loop`
Categories: `builtin`
When you want to add/remove a bunch of items to/from a set, don't use a for
loop, call the appropriate method on the set itself.
Bad:
```python
sentence = "hello world"
vowels = "aeiou"
letters = set(sentence)
for vowel in vowels:
letters.discard(vowel)
```
Good:
```python
sentence = "hello world"
vowels = "aeiou"
letters = set(sentence)
letters.difference_update(vowels)
```
## FURB143: `no-default-or`
Categories: `logical` `readability`
Don't check an expression to see if it is falsey then assign the same
falsey value to it. For example, if an expression used to be of type
`int | None`, checking if the expression is falsey would make sense,
since it could be `None` or `0`. But, if the expression is changed to
be of type `int`, the falsey value is just `0`, so setting it to `0`
if it is falsey (`0`) is redundant.
Bad:
```python
def is_markdown_header(line: str) -> bool:
return (line or "").startswith("#")
```
Good:
```python
def is_markdown_header(line: str) -> bool:
return line.startswith("#")
```
## FURB144: `use-pathlib-unlink`
Categories: `pathlib`
When removing a file, use the more modern `Path.unlink()` method instead of
`os.remove()` or `os.unlink()`: The `pathlib` module allows for more
flexibility when it comes to traversing folders, building file paths, and
accessing/modifying files.
Bad:
```python
import os
os.remove("filename")
```
Good:
```python
from pathlib import Path
Path("filename").unlink()
```
## FURB145: `no-slice-copy`
Categories: `readability`
Don't use a slice expression (with no bounds) to make a copy of something,
use the more readable `.copy()` method instead:
Bad:
```python
nums = [3.1415, 1234]
copy = nums[:]
```
Good:
```python
nums = [3.1415, 1234]
copy = nums.copy()
```
## FURB146: `use-pathlib-is-funcs`
Categories: `pathlib`
Don't use the `os.path.isfile` (or similar) functions, use the more modern
`pathlib` module instead:
Bad:
```python
if os.path.isfile("file.txt"):
pass
```
Good:
```python
if Path("file.txt").is_file():
pass
```
## FURB147: `no-path-join`
Categories: `pathlib`
When joining strings to make a filepath, use the more modern and flexible
`Path()` object instead of `os.path.join`:
Bad:
```python
with open(os.path.join("folder", "file"), "w") as f:
f.write("hello world!")
```
Good:
```python
from pathlib import Path
with open(Path("folder", "file"), "w") as f:
f.write("hello world!")
# even better ...
with Path("folder", "file").open("w") as f:
f.write("hello world!")
# even better ...
Path("folder", "file").write_text("hello world!")
```
Note that this check is disabled by default because `Path()` returns a Path
object, not a string, meaning that the Path object will propagate through
your code. This might be what you want, and might encourage you to use the
pathlib module in more places, but since it is not a drop-in replacement it
is disabled by default.
## FURB148: `no-ignored-enumerate-items`
Categories: `builtin`
Don't use `enumerate` if you are disregarding either the index or the
value:
Bad:
```python
books = ["Ender's Game", "The Black Swan"]
for index, _ in enumerate(books):
print(index)
for _, book in enumerate(books):
print(book)
```
Good:
```python
books = ["Ender's Game", "The Black Swan"]
for index in range(len(books)):
print(index)
for book in books:
print(book)
```
## FURB149: `no-bool-literal-compare`
Categories: `logical` `readability` `truthy`
Don't use `is` or `==` to check if a boolean is True or False, simply
use the name itself:
Bad:
```python
failed = True
if failed is True:
print("You failed")
```
Good:
```python
failed = True
if failed:
print("You failed")
```
## FURB150: `use-pathlib-mkdir`
Categories: `pathlib`
Use the `mkdir` method from the pathlib library instead of using the
`mkdir` and `makedirs` functions from the `os` library: the pathlib library
is more modern and provides better flexibility over the construction and
manipulation of file paths.
Bad:
```python
import os
os.mkdir("new_folder")
```
Good:
```python
from pathlib import Path
Path("new_folder").mkdir()
```
## FURB151: `use-pathlib-touch`
Categories: `pathlib`
Don't use `open(x, "w").close()` if you just want to create an empty file,
use the less confusing `Path.touch()` method instead.
Bad:
```python
open("file.txt", "w").close()
```
Good:
```python
from pathlib import Path
Path("file.txt").touch()
```
This check is disabled by default because `touch()` will throw a
`FileExistsError` if the file already exists, and (at least on Linux) it
sets different file permissions, meaning it is not a drop-in replacement.
If you don't care about the file permissions or know that the file doesn't
exist beforehand this check may be for you.
## FURB152: `use-math-constant`
Categories: `math` `readability`
Don't hardcode math constants like pi, tau, or e, use the `math.pi`,
`math.tau`, or `math.e` constants respectively.
Bad:
```python
def area(r: float) -> float:
return 3.1415 * r * r
```
Good:
```python
import math
def area(r: float) -> float:
return math.pi * r * r
```
## FURB153: `simplify-path-constructor`
Categories: `pathlib` `readability`
The Path() constructor defaults to the current directory, so don't pass the
current directory explicitly.
Bad:
```python
file = Path(".")
```
Good:
```python
file = Path()
```
Note: Lots of different values can trigger this check, including `"."`,
`""`, `os.curdir`, and `os.path.curdir`.
## FURB154: `simplify-global-and-nonlocal`
Categories: `builtin` `readability`
The `global` and `nonlocal` keywords can take multiple comma-separated
names, removing the need for multiple lines.
Bad:
```python
def some_func():
global x
global y
print(x, y)
```
Good:
```python
def some_func():
global x, y
print(x, y)
```
## FURB155: `use-pathlib-stat`
Categories: `pathlib`
Don't use the `os.path.getsize` (or similar) functions, use the more modern
`pathlib` module instead:
Bad:
```python
if os.path.getsize("file.txt"):
pass
```
Good:
```python
if Path("file.txt").stat().st_size:
pass
```
## FURB156: `use-string-charsets`
Categories: `readability` `string`
Python includes some pre-defined charsets such as digits (0-9), upper and
lower case alpha characters, and so on. You don't have to define them
yourself, and they are usually more readable.
Bad:
```python
digits = "0123456789"
if c in digits:
pass
if c in "0123456789abcdefABCDEF":
pass
```
Good:
```python
if c in string.digits:
pass
if c in string.hexdigits:
pass
```
Note that when using a literal string, the corresponding `string.xyz` value
must be exact, but when used in an `in` comparison, the characters can be
out of order since `in` will compare every character in the string.
## FURB157: `simplify-decimal-ctor`
Categories: `decimal`
Under certain circumstances the `Decimal()` constructor can be made more
succinct.
Bad:
```python
if x == Decimal("0"):
pass
if y == Decimal(float("Infinity")):
pass
```
Good:
```python
if x == Decimal(0):
pass
if y == Decimal("Infinity"):
pass
```
## FURB158: `simplify-as-pattern-with-builtin`
Categories: `pattern-matching` `readability`
When pattern matching builtin classes such as `int()` and `str()`, don't
use an `as` pattern to bind to the value, since the most common builtin
classes can use positional patterns instead.
Bad:
```python
match x:
case str() as name:
print(f"Hello {name}")
```
Good:
```python
match x:
case str(name):
print(f"Hello {name}")
```
## FURB159: `simplify-strip`
Categories: `readability` `string`
In some situations the `.lstrip()`, `.rstrip()` and `.strip()` string
methods can be written more succinctly: `strip()` is the same thing as
calling both `lstrip()` and `rstrip()` together, and all the strip
functions take an iterable argument of the characters to strip, meaning
you don't need to call strip methods multiple times with different
arguments, you can just concatenate them and call it once.
Bad:
```python
name = input().lstrip().rstrip()
num = " -123".lstrip(" ").lstrip("-")
```
Good:
```python
name = input().strip()
num = " -123".lstrip(" -")
```
## FURB160: `no-redundant-assignment`
Categories: `readability`
Sometimes when you are debugging (or copy-pasting code) you will end up
with a variable that is assigning itself to itself. These lines can be
removed.
Bad:
```python
name = input("What is your name? ")
name = name
```
Good:
```python
name = input("What is your name? ")
```
## FURB161: `use-bit-count`
Categories: `builtin` `performance` `python310` `readability`
Python 3.10 adds a very helpful `bit_count()` function for integers which
counts the number of set bits. This new function is more descriptive and
faster compared to converting/counting characters in a string.
Bad:
```python
x = bin(0b1010).count("1")
assert x == 2
```
Good:
```python
x = 0b1010.bit_count()
assert x == 2
```
## FURB162: `simplify-fromisoformat`
Categories: `datetime` `python311` `readability`
Python 3.11 adds support for parsing UTC timestamps that end with `Z`, thus
removing the need to strip and append the `+00:00` timezone.
Bad:
```python
date = "2023-02-21T02:23:15Z"
start_date = datetime.fromisoformat(date.replace("Z", "+00:00"))
```
Good:
```python
date = "2023-02-21T02:23:15Z"
start_date = datetime.fromisoformat(date)
```
## FURB163: `simplify-math-log`
Categories: `math` `readability`
Use the shorthand `log2` and `log10` functions instead of passing 2 or 10
as the second argument to the `log` function. If `math.e` is used as the
second argument, just use `math.log(x)` instead, since `e` is the default.
Bad:
```python
power = math.log(x, 10)
```
Good:
```python
power = math.log10(x)
```
## FURB164: `no-from-float`
Categories: `decimal` `fractions` `readability`
When constructing a Fraction or Decimal using a float, don't use the
`from_float()` or `from_decimal()` class methods: Just use the more concise
`Fraction()` and `Decimal()` class constructors instead.
Bad:
```python
ratio = Fraction.from_float(1.2)
score = Decimal.from_float(98.0)
```
Good:
```python
ratio = Fraction(1.2)
score = Decimal(98.0)
```
## FURB165: `no-temp-class-object`
Categories: `readability`
You don't need to construct a class object to call a static method or a
class method, just invoke the method on the class directly:
Bad:
```python
cwd = Path().cwd()
```
Good:
```python
cwd = Path.cwd()
```
## FURB166: `use-int-base-zero`
Categories: `builtin` `readability`
When converting a string starting with `0b`, `0o`, or `0x` to an int, you
don't need to slice the string and set the base yourself: just call `int()`
with a base of zero. Doing this will autodeduce the correct base to use
based on the string prefix.
Bad:
```python
num = "0xABC"
if num.startswith("0b"):
i = int(num[2:], 2)
elif num.startswith("0o"):
i = int(num[2:], 8)
elif num.startswith("0x"):
i = int(num[2:], 16)
print(i)
```
Good:
```python
num = "0xABC"
i = int(num, 0)
print(i)
```
This check is disabled by default because there is no way for Refurb to
detect whether the prefixes that are being stripped are valid Python int
prefixes (like `0x`) or some other prefix which would fail if parsed using
this method.
## FURB167: `use-long-regex-flag`
Categories: `readability` `regex`
Regex operations can be changed using flags such as `re.I`, which will make
the regex case-insensitive. These single-character flag names can be harder
to read/remember, and should be replaced with the longer aliases so that
they are more descriptive.
Bad:
```python
if re.match("^hello", "hello world", re.I):
pass
```
Good:
```python
if re.match("^hello", "hello world", re.IGNORECASE):
pass
```
## FURB168: `no-isinstance-type-none`
Categories: `pythonic` `readability`
Checking if an object is `None` using `isinstance()` is un-pythonic: use an
`is` comparison instead.
Bad:
```python
x = 123
if isinstance(x, type(None)):
pass
```
Good:
```python
x = 123
if x is None:
pass
```
## FURB169: `no-is-type-none`
Categories: `pythonic` `readability`
Don't use `type(None)` to check if the type of an object is `None`, use an
`is` comparison instead.
Bad:
```python
x = 123
if type(x) is type(None):
pass
```
Good:
```python
x = 123
if x is None:
pass
```
## FURB170: `use-regex-pattern-methods`
Categories: `readability` `regex`
If you are passing a compiled regular expression to a regex function,
consider calling the regex method on the pattern itself: It is faster, and
can improve readability.
Bad:
```python
import re
COMMENT = re.compile(".*(#.*)")
found_comment = re.match(COMMENT, "this is a # comment")
```
Good:
```python
import re
COMMENT = re.compile(".*(#.*)")
found_comment = COMMENT.match("this is a # comment")
```
## FURB171: `no-single-item-in`
Categories: `iterable` `readability`
Don't use `in` to check against a single value, use `==` instead:
Bad:
```python
if name in ("bob",):
pass
```
Good:
```python
if name == "bob":
pass
```
## FURB172: `use-suffix`
Categories: `pathlib`
When checking the file extension for a Path object don't call
`endswith()` on the `name` field, directly check against `suffix` instead.
Bad:
```python
from pathlib import Path
def is_markdown_file(file: Path) -> bool:
return file.name.endswith(".md")
```
Good:
```python
from pathlib import Path
def is_markdown_file(file: Path) -> bool:
return file.suffix == ".md"
```
Note: The `suffix` field will only contain the last file extension, so
don't use `suffix` if you are checking for an extension like `.tar.gz`.
Refurb won't warn in those cases, but it is good to remember in case you
plan to use this in other places.
## FURB173: `use-dict-union`
Categories: `dict` `readability`
Dicts can be created/combined in many ways, one of which is the `**`
operator (inside the dict), and another is the `|` operator (used outside
the dict). While they both have valid uses, the `|` operator allows for
more flexibility, including using `|=` to update an existing dict.
See PEP 584 for more info.
Bad:
```python
def add_defaults(settings: dict[str, str]) -> dict[str, str]:
return {"color": "1", **settings}
```
Good:
```python
def add_defaults(settings: dict[str, str]) -> dict[str, str]:
return {"color": "1"} | settings
```
## FURB174: `simplify-token-function`
Categories: `readability` `secrets`
Depending on how you are using the `secrets` module, there might be more
expressive ways of writing what it is you're trying to write.
Bad:
```python
random_hex = token_bytes().hex()
random_url = token_urlsafe()[:16]
```
Good:
```python
random_hex = token_hex()
random_url = token_urlsafe(16)
```
## FURB175: `simplify-fastapi-query`
Categories: `fastapi` `readability`
FastAPI will automatically pass along query parameters to your function, so
you only need to use `Query()` when you use params other than `default`.
Bad:
```python
@app.get("/")
def index(name: str = Query()) -> str:
return f"Your name is {name}"
```
Good:
```python
@app.get("/")
def index(name: str) -> str:
return f"Your name is {name}"
```
## FURB176: `unreliable-utc-usage`
Categories: `datetime`
Because naive `datetime` objects are treated by many `datetime` methods
as local times, it is preferred to use aware datetimes to represent times
in UTC.
This check affects `datetime.utcnow` and `datetime.utcfromtimestamp`.
Bad:
```python
from datetime import datetime
now = datetime.utcnow()
past_date = datetime.utcfromtimestamp(some_timestamp)
```
Good:
```python
from datetime import datetime, timezone
datetime.now(timezone.utc)
datetime.fromtimestamp(some_timestamp, tz=timezone.utc)
```
## FURB177: `no-implicit-cwd`
Categories: `pathlib`
If you want to get the current working directory don't call `resolve()` on
an empty `Path()` object, use `Path.cwd()` instead.
Bad:
```python
cwd = Path().resolve()
```
Good:
```python
cwd = Path.cwd()
```
## FURB178: `use-shlex-join`
Categories: `readability` `shlex`
When using `shlex` to escape and join a bunch of strings consider using the
`shlex.join` method instead.
Bad:
```python
args = ["hello", "world!"]
cmd = " ".join(shlex.quote(arg) for arg in args)
```
Good:
```python
args = ["hello", "world!"]
cmd = shlex.join(args)
```
## FURB179: `use-chain-from-iterable`
Categories: `itertools` `performance` `readability`
When flattening a list of lists, use the `chain.from_iterable()` function
from the `itertools` stdlib package. This function is faster than native
list/generator comprehensions or using `sum()` with a list default.
Bad:
```python
from itertools import chain
rows = [[1, 2], [3, 4]]
# using list comprehension
flat = [col for row in rows for col in row]
# using sum()
flat = sum(rows, [])
# using chain(*x)
flat = chain(*rows)
```
Good:
```python
from itertools import chain
rows = [[1, 2], [3, 4]]
flat = chain.from_iterable(rows)
```
Note: `chain.from_iterable()` returns an iterator, which means you might
need to wrap it in `list()` depending on your use case. Refurb cannot
detect this (yet), so this is something you will need to keep in mind.
Note: `chain(*x)` may be marginally faster/slower depending on the length
of `x`. Since `*` might potentially expand to a lot of arguments, it is
better to use `chain.from_iterable()` when you are unsure.
## FURB180: `use-abc-shorthand`
Categories: `abc` `readability`
Instead of setting `metaclass` directly, inherit from the `ABC` wrapper
class. This is semantically the same thing, but more succinct.
Bad:
```python
class C(metaclass=ABCMeta):
pass
```
Good:
```python
class C(ABC):
pass
```
## FURB181: `use-hexdigest-hashlib`
Categories: `hashlib` `readability`
Use `.hexdigest()` to get a hex digest from a hash.
Bad:
```python
from hashlib import sha512
hashed = sha512(b"some data").digest().hex()
```
Good:
```python
from hashlib import sha512
hashed = sha512(b"some data").hexdigest()
```
## FURB182: `simplify-hashlib-ctor`
Categories: `hashlib` `readability`
You can pass data into `hashlib` constructors, so instead of creating a
hash object and immediately updating it, pass the data directly.
Bad:
```python
from hashlib import sha512
h = sha512()
h.update(b"data)
```
Good:
```python
from hashlib import sha512
h = sha512(b"data")
```
## FURB183: `use-str-func`
Categories: `readability`
If you want to stringify a single value without concatenating anything, use
the `str()` function instead.
Bad:
```python
nums = [123, 456]
num = f"{num[0]}")
```
Good:
```python
nums = [123, 456]
num = str(num[0])
```
## FURB184: `use-fluid-interface`
Categories: `readability`
When an API has a Fluent Interface (the ability to chain multiple calls together), you should
chain those calls instead of repeatedly assigning and using the value.
Sometimes a return statement can be written more succinctly:
Bad:
```pythonpython
def get_tensors(device: str) -> torch.Tensor:
t1 = torch.ones(2, 1)
t2 = t1.long()
t3 = t2.to(device)
return t3
def process(file_name: str):
common_columns = ["col1_renamed", "col2_renamed", "custom_col"]
df = spark.read.parquet(file_name)
df = df \
.withColumnRenamed('col1', 'col1_renamed') \
.withColumnRenamed('col2', 'col2_renamed')
df = df \
.select(common_columns) \
.withColumn('service_type', F.lit('green'))
return df
```
Good:
```pythonpython
def get_tensors(device: str) -> torch.Tensor:
t3 = (
torch.ones(2, 1)
.long()
.to(device)
)
return t3
def process(file_name: str):
common_columns = ["col1_renamed", "col2_renamed", "custom_col"]
df = (
spark.read.parquet(file_name)
.withColumnRenamed('col1', 'col1_renamed')
.withColumnRenamed('col2', 'col2_renamed')
.select(common_columns)
.withColumn('service_type', F.lit('green'))
)
return df
```
## FURB185: `no-copy-with-merge`
Categories: `readability`
You don't need to call `.copy()` on a dict/set when using it in a union
since the original dict/set is not modified.
Bad:
```python
d = {"a": 1}
merged = d.copy() | {"b": 2}
```
Good:
```python
d = {"a": 1}
merged = d | {"b": 2}
```
## FURB186: `use-sort`
Categories: `performance` `readability`
Don't use `sorted()` to sort a list and reassign it to itself, use the
faster in-place `.sort()` method instead.
Bad:
```python
names = ["Bob", "Alice", "Charlie"]
names = sorted(names)
```
Good:
```python
names = ["Bob", "Alice", "Charlie"]
names.sort()
```
|