/usr/share/doc/python/faq/programming.html is in python 2.7.13-2.
This file is owned by root:root, with mode 0o644.
The actual contents of the file can be viewed below.
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 | <?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="generator" content="Docutils 0.12: http://docutils.sourceforge.net/" />
<title>Programming FAQ</title>
<meta name="date" content="2005-12-21" />
<style type="text/css">
/*
:Author: David Goodger (goodger@python.org)
:Id: $Id: html4css1.css 7614 2013-02-21 15:55:51Z milde $
:Copyright: This stylesheet has been placed in the public domain.
Default cascading style sheet for the HTML output of Docutils.
See http://docutils.sf.net/docs/howto/html-stylesheets.html for how to
customize this style sheet.
*/
/* used to remove borders from tables and images */
.borderless, table.borderless td, table.borderless th {
border: 0 }
table.borderless td, table.borderless th {
/* Override padding for "table.docutils td" with "! important".
The right padding separates the table cells. */
padding: 0 0.5em 0 0 ! important }
.first {
/* Override more specific margin styles with "! important". */
margin-top: 0 ! important }
.last, .with-subtitle {
margin-bottom: 0 ! important }
.hidden {
display: none }
a.toc-backref {
text-decoration: none ;
color: black }
blockquote.epigraph {
margin: 2em 5em ; }
dl.docutils dd {
margin-bottom: 0.5em }
object[type="image/svg+xml"], object[type="application/x-shockwave-flash"] {
overflow: hidden;
}
/* Uncomment (and remove this text!) to get bold-faced definition list terms
dl.docutils dt {
font-weight: bold }
*/
div.abstract {
margin: 2em 5em }
div.abstract p.topic-title {
font-weight: bold ;
text-align: center }
div.admonition, div.attention, div.caution, div.danger, div.error,
div.hint, div.important, div.note, div.tip, div.warning {
margin: 2em ;
border: medium outset ;
padding: 1em }
div.admonition p.admonition-title, div.hint p.admonition-title,
div.important p.admonition-title, div.note p.admonition-title,
div.tip p.admonition-title {
font-weight: bold ;
font-family: sans-serif }
div.attention p.admonition-title, div.caution p.admonition-title,
div.danger p.admonition-title, div.error p.admonition-title,
div.warning p.admonition-title, .code .error {
color: red ;
font-weight: bold ;
font-family: sans-serif }
/* Uncomment (and remove this text!) to get reduced vertical space in
compound paragraphs.
div.compound .compound-first, div.compound .compound-middle {
margin-bottom: 0.5em }
div.compound .compound-last, div.compound .compound-middle {
margin-top: 0.5em }
*/
div.dedication {
margin: 2em 5em ;
text-align: center ;
font-style: italic }
div.dedication p.topic-title {
font-weight: bold ;
font-style: normal }
div.figure {
margin-left: 2em ;
margin-right: 2em }
div.footer, div.header {
clear: both;
font-size: smaller }
div.line-block {
display: block ;
margin-top: 1em ;
margin-bottom: 1em }
div.line-block div.line-block {
margin-top: 0 ;
margin-bottom: 0 ;
margin-left: 1.5em }
div.sidebar {
margin: 0 0 0.5em 1em ;
border: medium outset ;
padding: 1em ;
background-color: #ffffee ;
width: 40% ;
float: right ;
clear: right }
div.sidebar p.rubric {
font-family: sans-serif ;
font-size: medium }
div.system-messages {
margin: 5em }
div.system-messages h1 {
color: red }
div.system-message {
border: medium outset ;
padding: 1em }
div.system-message p.system-message-title {
color: red ;
font-weight: bold }
div.topic {
margin: 2em }
h1.section-subtitle, h2.section-subtitle, h3.section-subtitle,
h4.section-subtitle, h5.section-subtitle, h6.section-subtitle {
margin-top: 0.4em }
h1.title {
text-align: center }
h2.subtitle {
text-align: center }
hr.docutils {
width: 75% }
img.align-left, .figure.align-left, object.align-left {
clear: left ;
float: left ;
margin-right: 1em }
img.align-right, .figure.align-right, object.align-right {
clear: right ;
float: right ;
margin-left: 1em }
img.align-center, .figure.align-center, object.align-center {
display: block;
margin-left: auto;
margin-right: auto;
}
.align-left {
text-align: left }
.align-center {
clear: both ;
text-align: center }
.align-right {
text-align: right }
/* reset inner alignment in figures */
div.align-right {
text-align: inherit }
/* div.align-center * { */
/* text-align: left } */
ol.simple, ul.simple {
margin-bottom: 1em }
ol.arabic {
list-style: decimal }
ol.loweralpha {
list-style: lower-alpha }
ol.upperalpha {
list-style: upper-alpha }
ol.lowerroman {
list-style: lower-roman }
ol.upperroman {
list-style: upper-roman }
p.attribution {
text-align: right ;
margin-left: 50% }
p.caption {
font-style: italic }
p.credits {
font-style: italic ;
font-size: smaller }
p.label {
white-space: nowrap }
p.rubric {
font-weight: bold ;
font-size: larger ;
color: maroon ;
text-align: center }
p.sidebar-title {
font-family: sans-serif ;
font-weight: bold ;
font-size: larger }
p.sidebar-subtitle {
font-family: sans-serif ;
font-weight: bold }
p.topic-title {
font-weight: bold }
pre.address {
margin-bottom: 0 ;
margin-top: 0 ;
font: inherit }
pre.literal-block, pre.doctest-block, pre.math, pre.code {
margin-left: 2em ;
margin-right: 2em }
pre.code .ln { color: grey; } /* line numbers */
pre.code, code { background-color: #eeeeee }
pre.code .comment, code .comment { color: #5C6576 }
pre.code .keyword, code .keyword { color: #3B0D06; font-weight: bold }
pre.code .literal.string, code .literal.string { color: #0C5404 }
pre.code .name.builtin, code .name.builtin { color: #352B84 }
pre.code .deleted, code .deleted { background-color: #DEB0A1}
pre.code .inserted, code .inserted { background-color: #A3D289}
span.classifier {
font-family: sans-serif ;
font-style: oblique }
span.classifier-delimiter {
font-family: sans-serif ;
font-weight: bold }
span.interpreted {
font-family: sans-serif }
span.option {
white-space: nowrap }
span.pre {
white-space: pre }
span.problematic {
color: red }
span.section-subtitle {
/* font-size relative to parent (h1..h6 element) */
font-size: 80% }
table.citation {
border-left: solid 1px gray;
margin-left: 1px }
table.docinfo {
margin: 2em 4em }
table.docutils {
margin-top: 0.5em ;
margin-bottom: 0.5em }
table.footnote {
border-left: solid 1px black;
margin-left: 1px }
table.docutils td, table.docutils th,
table.docinfo td, table.docinfo th {
padding-left: 0.5em ;
padding-right: 0.5em ;
vertical-align: top }
table.docutils th.field-name, table.docinfo th.docinfo-name {
font-weight: bold ;
text-align: left ;
white-space: nowrap ;
padding-left: 0 }
/* "booktabs" style (no vertical lines) */
table.docutils.booktabs {
border: 0px;
border-top: 2px solid;
border-bottom: 2px solid;
border-collapse: collapse;
}
table.docutils.booktabs * {
border: 0px;
}
table.docutils.booktabs th {
border-bottom: thin solid;
text-align: left;
}
h1 tt.docutils, h2 tt.docutils, h3 tt.docutils,
h4 tt.docutils, h5 tt.docutils, h6 tt.docutils {
font-size: 100% }
ul.auto-toc {
list-style-type: none }
</style>
</head>
<body>
<div class="document" id="programming-faq">
<h1 class="title">Programming FAQ</h1>
<table class="docinfo" frame="void" rules="none">
<col class="docinfo-name" />
<col class="docinfo-content" />
<tbody valign="top">
<tr><th class="docinfo-name">Date:</th>
<td>2005-12-21</td></tr>
<tr><th class="docinfo-name">Version:</th>
<td>8721</td></tr>
<tr class="field"><th class="docinfo-name">Web site:</th><td class="field-body"><a class="reference external" href="http://www.python.org/">http://www.python.org/</a></td>
</tr>
</tbody>
</table>
<div class="contents topic" id="contents">
<p class="topic-title first">Contents</p>
<ul class="auto-toc simple">
<li><a class="reference internal" href="#general-questions" id="id1">1 General Questions</a><ul class="auto-toc">
<li><a class="reference internal" href="#is-there-a-source-code-level-debugger-with-breakpoints-single-stepping-etc" id="id2">1.1 Is there a source code level debugger with breakpoints, single-stepping, etc.?</a></li>
<li><a class="reference internal" href="#is-there-a-tool-to-help-find-bugs-or-perform-static-analysis" id="id3">1.2 Is there a tool to help find bugs or perform static analysis?</a></li>
<li><a class="reference internal" href="#how-can-i-create-a-stand-alone-binary-from-a-python-script" id="id4">1.3 How can I create a stand-alone binary from a Python script?</a></li>
<li><a class="reference internal" href="#are-there-coding-standards-or-a-style-guide-for-python-programs" id="id5">1.4 Are there coding standards or a style guide for Python programs?</a></li>
<li><a class="reference internal" href="#my-program-is-too-slow-how-do-i-speed-it-up" id="id6">1.5 My program is too slow. How do I speed it up?</a></li>
</ul>
</li>
<li><a class="reference internal" href="#core-language" id="id7">2 Core Language</a><ul class="auto-toc">
<li><a class="reference internal" href="#how-do-you-set-a-global-variable-in-a-function" id="id8">2.1 How do you set a global variable in a function?</a></li>
<li><a class="reference internal" href="#what-are-the-rules-for-local-and-global-variables-in-python" id="id9">2.2 What are the rules for local and global variables in Python?</a></li>
<li><a class="reference internal" href="#how-do-i-share-global-variables-across-modules" id="id10">2.3 How do I share global variables across modules?</a></li>
<li><a class="reference internal" href="#what-are-the-best-practices-for-using-import-in-a-module" id="id11">2.4 What are the "best practices" for using import in a module?</a></li>
<li><a class="reference internal" href="#how-can-i-pass-optional-or-keyword-parameters-from-one-function-to-another" id="id12">2.5 How can I pass optional or keyword parameters from one function to another?</a></li>
<li><a class="reference internal" href="#how-do-i-write-a-function-with-output-parameters-call-by-reference" id="id13">2.6 How do I write a function with output parameters (call by reference)?</a></li>
<li><a class="reference internal" href="#how-do-you-make-a-higher-order-function-in-python" id="id14">2.7 How do you make a higher order function in Python?</a></li>
<li><a class="reference internal" href="#how-do-i-copy-an-object-in-python" id="id15">2.8 How do I copy an object in Python?</a></li>
<li><a class="reference internal" href="#how-can-i-find-the-methods-or-attributes-of-an-object" id="id16">2.9 How can I find the methods or attributes of an object?</a></li>
<li><a class="reference internal" href="#how-can-my-code-discover-the-name-of-an-object" id="id17">2.10 How can my code discover the name of an object?</a></li>
<li><a class="reference internal" href="#is-there-an-equivalent-of-c-s-ternary-operator" id="id18">2.11 Is there an equivalent of C's "?:" ternary operator?</a></li>
<li><a class="reference internal" href="#is-it-possible-to-write-obfuscated-one-liners-in-python" id="id19">2.12 Is it possible to write obfuscated one-liners in Python?</a></li>
</ul>
</li>
<li><a class="reference internal" href="#numbers-and-strings" id="id20">3 Numbers and strings</a><ul class="auto-toc">
<li><a class="reference internal" href="#how-do-i-specify-hexadecimal-and-octal-integers" id="id21">3.1 How do I specify hexadecimal and octal integers?</a></li>
<li><a class="reference internal" href="#why-does-22-10-return-3" id="id22">3.2 Why does -22 / 10 return -3?</a></li>
<li><a class="reference internal" href="#how-do-i-convert-a-string-to-a-number" id="id23">3.3 How do I convert a string to a number?</a></li>
<li><a class="reference internal" href="#how-do-i-convert-a-number-to-a-string" id="id24">3.4 How do I convert a number to a string?</a></li>
<li><a class="reference internal" href="#how-do-i-modify-a-string-in-place" id="id25">3.5 How do I modify a string in place?</a></li>
<li><a class="reference internal" href="#how-do-i-use-strings-to-call-functions-methods" id="id26">3.6 How do I use strings to call functions/methods?</a></li>
<li><a class="reference internal" href="#is-there-an-equivalent-to-perl-s-chomp-for-removing-trailing-newlines-from-strings" id="id27">3.7 Is there an equivalent to Perl's chomp() for removing trailing newlines from strings?</a></li>
<li><a class="reference internal" href="#is-there-a-scanf-or-sscanf-equivalent" id="id28">3.8 Is there a scanf() or sscanf() equivalent?</a></li>
<li><a class="reference internal" href="#what-does-unicodeerror-ascii-decoding-encoding-error-ordinal-not-in-range-128-mean" id="id29">3.9 What does 'UnicodeError: ASCII [decoding,encoding] error: ordinal not in range(128)' mean?</a></li>
</ul>
</li>
<li><a class="reference internal" href="#sequences-tuples-lists" id="id30">4 Sequences (Tuples/Lists)</a><ul class="auto-toc">
<li><a class="reference internal" href="#how-do-i-convert-between-tuples-and-lists" id="id31">4.1 How do I convert between tuples and lists?</a></li>
<li><a class="reference internal" href="#what-s-a-negative-index" id="id32">4.2 What's a negative index?</a></li>
<li><a class="reference internal" href="#how-do-i-iterate-over-a-sequence-in-reverse-order" id="id33">4.3 How do I iterate over a sequence in reverse order?</a></li>
<li><a class="reference internal" href="#how-do-you-remove-duplicates-from-a-list" id="id34">4.4 How do you remove duplicates from a list?</a></li>
<li><a class="reference internal" href="#how-do-you-make-an-array-in-python" id="id35">4.5 How do you make an array in Python?</a></li>
<li><a class="reference internal" href="#how-do-i-create-a-multidimensional-list" id="id36">4.6 How do I create a multidimensional list?</a></li>
<li><a class="reference internal" href="#how-do-i-apply-a-method-to-a-sequence-of-objects" id="id37">4.7 How do I apply a method to a sequence of objects?</a></li>
</ul>
</li>
<li><a class="reference internal" href="#dictionaries" id="id38">5 Dictionaries</a><ul class="auto-toc">
<li><a class="reference internal" href="#how-can-i-get-a-dictionary-to-display-its-keys-in-a-consistent-order" id="id39">5.1 How can I get a dictionary to display its keys in a consistent order?</a></li>
<li><a class="reference internal" href="#i-want-to-do-a-complicated-sort-can-you-do-a-schwartzian-transform-in-python" id="id40">5.2 I want to do a complicated sort: can you do a Schwartzian Transform in Python?</a></li>
<li><a class="reference internal" href="#how-can-i-sort-one-list-by-values-from-another-list" id="id41">5.3 How can I sort one list by values from another list?</a></li>
</ul>
</li>
<li><a class="reference internal" href="#objects" id="id42">6 Objects</a><ul class="auto-toc">
<li><a class="reference internal" href="#what-is-a-class" id="id43">6.1 What is a class?</a></li>
<li><a class="reference internal" href="#what-is-a-method" id="id44">6.2 What is a method?</a></li>
<li><a class="reference internal" href="#what-is-self" id="id45">6.3 What is self?</a></li>
<li><a class="reference internal" href="#how-do-i-check-if-an-object-is-an-instance-of-a-given-class-or-of-a-subclass-of-it" id="id46">6.4 How do I check if an object is an instance of a given class or of a subclass of it?</a></li>
<li><a class="reference internal" href="#what-is-delegation" id="id47">6.5 What is delegation?</a></li>
<li><a class="reference internal" href="#how-do-i-call-a-method-defined-in-a-base-class-from-a-derived-class-that-overrides-it" id="id48">6.6 How do I call a method defined in a base class from a derived class that overrides it?</a></li>
<li><a class="reference internal" href="#how-can-i-organize-my-code-to-make-it-easier-to-change-the-base-class" id="id49">6.7 How can I organize my code to make it easier to change the base class?</a></li>
<li><a class="reference internal" href="#how-do-i-create-static-class-data-and-static-class-methods" id="id50">6.8 How do I create static class data and static class methods?</a></li>
<li><a class="reference internal" href="#how-can-i-overload-constructors-or-methods-in-python" id="id51">6.9 How can I overload constructors (or methods) in Python?</a></li>
<li><a class="reference internal" href="#i-try-to-use-spam-and-i-get-an-error-about-someclassname-spam" id="id52">6.10 I try to use __spam and I get an error about _SomeClassName__spam.</a></li>
<li><a class="reference internal" href="#my-class-defines-del-but-it-is-not-called-when-i-delete-the-object" id="id53">6.11 My class defines __del__ but it is not called when I delete the object.</a></li>
<li><a class="reference internal" href="#how-do-i-get-a-list-of-all-instances-of-a-given-class" id="id54">6.12 How do I get a list of all instances of a given class?</a></li>
</ul>
</li>
<li><a class="reference internal" href="#modules" id="id55">7 Modules</a><ul class="auto-toc">
<li><a class="reference internal" href="#how-do-i-create-a-pyc-file" id="id56">7.1 How do I create a .pyc file?</a></li>
<li><a class="reference internal" href="#how-do-i-find-the-current-module-name" id="id57">7.2 How do I find the current module name?</a></li>
<li><a class="reference internal" href="#how-can-i-have-modules-that-mutually-import-each-other" id="id58">7.3 How can I have modules that mutually import each other?</a></li>
<li><a class="reference internal" href="#import-x-y-z-returns-module-x-how-do-i-get-z" id="id59">7.4 __import__('x.y.z') returns <module 'x'>; how do I get z?</a></li>
<li><a class="reference internal" href="#when-i-edit-an-imported-module-and-reimport-it-the-changes-don-t-show-up-why-does-this-happen" id="id60">7.5 When I edit an imported module and reimport it, the changes don't show up. Why does this happen?</a></li>
</ul>
</li>
</ul>
</div>
<div class="section" id="general-questions">
<h1><a class="toc-backref" href="#id1">1 General Questions</a></h1>
<div class="section" id="is-there-a-source-code-level-debugger-with-breakpoints-single-stepping-etc">
<h2><a class="toc-backref" href="#id2">1.1 Is there a source code level debugger with breakpoints, single-stepping, etc.?</a></h2>
<p>Yes.</p>
<p>The pdb module is a simple but adequate console-mode debugger for
Python. It is part of the standard Python library, and is <a class="reference external" href="http://docs.python.org/lib/module-pdb.html">documented
in the Library Reference Manual</a>. You can
also write your own debugger by using the code for pdb as an example.</p>
<p>The IDLE interactive development environment, which is part of the
standard Python distribution (normally available as Tools/scripts/idle),
includes a graphical debugger. There is documentation for the IDLE
debugger at <a class="reference external" href="http://www.python.org/idle/doc/idle2.html#Debugger">http://www.python.org/idle/doc/idle2.html#Debugger</a></p>
<p>PythonWin is a Python IDE that includes a GUI debugger based on pdb.
The Pythonwin debugger colors breakpoints and has quite a few cool
features such as debugging non-Pythonwin programs. A reference can be
found at <a class="reference external" href="http://www.python.org/windows/pythonwin/">http://www.python.org/windows/pythonwin/</a>. Recent versions of
PythonWin are available as a part of the ActivePython distribution
(see <a class="reference external" href="http://www.activestate.com/Products/ActivePython/index.html">http://www.activestate.com/Products/ActivePython/index.html</a>).</p>
<p><a class="reference external" href="http://boa-constructor.sourceforge.net/">Boa Constructor</a> is an IDE
and GUI builder that uses wxPython. It offers visual frame creation
and manipulation, an object
inspector, many views on the source like object browsers, inheritance
hierarchies, doc string generated html documentation, an advanced
debugger, integrated help, and Zope support.</p>
<p><a class="reference external" href="http://www.die-offenbachs.de/detlev/eric3.html">Eric3</a> is an IDE
built on PyQt and the Scintilla editing component.</p>
<p>Pydb is a version of the standard Python debugger pdb, modified for
use with DDD (Data Display Debugger), a popular graphical debugger
front end. Pydb can be found at
<a class="reference external" href="http://packages.debian.org/unstable/devel/pydb.html">http://packages.debian.org/unstable/devel/pydb.html</a>> and DDD can be
found at <a class="reference external" href="http://www.gnu.org/software/ddd">http://www.gnu.org/software/ddd</a>.</p>
<p>There are a number of commmercial Python IDEs that include graphical
debuggers. They include:</p>
<ul class="simple">
<li>Wing IDE (<a class="reference external" href="http://wingide.com">http://wingide.com</a>)</li>
<li>Komodo IDE (<a class="reference external" href="http://www.activestate.com/Products/Komodo">http://www.activestate.com/Products/Komodo</a>)</li>
</ul>
</div>
<div class="section" id="is-there-a-tool-to-help-find-bugs-or-perform-static-analysis">
<h2><a class="toc-backref" href="#id3">1.2 Is there a tool to help find bugs or perform static analysis?</a></h2>
<p>Yes.</p>
<p>PyChecker is a static analysis tool that finds bugs in Python source
code and warns about code complexity and style. You can get PyChecker
from <a class="reference external" href="http://pychecker.sf.net">http://pychecker.sf.net</a>.</p>
<p><a class="reference external" href="http://www.logilab.org/projects/pylint">Pylint</a> is another tool
that checks if a module satisfies a coding standard, and also makes it
possible to write plug-ins to add a custom feature. In addition to
the bug checking that PyChecker performs, Pylint offers some
additional features such as checking line length, whether variable
names are well-formed according to your coding standard, whether
declared interfaces are fully implemented, and more.
<a class="reference external" href="http://www.logilab.org/projects/pylint/documentation">http://www.logilab.org/projects/pylint/documentation</a> provides a full
list of Pylint's features.</p>
</div>
<div class="section" id="how-can-i-create-a-stand-alone-binary-from-a-python-script">
<h2><a class="toc-backref" href="#id4">1.3 How can I create a stand-alone binary from a Python script?</a></h2>
<p>You don't need the ability to compile Python to C code if all you
want is a stand-alone program that users can download and run without
having to install the Python distribution first. There are a number
of tools that determine the set of modules required by a program and
bind these modules together with a Python binary to produce a single
executable.</p>
<p>One is to use the freeze tool, which is included in the Python
source tree as <tt class="docutils literal">Tools/freeze</tt>. It converts Python byte
code to C arrays; a C compiler you can embed all
your modules into a new program, which is then linked
with the standard Python modules.</p>
<p>It works by scanning your source recursively for import statements (in
both forms) and looking for the modules in the standard Python path as
well as in the source directory (for built-in modules). It then turns
the bytecode for modules written in Python into C code (array
initializers that can be turned into code objects using the marshal
module) and creates a custom-made config file that only contains those
built-in modules which are actually used in the program. It then
compiles the generated C code and links it with the rest of the Python
interpreter to form a self-contained binary which acts exactly like
your script.</p>
<p>Obviously, freeze requires a C compiler. There are several other
utilities which don't. The first is Gordon McMillan's installer at</p>
<blockquote>
<a class="reference external" href="http://www.mcmillan-inc.com/install1.html">http://www.mcmillan-inc.com/install1.html</a></blockquote>
<p>which works on Windows, Linux and at least some forms of Unix.</p>
<p>Another is Thomas Heller's py2exe (Windows only) at</p>
<blockquote>
<a class="reference external" href="http://starship.python.net/crew/theller/py2exe">http://starship.python.net/crew/theller/py2exe</a></blockquote>
<p>A third is Christian Tismer's <a class="reference external" href="http://starship.python.net/crew/pirx">SQFREEZE</a> which appends the byte code
to a specially-prepared Python interpreter that can find the byte
code in the executable. It's possible that a similar approach will
be added to Python 2.4, due out some time in 2004.</p>
<p>Other tools include Fredrik Lundh's <a class="reference external" href="http://www.pythonware.com/products/python/squeeze">Squeeze</a> and Anthony
Tuininga's <a class="reference external" href="http://starship.python.net/crew/atuining/cx_Freeze/index.html">cx_Freeze</a>.</p>
</div>
<div class="section" id="are-there-coding-standards-or-a-style-guide-for-python-programs">
<h2><a class="toc-backref" href="#id5">1.4 Are there coding standards or a style guide for Python programs?</a></h2>
<p>Yes. The coding style required for standard library modules
is documented as <a class="reference external" href="../../peps/pep-0008.html">PEP 8</a>.</p>
</div>
<div class="section" id="my-program-is-too-slow-how-do-i-speed-it-up">
<h2><a class="toc-backref" href="#id6">1.5 My program is too slow. How do I speed it up?</a></h2>
<p>That's a tough one, in general. There are many tricks to speed up
Python code; consider rewriting parts in C as a last resort.</p>
<p>In some cases it's possible to automatically translate Python to C or
x86 assembly language, meaning that you don't have to modify your code
to gain increased speed.</p>
<p><a class="reference external" href="http://www.cosc.canterbury.ac.nz/~greg/python/Pyrex/">Pyrex</a> can
compile a slightly modified version of Python code into a C extension,
and can be used on many different platforms.</p>
<p><a class="reference external" href="http://psyco.sourceforge.net">Psyco</a> is a just-in-time compiler
that translates Python code into x86 assembly language. If you can
use it, Psyco can provide dramatic speedups for critical functions.</p>
<p>The rest of this answer will discuss various tricks for squeezing a
bit more speed out of Python code. <em>Never</em> apply any optimization
tricks unless you know you need them, after profiling has indicated
that a particular function is the heavily executed hot spot in the
code. Optimizations almost always make the code less clear, and you
shouldn't pay the costs of reduced clarity (increased development
time, greater likelihood of bugs) unless the resulting performance
benefit is worth it.</p>
<p>There is a page on the wiki devoted to <a class="reference external" href="http://wiki.python.org/moin/PythonSpeed/PerformanceTips">performance tips</a>.</p>
<p>Guido van Rossum has written up an anecdote related to optimization at
<a class="reference external" href="http://www.python.org/doc/essays/list2str.html">http://www.python.org/doc/essays/list2str.html</a>.</p>
<p>One thing to notice is that function and (especially) method calls are
rather expensive; if you have designed a purely OO interface with lots
of tiny functions that don't do much more than get or set an instance
variable or call another method, you might consider using a more
direct way such as directly accessing instance variables. Also see the
standard module "profile" (<a class="reference external" href="http://docs.python.org/lib/module-profile.html">described in the Library Reference manual</a>) which
makes it possible to find out where your program is spending most of
its time (if you have some patience -- the profiling itself can slow
your program down by an order of magnitude).</p>
<p>Remember that many standard optimization heuristics you
may know from other programming experience may well apply
to Python. For example it may be faster to send output to output
devices using larger writes rather than smaller ones in order to
reduce the overhead of kernel system calls. Thus CGI scripts
that write all output in "one shot" may be faster than
those that write lots of small pieces of output.</p>
<p>Also, be sure to use Python's core features where appropriate.
For example, slicing allows programs to chop up
lists and other sequence objects in a single tick of the interpreter's
mainloop using highly optimized C implementations. Thus to
get the same effect as:</p>
<pre class="literal-block">
L2 = []
for i in range[3]:
L2.append(L1[i])
</pre>
<p>it is much shorter and far faster to use</p>
<pre class="literal-block">
L2 = list(L1[:3]) # "list" is redundant if L1 is a list.
</pre>
<p>Note that the functionally-oriented builtins such as
<tt class="docutils literal">map()</tt>, <tt class="docutils literal">zip()</tt>, and friends can be a convenient
accelerator for loops that perform a single task. For example to pair the elements of two
lists together:</p>
<pre class="literal-block">
>>> zip([1,2,3], [4,5,6])
[(1, 4), (2, 5), (3, 6)]
</pre>
<p>or to compute a number of sines:</p>
<pre class="literal-block">
>>> map( math.sin, (1,2,3,4))
[0.841470984808, 0.909297426826, 0.14112000806, -0.756802495308]
</pre>
<p>The operation completes very quickly in such cases.</p>
<p>Other examples include the <tt class="docutils literal">join()</tt> and <tt class="docutils literal">split()</tt>
methods of string objects. For example if s1..s7 are large (10K+) strings then
<tt class="docutils literal"><span class="pre">"".join([s1,s2,s3,s4,s5,s6,s7])`</span> may be far faster than
the more obvious ``s1+s2+s3+s4+s5+s6+s7</tt>, since the "summation"
will compute many subexpressions, whereas <tt class="docutils literal">join()</tt> does all the
copying in one pass. For manipulating strings, use
the <tt class="docutils literal">replace()</tt> method on string objects. Use
regular expressions only when you're not dealing with constant string patterns.
Consider using the string formatting operations
<tt class="docutils literal">string % tuple</tt> and <tt class="docutils literal">string % dictionary</tt>.</p>
<p>Be sure to use the <tt class="docutils literal">list.sort()</tt> builtin method to do sorting, and see
the <a class="reference external" href="http://wiki.python.org/moin/HowTo/Sorting">sorting mini-HOWTO</a> for examples of moderately advanced usage.
<tt class="docutils literal">list.sort()</tt> beats other techniques for sorting in all but the most
extreme circumstances.</p>
<p>Another common trick is to "push loops into functions or methods."
For example suppose you have a program that runs slowly and you
use the profiler to determine that a Python function <tt class="docutils literal">ff()</tt>
is being called lots of times. If you notice that <tt class="docutils literal">ff ()</tt>:</p>
<pre class="literal-block">
def ff(x):
...do something with x computing result...
return result
</pre>
<p>tends to be called in loops like:</p>
<pre class="literal-block">
list = map(ff, oldlist)
</pre>
<p>or:</p>
<pre class="literal-block">
for x in sequence:
value = ff(x)
...do something with value...
</pre>
<p>then you can often eliminate function call overhead by rewriting
<tt class="docutils literal">ff()</tt> to:</p>
<pre class="literal-block">
def ffseq(seq):
resultseq = []
for x in seq:
...do something with x computing result...
resultseq.append(result)
return resultseq
</pre>
<p>and rewrite the two examples to <tt class="docutils literal">list = ffseq(oldlist)</tt> and to:</p>
<pre class="literal-block">
for value in ffseq(sequence):
...do something with value...
</pre>
<p>Single calls to ff(x) translate to ffseq([x])[0] with little
penalty. Of course this technique is not always appropriate
and there are other variants which you can figure out.</p>
<p>You can gain some performance by explicitly storing the results of
a function or method lookup into a local variable. A loop like:</p>
<pre class="literal-block">
for key in token:
dict[key] = dict.get(key, 0) + 1
</pre>
<p>resolves dict.get every iteration. If the method isn't going to
change, a slightly faster implementation is:</p>
<pre class="literal-block">
dict_get = dict.get # look up the method once
for key in token:
dict[key] = dict_get(key, 0) + 1
</pre>
<p>Default arguments can be used to determine values once, at
compile time instead of at run time. This can only be done for
functions or objects which will not be changed during program
execution, such as replacing</p>
<pre class="literal-block">
def degree_sin(deg):
return math.sin(deg * math.pi / 180.0)
</pre>
<p>with</p>
<pre class="literal-block">
def degree_sin(deg, factor = math.pi/180.0, sin = math.sin):
return sin(deg * factor)
</pre>
<p>Because this trick uses default arguments for terms which should
not be changed, it should only be used when you are not concerned
with presenting a possibly confusing API to your users.</p>
</div>
</div>
<div class="section" id="core-language">
<h1><a class="toc-backref" href="#id7">2 Core Language</a></h1>
<div class="section" id="how-do-you-set-a-global-variable-in-a-function">
<h2><a class="toc-backref" href="#id8">2.1 How do you set a global variable in a function?</a></h2>
<p>Did you do something like this?</p>
<pre class="literal-block">
x = 1 # make a global
def f():
print x # try to print the global
...
for j in range(100):
if q>3:
x=4
</pre>
<p>Any variable assigned in a function is local to that function.
unless it is specifically declared global. Since a value is bound
to <tt class="docutils literal">x</tt> as the last statement of the function body, the compiler
assumes that <tt class="docutils literal">x</tt> is local. Consequently the <tt class="docutils literal">print x</tt>
attempts to print an uninitialized local variable and will
trigger a <tt class="docutils literal">NameError</tt>.</p>
<p>The solution is to insert an explicit global declaration at the start
of the function:</p>
<pre class="literal-block">
def f():
global x
print x # try to print the global
...
for j in range(100):
if q>3:
x=4
</pre>
<p>In this case, all references to <tt class="docutils literal">x</tt> are interpreted as references
to the <tt class="docutils literal">x</tt> from the module namespace.</p>
</div>
<div class="section" id="what-are-the-rules-for-local-and-global-variables-in-python">
<h2><a class="toc-backref" href="#id9">2.2 What are the rules for local and global variables in Python?</a></h2>
<p>In Python, variables that are only referenced inside a function are
implicitly global. If a variable is assigned a new value anywhere
within the function's body, it's assumed to be a local. If a variable
is ever assigned a new value inside the function, the variable is
implicitly local, and you need to explicitly declare it as 'global'.</p>
<p>Though a bit surprising at first, a moment's consideration explains
this. On one hand, requiring <tt class="docutils literal">global</tt> for assigned variables provides
a bar against unintended side-effects. On the other hand, if <tt class="docutils literal">global</tt>
was required for all global references, you'd be using <tt class="docutils literal">global</tt> all the
time. You'd have to declare as global every reference to a
builtin function or to a component of an imported module. This
clutter would defeat the usefulness of the <tt class="docutils literal">global</tt> declaration for
identifying side-effects.</p>
</div>
<div class="section" id="how-do-i-share-global-variables-across-modules">
<h2><a class="toc-backref" href="#id10">2.3 How do I share global variables across modules?</a></h2>
<p>The canonical way to share information across modules within a single
program is to create a special module (often called config or cfg).
Just import the config module in all modules of your application; the
module then becomes available as a global name. Because there is only
one instance of each module, any changes made to the module object get
reflected everywhere. For example:</p>
<p>config.py:</p>
<pre class="literal-block">
x = 0 # Default value of the 'x' configuration setting
</pre>
<p>mod.py:</p>
<pre class="literal-block">
import config
config.x = 1
</pre>
<p>main.py:</p>
<pre class="literal-block">
import config
import mod
print config.x
</pre>
<p>Note that using a module is also the basis for implementing the
Singleton design pattern, for the same reason.</p>
</div>
<div class="section" id="what-are-the-best-practices-for-using-import-in-a-module">
<h2><a class="toc-backref" href="#id11">2.4 What are the "best practices" for using import in a module?</a></h2>
<p>In general, don't use <tt class="docutils literal">from modulename import *</tt>.
Doing so clutters the importer's namespace. Some people avoid this idiom
even with the few modules that were designed to be imported in this
manner. Modules designed in this manner include <tt class="docutils literal">Tkinter</tt>,
and <tt class="docutils literal">threading</tt>.</p>
<p>Import modules at the top of a file. Doing so makes it clear what
other modules your code requires and avoids questions of whether the
module name is in scope. Using one import per line makes it easy to
add and delete module imports, but using multiple imports per line
uses less screen space.</p>
<p>It's good practice if you import modules in the following order:</p>
<ol class="arabic simple">
<li>standard libary modules -- e.g. <tt class="docutils literal">sys</tt>, <tt class="docutils literal">os</tt>, <tt class="docutils literal">getopt</tt>, <tt class="docutils literal">re</tt>)</li>
<li>third-party library modules (anything installed in Python's
site-packages directory) -- e.g. mx.DateTime, ZODB, PIL.Image, etc.</li>
<li>locally-developed modules</li>
</ol>
<p>Never use relative package imports. If you're writing code that's
in the <tt class="docutils literal">package.sub.m1</tt> module and want to import <tt class="docutils literal">package.sub.m2</tt>,
do not just write <tt class="docutils literal">import m2</tt>, even though it's legal.
Write <tt class="docutils literal">from package.sub import m2</tt> instead. Relative imports can lead to a
module being initialized twice, leading to confusing bugs.</p>
<p>It is sometimes necessary to move imports to a function or class to
avoid problems with circular imports. Gordon McMillan says:</p>
<blockquote>
Circular imports are fine where both modules use the "import <module>"
form of import. They fail when the 2nd module wants to grab a name
out of the first ("from module import name") and the import is at
the top level. That's because names in the 1st are not yet available,
because the first module is busy importing the 2nd.</blockquote>
<p>In this case, if the second module is only used in one function, then the
import can easily be moved into that function. By the time the import
is called, the first module will have finished initializing, and the
second module can do its import.</p>
<p>It may also be necessary to move imports out of the top level of code
if some of the modules are platform-specific. In that case, it may
not even be possible to import all of the modules at the top of the
file. In this case, importing the correct modules in the
corresponding platform-specific code is a good option.</p>
<p>Only move imports into a local scope, such as inside a function
definition, if it's necessary to solve a problem such as avoiding a
circular import or are trying to reduce the initialization time of a
module. This technique is especially helpful if many of the imports
are unnecessary depending on how the program executes. You may also
want to move imports into a function if the modules are only ever used
in that function. Note that loading a module the first time may be
expensive because of the one time initialization of the module, but
loading a module multiple times is virtually free, costing only a couple of
dictionary lookups. Even if the module name has gone out of scope,
the module is probably available in sys.modules.</p>
<p>If only instances of a specific class use a module, then it is
reasonable to import the module in the class's <tt class="docutils literal">__init__</tt> method and
then assign the module to an instance variable so that the module is
always available (via that instance variable) during the life of the
object. Note that to delay an import until the class is instantiated,
the import must be inside a method. Putting the import inside the
class but outside of any method still causes the import to occur when
the module is initialized.</p>
</div>
<div class="section" id="how-can-i-pass-optional-or-keyword-parameters-from-one-function-to-another">
<h2><a class="toc-backref" href="#id12">2.5 How can I pass optional or keyword parameters from one function to another?</a></h2>
<p>Collect the arguments using the <tt class="docutils literal">*</tt> and <tt class="docutils literal">**</tt> specifiers in the function's
parameter list; this gives you the positional arguments as a tuple
and the keyword arguments as a dictionary. You can
then pass these arguments when calling another function by using
<tt class="docutils literal">*</tt> and <tt class="docutils literal">**</tt>:</p>
<pre class="literal-block">
def f(x, *tup, **kwargs):
...
kwargs['width']='14.3c'
...
g(x, *tup, **kwargs)
</pre>
<p>In the unlikely case that you care about Python
versions older than 2.0, use 'apply':</p>
<pre class="literal-block">
def f(x, *tup, **kwargs):
...
kwargs['width']='14.3c'
...
apply(g, (x,)+tup, kwargs)
</pre>
</div>
<div class="section" id="how-do-i-write-a-function-with-output-parameters-call-by-reference">
<h2><a class="toc-backref" href="#id13">2.6 How do I write a function with output parameters (call by reference)?</a></h2>
<p>Remember that arguments are passed by assignment in Python. Since
assignment just creates references to objects, there's no alias
between an argument name in the caller and callee, and so no
call-by-reference per se. You can achieve the desired effect in a
number of ways.</p>
<ol class="arabic">
<li><p class="first">By returning a tuple of the results:</p>
<pre class="literal-block">
def func2(a, b):
a = 'new-value' # a and b are local names
b = b + 1 # assigned to new objects
return a, b # return new values
x, y = 'old-value', 99
x, y = func2(x, y)
print x, y # output: new-value 100
</pre>
<p>This is almost always the clearest solution.</p>
</li>
<li><p class="first">By using global variables. This isn't thread-safe, and is not
recommended.</p>
</li>
<li><p class="first">By passing a mutable (changeable in-place) object:</p>
<pre class="literal-block">
def func1(a):
a[0] = 'new-value' # 'a' references a mutable list
a[1] = a[1] + 1 # changes a shared object
args = ['old-value', 99]
func1(args)
print args[0], args[1] # output: new-value 100
</pre>
</li>
<li><p class="first">By passing in a dictionary that gets mutated:</p>
<pre class="literal-block">
def func3(args):
args['a'] = 'new-value' # args is a mutable dictionary
args['b'] = args['b'] + 1 # change it in-place
args = {'a':' old-value', 'b': 99}
func3(args)
print args['a'], args['b']
</pre>
</li>
<li><p class="first">Or bundle up values in a class instance:</p>
<pre class="literal-block">
class callByRef:
def __init__(self, **args):
for (key, value) in args.items():
setattr(self, key, value)
def func4(args):
args.a = 'new-value' # args is a mutable callByRef
args.b = args.b + 1 # change object in-place
args = callByRef(a='old-value', b=99)
func4(args)
print args.a, args.b
</pre>
<p>There's almost never a good reason to get this complicated.</p>
</li>
</ol>
<p>Your best choice is to return a tuple containing the multiple results.</p>
</div>
<div class="section" id="how-do-you-make-a-higher-order-function-in-python">
<h2><a class="toc-backref" href="#id14">2.7 How do you make a higher order function in Python?</a></h2>
<p>You have two choices: you can use nested scopes
or you can use callable objects. For example, suppose you wanted to
define <tt class="docutils literal">linear(a,b)</tt> which returns a function <tt class="docutils literal">f(x)</tt> that computes the
value <tt class="docutils literal">a*x+b</tt>. Using nested scopes:</p>
<pre class="literal-block">
def linear(a,b):
def result(x):
return a*x + b
return result
</pre>
<p>Or using a callable object:</p>
<pre class="literal-block">
class linear:
def __init__(self, a, b):
self.a, self.b = a,b
def __call__(self, x):
return self.a * x + self.b
</pre>
<p>In both cases:</p>
<pre class="literal-block">
taxes = linear(0.3,2)
</pre>
<p>gives a callable object where taxes(10e6) == 0.3 * 10e6 + 2.</p>
<p>The callable object approach has the disadvantage that it is a bit
slower and results in slightly longer code. However, note that a
collection of callables can share their signature via inheritance:</p>
<pre class="literal-block">
class exponential(linear):
# __init__ inherited
def __call__(self, x):
return self.a * (x ** self.b)
</pre>
<p>Object can encapsulate state for several methods:</p>
<pre class="literal-block">
class counter:
value = 0
def set(self, x): self.value = x
def up(self): self.value=self.value+1
def down(self): self.value=self.value-1
count = counter()
inc, dec, reset = count.up, count.down, count.set
</pre>
<p>Here <tt class="docutils literal">inc()</tt>, <tt class="docutils literal">dec()</tt> and <tt class="docutils literal">reset()</tt> act like functions which share the
same counting variable.</p>
</div>
<div class="section" id="how-do-i-copy-an-object-in-python">
<h2><a class="toc-backref" href="#id15">2.8 How do I copy an object in Python?</a></h2>
<p>In general, try copy.copy() or copy.deepcopy() for the general case. Not all
objects can be copied, but most can.</p>
<p>Some objects can be copied more easily.
Dictionaries have a <tt class="docutils literal">copy()</tt> method:</p>
<pre class="literal-block">
newdict = olddict.copy()
</pre>
<p>Sequences can be copied by slicing:</p>
<pre class="literal-block">
new_l = l[:]
</pre>
</div>
<div class="section" id="how-can-i-find-the-methods-or-attributes-of-an-object">
<h2><a class="toc-backref" href="#id16">2.9 How can I find the methods or attributes of an object?</a></h2>
<p>For an instance x of a user-defined class, <tt class="docutils literal">dir(x)</tt> returns an
alphabetized list of the names containing the instance attributes and
methods and attributes defined by its class.</p>
</div>
<div class="section" id="how-can-my-code-discover-the-name-of-an-object">
<h2><a class="toc-backref" href="#id17">2.10 How can my code discover the name of an object?</a></h2>
<p>Generally speaking, it can't, because objects don't really have
names. Essentially, assignment always binds a name to a value; The
same is true of <tt class="docutils literal">def</tt> and <tt class="docutils literal">class</tt> statements, but in that case the
value is a callable. Consider the following code:</p>
<pre class="literal-block">
class A:
pass
B = A
a = B()
b = a
print b
<__main__.A instance at 016D07CC>
print a
<__main__.A instance at 016D07CC>
</pre>
<p>Arguably the class has a name: even though it is bound to two names
and invoked through the name B the created instance is still reported
as an instance of class A. However, it is impossible to say whether
the instance's name is a or b, since both names are bound to the same
value.</p>
<p>Generally speaking it should not be necessary for your code to "know
the names" of particular values. Unless you are deliberately writing
introspective programs, this is usually an indication that a change of
approach might be beneficial.</p>
<p>In comp.lang.python, Fredrik Lundh once gave an excellent analogy in
answer to this question:</p>
<blockquote>
<p>The same way as you get the name of that cat you found on your
porch: the cat (object) itself cannot tell you its name, and it
doesn't really care -- so the only way to find out what it's called
is to ask all your neighbours (namespaces) if it's their cat
(object)...</p>
<p>....and don't be surprised if you'll find that it's known by many
names, or no name at all!</p>
</blockquote>
</div>
<div class="section" id="is-there-an-equivalent-of-c-s-ternary-operator">
<h2><a class="toc-backref" href="#id18">2.11 Is there an equivalent of C's "?:" ternary operator?</a></h2>
<p>No. In many cases you can mimic a?b:c with "a and b or
c", but there's a flaw: if b is zero (or empty, or None -- anything
that tests false) then c will be selected instead. In many cases you
can prove by looking at the code that this can't happen (e.g. because
b is a constant or has a type that can never be false), but in general
this can be a problem.</p>
<p>Tim Peters (who wishes it was Steve Majewski) suggested the following
solution: (a and [b] or [c])[0]. Because [b] is a singleton list it
is never false, so the wrong path is never taken; then applying [0] to
the whole thing gets the b or c that you really wanted. Ugly, but it
gets you there in the rare cases where it is really inconvenient to
rewrite your code using 'if'.</p>
<p>The best course is usually to write a simple <tt class="docutils literal"><span class="pre">if...else</span></tt> statement.
Another solution is to implement the "?:" operator as a function:</p>
<pre class="literal-block">
def q(cond,on_true,on_false):
if cond:
if not isfunction(on_true): return on_true
else: return apply(on_true)
else:
if not isfunction(on_false): return on_false
else: return apply(on_false)
</pre>
<p>In most cases you'll pass b and c directly: <tt class="docutils literal">q(a,b,c)</tt>. To avoid
evaluating b or c when they shouldn't be, encapsulate them within a
lambda function, e.g.: <tt class="docutils literal">q(a,lambda: b, lambda: c)</tt>.</p>
<p>It has been asked <em>why</em> Python has no if-then-else expression.
There are several answers: many languages do
just fine without one; it can easily lead to less readable code;
no sufficiently "Pythonic" syntax has been discovered; a search
of the standard library found remarkably few places where using an
if-then-else expression would make the code more understandable.</p>
<p>In 2002, <a class="reference external" href="../../peps/pep-0308.html">PEP 308</a> was
written proposing several possible syntaxes and the community was
asked to vote on the issue. The vote was inconclusive. Most people
liked one of the syntaxes, but also hated other syntaxes; many votes
implied that people preferred no ternary operator
rather than having a syntax they hated.</p>
</div>
<div class="section" id="is-it-possible-to-write-obfuscated-one-liners-in-python">
<h2><a class="toc-backref" href="#id19">2.12 Is it possible to write obfuscated one-liners in Python?</a></h2>
<p>Yes. Usually this is done by nesting <cite>lambda</cite> within <cite>lambda</cite>.
See the following three examples, due to Ulf Bartelt:</p>
<pre class="literal-block">
# Primes < 1000
print filter(None,map(lambda y:y*reduce(lambda x,y:x*y!=0,
map(lambda x,y=y:y%x,range(2,int(pow(y,0.5)+1))),1),range(2,1000)))
# First 10 Fibonacci numbers
print map(lambda x,f=lambda x,f:(x<=1) or (f(x-1,f)+f(x-2,f)): f(x,f),
range(10))
# Mandelbrot set
print (lambda Ru,Ro,Iu,Io,IM,Sx,Sy:reduce(lambda x,y:x+y,map(lambda y,
Iu=Iu,Io=Io,Ru=Ru,Ro=Ro,Sy=Sy,L=lambda yc,Iu=Iu,Io=Io,Ru=Ru,Ro=Ro,i=IM,
Sx=Sx,Sy=Sy:reduce(lambda x,y:x+y,map(lambda x,xc=Ru,yc=yc,Ru=Ru,Ro=Ro,
i=i,Sx=Sx,F=lambda xc,yc,x,y,k,f=lambda xc,yc,x,y,k,f:(k<=0)or (x*x+y*y
>=4.0) or 1+f(xc,yc,x*x-y*y+xc,2.0*x*y+yc,k-1,f):f(xc,yc,x,y,k,f):chr(
64+F(Ru+x*(Ro-Ru)/Sx,yc,0,0,i)),range(Sx))):L(Iu+y*(Io-Iu)/Sy),range(Sy
))))(-2.1, 0.7, -1.2, 1.2, 30, 80, 24)
# \___ ___ \___ ___ | | |__ lines on screen
# V V | |______ columns on screen
# | | |__________ maximum of "iterations"
# | |_________________ range on y axis
# |____________________________ range on x axis
</pre>
<p>Don't try this at home, kids!</p>
</div>
</div>
<div class="section" id="numbers-and-strings">
<h1><a class="toc-backref" href="#id20">3 Numbers and strings</a></h1>
<div class="section" id="how-do-i-specify-hexadecimal-and-octal-integers">
<h2><a class="toc-backref" href="#id21">3.1 How do I specify hexadecimal and octal integers?</a></h2>
<p>To specify an octal digit, precede the octal value with a zero. For
example, to set the variable "a" to the octal value "10" (8 in
decimal), type:</p>
<pre class="literal-block">
>>> a = 010
>>> a
8
</pre>
<p>Hexadecimal is just as easy. Simply precede the hexadecimal number with a
zero, and then a lower or uppercase "x". Hexadecimal digits can be specified
in lower or uppercase. For example, in the Python interpreter:</p>
<pre class="literal-block">
>>> a = 0xa5
>>> a
165
>>> b = 0XB2
>>> b
178
</pre>
</div>
<div class="section" id="why-does-22-10-return-3">
<h2><a class="toc-backref" href="#id22">3.2 Why does -22 / 10 return -3?</a></h2>
<p>It's primarily driven by the desire that <tt class="docutils literal">i%j</tt> have the same sign as
<tt class="docutils literal">j</tt>. If you want that, and also want:</p>
<pre class="literal-block">
i == (i/j)*j + (i%j)
</pre>
<p>then integer division has to return the floor. C also requres that identity
to hold, and then compilers that truncate <tt class="docutils literal">i/j</tt> need to make <tt class="docutils literal">i%j</tt> have
the same sign as <tt class="docutils literal">i</tt>.</p>
<p>There are few real use cases for <tt class="docutils literal">i%j</tt> when <tt class="docutils literal">j</tt> is negative. When <tt class="docutils literal">j</tt>
is positive, there are many, and in virtually all of them it's more useful
for <tt class="docutils literal">i%j</tt> to be <tt class="docutils literal">>= 0</tt>. If the clock says 10 now, what did it say 200
hours ago? <tt class="docutils literal"><span class="pre">-190</span> % 12 == 2</tt> is useful; <tt class="docutils literal"><span class="pre">-190</span> % 12 == <span class="pre">-10</span></tt> is a bug
waiting to bite.</p>
</div>
<div class="section" id="how-do-i-convert-a-string-to-a-number">
<h2><a class="toc-backref" href="#id23">3.3 How do I convert a string to a number?</a></h2>
<p>For integers, use the built-in <tt class="docutils literal">int()</tt> type constructor,
e.g. int('144') == 144. Similarly, <tt class="docutils literal">float()</tt> converts to
floating-point, e.g. <tt class="docutils literal"><span class="pre">float('144')</span> == 144.0</tt>.</p>
<p>By default, these interpret the number as decimal, so that
<tt class="docutils literal"><span class="pre">int('0144')</span> == 144</tt> and <tt class="docutils literal"><span class="pre">int('0x144')</span></tt> raises
<tt class="docutils literal">ValueError</tt>. <tt class="docutils literal">int(string, base)</tt> takes the base to convert from
as a second optional argument, so <tt class="docutils literal"><span class="pre">int('0x144',</span> 16) == 324</tt>. If the
base is specified as 0, the number is interpreted using Python's
rules: a leading '0' indicates octal, and '0x' indicates a hex number.</p>
<p>Do not use the built-in function <tt class="docutils literal">eval()</tt> if all you need is to
convert strings to numbers. <tt class="docutils literal">eval()</tt> will be significantly slower
and it presents a security risk: someone could pass you a Python
expression that might have unwanted side effects. For example,
someone could pass <tt class="docutils literal"><span class="pre">__import__('os').system("rm</span> <span class="pre">-rf</span> $HOME")</tt> which
would erase your home directory.</p>
<p><tt class="docutils literal">eval()</tt> also has the effect of interpreting numbers as Python
expressions, so that e.g. eval('09') gives a syntax error because Python
regards numbers starting with '0' as octal (base 8).</p>
</div>
<div class="section" id="how-do-i-convert-a-number-to-a-string">
<h2><a class="toc-backref" href="#id24">3.4 How do I convert a number to a string?</a></h2>
<p>To convert, e.g., the number 144 to the string '144', use the built-in
function <tt class="docutils literal">str()</tt>. If you want a hexadecimal or octal
representation, use the built-in functions <tt class="docutils literal">hex()</tt> or <tt class="docutils literal">oct()</tt>.
For fancy formatting, use <a class="reference external" href="../../doc/lib/typesseq-strings.html">the % operator</a> on strings, e.g. <tt class="docutils literal">"%04d" % 144</tt>
yields '0144' and <tt class="docutils literal"><span class="pre">"%.3f"</span> % (1/3.0)</tt> yields '0.333'. See the library
reference manual for details.</p>
</div>
<div class="section" id="how-do-i-modify-a-string-in-place">
<h2><a class="toc-backref" href="#id25">3.5 How do I modify a string in place?</a></h2>
<p>You can't, because strings are immutable. If you need an object with
this ability, try converting the string to a list or use the array
module:</p>
<pre class="literal-block">
>>> s = "Hello, world"
>>> a = list(s)
>>> print a
['H', 'e', 'l', 'l', 'o', ',', ' ', 'w', 'o', 'r', 'l', 'd']
>>> a[7:] = list("there!")
>>> ''.join(a)
'Hello, there!'
>>> import array
>>> a = array.array('c', s)
>>> print a
array('c', 'Hello, world')
>>> a[0] = 'y' ; print a
array('c', 'yello world')
>>> a.tostring()
'yello, world'
</pre>
</div>
<div class="section" id="how-do-i-use-strings-to-call-functions-methods">
<h2><a class="toc-backref" href="#id26">3.6 How do I use strings to call functions/methods?</a></h2>
<p>There are various techniques.</p>
<ul>
<li><p class="first">The best is to use a dictionary that maps strings to functions. The
primary advantage of this technique is that the strings do not need
to match the names of the functions. This is also the primary
technique used to emulate a case construct:</p>
<pre class="literal-block">
def a():
pass
def b():
pass
dispatch = {'go': a, 'stop': b} # Note lack of parens for funcs
dispatch[get_input()]() # Note trailing parens to call function
</pre>
</li>
<li><p class="first">Use the built-in function <tt class="docutils literal">getattr()</tt>:</p>
<pre class="literal-block">
import foo
getattr(foo, 'bar')()
</pre>
<p>Note that getattr() works on any object, including classes, class
instances, modules, and so on.</p>
<p>This is used in several places in the standard library, like
this:</p>
<pre class="literal-block">
class Foo:
def do_foo(self):
...
def do_bar(self):
...
f = getattr(foo_instance, 'do_' + opname)
f()
</pre>
</li>
<li><p class="first">Use <tt class="docutils literal">locals()</tt> or <tt class="docutils literal">eval()</tt> to resolve the function name:</p>
<pre class="literal-block">
def myFunc():
print "hello"
fname = "myFunc"
f = locals()[fname]
f()
f = eval(fname)
f()
</pre>
<p>Note: Using <tt class="docutils literal">eval()</tt> is slow and dangerous. If you don't have absolute control
over the contents of the string, someone could pass a string that
resulted in an arbitrary function being executed.</p>
</li>
</ul>
</div>
<div class="section" id="is-there-an-equivalent-to-perl-s-chomp-for-removing-trailing-newlines-from-strings">
<h2><a class="toc-backref" href="#id27">3.7 Is there an equivalent to Perl's chomp() for removing trailing newlines from strings?</a></h2>
<p>Starting with Python 2.2, you can use <tt class="docutils literal"><span class="pre">S.rstrip("\r\n")</span></tt> to remove
all occurances of any line terminator from the end of the string <tt class="docutils literal">S</tt>
without removing other trailing whitespace. If the string <tt class="docutils literal">S</tt>
represents more than one line, with several empty lines at the end,
the line terminators for all the blank lines will be removed:</p>
<pre class="literal-block">
>>> lines = ("line 1 \r\n"
... "\r\n"
... "\r\n")
>>> lines.rstrip("\n\r")
"line 1 "
</pre>
<p>Since this is typically only desired when reading text one line at a
time, using <tt class="docutils literal">S.rstrip()</tt> this way works well.</p>
<p>For older versions of Python, There are two partial substitutes:</p>
<ul class="simple">
<li>If you want to remove all trailing whitespace, use the <tt class="docutils literal">rstrip()</tt>
method of string objects. This removes all trailing whitespace, not
just a single newline.</li>
<li>Otherwise, if there is only one line in the string <tt class="docutils literal">S</tt>, use
<tt class="docutils literal"><span class="pre">S.splitlines()[0]</span></tt>.</li>
</ul>
</div>
<div class="section" id="is-there-a-scanf-or-sscanf-equivalent">
<h2><a class="toc-backref" href="#id28">3.8 Is there a scanf() or sscanf() equivalent?</a></h2>
<p>Not as such.</p>
<p>For simple input parsing, the easiest approach is usually to split the
line into whitespace-delimited words using the <tt class="docutils literal">split()</tt> method of
string objects and then convert decimal strings to numeric values using
<tt class="docutils literal">int()</tt> or <tt class="docutils literal">float()</tt>. <tt class="docutils literal">split()</tt> supports an optional "sep"
parameter which is useful if the line uses something other than
whitespace as a separator.</p>
<p>For more complicated input parsing, regular expressions
more powerful than C's <tt class="docutils literal">sscanf()</tt> and better suited for the task.</p>
</div>
<div class="section" id="what-does-unicodeerror-ascii-decoding-encoding-error-ordinal-not-in-range-128-mean">
<h2><a class="toc-backref" href="#id29">3.9 What does 'UnicodeError: ASCII [decoding,encoding] error: ordinal not in range(128)' mean?</a></h2>
<p>This error indicates that your Python installation can handle
only 7-bit ASCII strings. There are a couple ways to fix or
work around the problem.</p>
<p>If your programs must handle data in arbitary character set encodings,
the environment the application runs in will generally identify the
encoding of the data it is handing you. You need to convert the input
to Unicode data using that encoding. For example, a program that
handles email or web input will typically find character set encoding
information in Content-Type headers. This can then be used to
properly convert input data to Unicode. Assuming the string referred
to by <tt class="docutils literal">value</tt> is encoded as UTF-8:</p>
<pre class="literal-block">
value = unicode(value, "utf-8")
</pre>
<p>will return a Unicode object. If the data is not correctly encoded as
UTF-8, the above call will raise a <tt class="docutils literal">UnicodeError</tt> exception.</p>
<p>If you only want strings coverted to Unicode which have non-ASCII
data, you can try converting them first assuming an ASCII encoding,
and then generate Unicode objects if that fails:</p>
<pre class="literal-block">
try:
x = unicode(value, "ascii")
except UnicodeError:
value = unicode(value, "utf-8")
else:
# value was valid ASCII data
pass
</pre>
<p>It's possible to set a default encoding in a file called <tt class="docutils literal">sitecustomize.py</tt>
that's part of the Python library. However, this isn't recommended because changing the Python-wide default encoding may cause third-party extension modules to fail.</p>
<p>Note that on Windows, there is an encoding known as "mbcs", which uses
an encoding specific to your current locale. In many cases, and
particularly when working with COM, this may be an appropriate default
encoding to use.</p>
</div>
</div>
<div class="section" id="sequences-tuples-lists">
<h1><a class="toc-backref" href="#id30">4 Sequences (Tuples/Lists)</a></h1>
<div class="section" id="how-do-i-convert-between-tuples-and-lists">
<h2><a class="toc-backref" href="#id31">4.1 How do I convert between tuples and lists?</a></h2>
<p>The function <tt class="docutils literal">tuple(seq)</tt> converts any sequence (actually, any
iterable) into a tuple with the same items in the same order.</p>
<p>For example, <tt class="docutils literal"><span class="pre">tuple([1,</span> 2, 3])</tt> yields <tt class="docutils literal">(1, 2, 3)</tt> and <tt class="docutils literal"><span class="pre">tuple('abc')</span></tt>
yields <tt class="docutils literal">('a', 'b', 'c')</tt>. If the argument is
a tuple, it does not make a copy but returns the same object, so
it is cheap to call <tt class="docutils literal">tuple()</tt> when you aren't sure that an object
is already a tuple.</p>
<p>The function <tt class="docutils literal">list(seq)</tt> converts any sequence or iterable into a list with
the same items in the same order.
For example, <tt class="docutils literal"><span class="pre">list((1,</span> 2, 3))</tt> yields <tt class="docutils literal">[1, 2, 3]</tt> and <tt class="docutils literal"><span class="pre">list('abc')</span></tt>
yields <tt class="docutils literal">['a', 'b', 'c']</tt>. If the argument is a list,
it makes a copy just like <tt class="docutils literal"><span class="pre">seq[:]</span></tt> would.</p>
</div>
<div class="section" id="what-s-a-negative-index">
<h2><a class="toc-backref" href="#id32">4.2 What's a negative index?</a></h2>
<p>Python sequences are indexed with positive numbers and
negative numbers. For positive numbers 0 is the first index
1 is the second index and so forth. For negative indices -1
is the last index and -2 is the pentultimate (next to last) index
and so forth. Think of <tt class="docutils literal"><span class="pre">seq[-n]</span></tt> as the same as <tt class="docutils literal"><span class="pre">seq[len(seq)-n]</span></tt>.</p>
<p>Using negative indices can be very convenient. For example <tt class="docutils literal"><span class="pre">S[:-1]</span></tt>
is all of the string except for its last character, which is useful
for removing the trailing newline from a string.</p>
</div>
<div class="section" id="how-do-i-iterate-over-a-sequence-in-reverse-order">
<h2><a class="toc-backref" href="#id33">4.3 How do I iterate over a sequence in reverse order?</a></h2>
<p>If it is a list, the fastest solution is</p>
<pre class="literal-block">
list.reverse()
try:
for x in list:
"do something with x"
finally:
list.reverse()
</pre>
<p>This has the disadvantage that while you are in the loop, the list
is temporarily reversed. If you don't like this, you can make a copy.
This appears expensive but is actually faster than other solutions:</p>
<pre class="literal-block">
rev = list[:]
rev.reverse()
for x in rev:
<do something with x>
</pre>
<p>If it's not a list, a more general but slower solution is:</p>
<pre class="literal-block">
for i in range(len(sequence)-1, -1, -1):
x = sequence[i]
<do something with x>
</pre>
<p>A more elegant solution, is to define a class which acts as a sequence
and yields the elements in reverse order (solution due to Steve
Majewski):</p>
<pre class="literal-block">
class Rev:
def __init__(self, seq):
self.forw = seq
def __len__(self):
return len(self.forw)
def __getitem__(self, i):
return self.forw[-(i + 1)]
</pre>
<p>You can now simply write:</p>
<pre class="literal-block">
for x in Rev(list):
<do something with x>
</pre>
<p>Unfortunately, this solution is slowest of all, due to the method
call overhead.</p>
<p>With Python 2.3, you can use an extended slice syntax:</p>
<pre class="literal-block">
for x in sequence[::-1]:
<do something with x>
</pre>
</div>
<div class="section" id="how-do-you-remove-duplicates-from-a-list">
<h2><a class="toc-backref" href="#id34">4.4 How do you remove duplicates from a list?</a></h2>
<p>See the Python Cookbook for a long discussion of many ways to do this:</p>
<blockquote>
<a class="reference external" href="http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52560">http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52560</a></blockquote>
<p>If you don't mind reordering the list, sort it and then scan from the
end of the list, deleting duplicates as you go:</p>
<pre class="literal-block">
if List:
List.sort()
last = List[-1]
for i in range(len(List)-2, -1, -1):
if last==List[i]: del List[i]
else: last=List[i]
</pre>
<p>If all elements of the list may be used as
dictionary keys (i.e. they are all hashable)
this is often faster</p>
<pre class="literal-block">
d = {}
for x in List: d[x]=x
List = d.values()
</pre>
</div>
<div class="section" id="how-do-you-make-an-array-in-python">
<h2><a class="toc-backref" href="#id35">4.5 How do you make an array in Python?</a></h2>
<p>Use a list:</p>
<pre class="literal-block">
["this", 1, "is", "an", "array"]
</pre>
<p>Lists are equivalent to C or Pascal arrays in their time complexity;
the primary difference is that a Python list can contain objects of
many different types.</p>
<p>The <tt class="docutils literal">array</tt> module also provides methods for creating arrays of
fixed types with compact representations, but they are slower to index
than lists. Also note that the Numeric extensions and others define
array-like structures with various characteristics as well.</p>
<p>To get Lisp-style linked lists, you can emulate cons cells using tuples:</p>
<pre class="literal-block">
lisp_list = ("like", ("this", ("example", None) ) )
</pre>
<p>If mutability is desired, you could use lists instead of tuples. Here
the analogue of lisp car is <tt class="docutils literal">lisp_list[0]</tt> and the analogue of cdr
is <tt class="docutils literal">lisp_list[1]</tt>. Only do this if you're sure you really need to,
because it's usually a lot slower than using Python lists.</p>
</div>
<div class="section" id="how-do-i-create-a-multidimensional-list">
<h2><a class="toc-backref" href="#id36">4.6 How do I create a multidimensional list?</a></h2>
<p>You probably tried to make a multidimensional array like this:</p>
<pre class="literal-block">
A = [[None] * 2] * 3
</pre>
<p>This looks correct if you print it:</p>
<pre class="literal-block">
>>> A
[[None, None], [None, None], [None, None]]
</pre>
<p>But when you assign a value, it shows up in multiple places:</p>
<blockquote>
<pre class="doctest-block">
>>> A[0][0] = 5
>>> A
[[5, None], [5, None], [5, None]]
</pre>
</blockquote>
<p>The reason is that replicating a list with <tt class="docutils literal">*</tt> doesn't create copies, it only creates references to the existing objects. The <tt class="docutils literal">*3</tt>
creates a list containing 3 references to the same list of length
two. Changes to one row will show in all rows, which is almost certainly
not what you want.</p>
<p>The suggested approach is to create a list of the desired length first
and then fill in each element with a newly created list:</p>
<pre class="literal-block">
A = [None]*3
for i in range(3):
A[i] = [None] * 2
</pre>
<p>This generates a list containing 3 different lists of length two.
You can also use a list comprehension:</p>
<pre class="literal-block">
w,h = 2,3
A = [ [None]*w for i in range(h) ]
</pre>
<p>Or, you can use an extension that provides a matrix datatype; <a class="reference external" href="http://www.pfdubois.com/numpy/">Numeric
Python</a> is the best known.</p>
</div>
<div class="section" id="how-do-i-apply-a-method-to-a-sequence-of-objects">
<h2><a class="toc-backref" href="#id37">4.7 How do I apply a method to a sequence of objects?</a></h2>
<p>Use a list comprehension:</p>
<pre class="literal-block">
result = [obj.method() for obj in List]
</pre>
<p>More generically, you can try the following function:</p>
<pre class="literal-block">
def method_map(objects, method, arguments):
"""method_map([a,b], "meth", (1,2)) gives [a.meth(1,2), b.meth(1,2)]"""
nobjects = len(objects)
methods = map(getattr, objects, [method]*nobjects)
return map(apply, methods, [arguments]*nobjects)
</pre>
</div>
</div>
<div class="section" id="dictionaries">
<h1><a class="toc-backref" href="#id38">5 Dictionaries</a></h1>
<div class="section" id="how-can-i-get-a-dictionary-to-display-its-keys-in-a-consistent-order">
<h2><a class="toc-backref" href="#id39">5.1 How can I get a dictionary to display its keys in a consistent order?</a></h2>
<p>You can't. Dictionaries store their keys in an unpredictable order,
so the display order of a dictionary's elements will be similarly
unpredictable.</p>
<p>This can be frustrating if you want to save a printable version to a
file, make some changes and then compare it with some other printed
dictionary. In this case, use the <tt class="docutils literal">pprint</tt> module to pretty-print
the dictionary; the items will be presented in order sorted by the key.</p>
<p>A more complicated solution is to subclass <tt class="docutils literal">UserDict.UserDict</tt>
to create a <tt class="docutils literal">SortedDict</tt> class that prints itself in a predictable order.
Here's one simpleminded implementation of such a class:</p>
<pre class="literal-block">
import UserDict, string
class SortedDict(UserDict.UserDict):
def __repr__(self):
result = []
append = result.append
keys = self.data.keys()
keys.sort()
for k in keys:
append("%s: %s" % (`k`, `self.data[k]`))
return "{%s}" % string.join(result, ", ")
___str__ = __repr__
</pre>
<p>This will work for many common situations you might encounter, though
it's far from a perfect solution. The largest flaw is that if some
values in the dictionary are also dictionaries, their values won't be
presented in any particular order.</p>
</div>
<div class="section" id="i-want-to-do-a-complicated-sort-can-you-do-a-schwartzian-transform-in-python">
<h2><a class="toc-backref" href="#id40">5.2 I want to do a complicated sort: can you do a Schwartzian Transform in Python?</a></h2>
<p>Yes, it's quite simple with list comprehensions.</p>
<p>The technique, attributed to Randal Schwartz of the Perl community,
sorts the elements of a list by a metric which maps each element to
its "sort value". To sort a list of strings by their uppercase
values:</p>
<pre class="literal-block">
tmp1 = [ (x.upper(), x) for x in L ] # Schwartzian transform
tmp1.sort()
Usorted = [ x[1] for x in tmp1 ]
</pre>
<p>To sort by the integer value of a subfield extending from positions 10-15
in each string:</p>
<pre class="literal-block">
tmp2 = [ (int(s[10:15]), s) for s in L ] # Schwartzian transform
tmp2.sort()
Isorted = [ x[1] for x in tmp2 ]
</pre>
<p>Note that Isorted may also be computed by</p>
<pre class="literal-block">
def intfield(s):
return int(s[10:15])
def Icmp(s1, s2):
return cmp(intfield(s1), intfield(s2))
Isorted = L[:]
Isorted.sort(Icmp)
</pre>
<p>but since this method calls <tt class="docutils literal">intfield()</tt> many times for each element
of L, it is slower than the Schwartzian Transform.</p>
</div>
<div class="section" id="how-can-i-sort-one-list-by-values-from-another-list">
<h2><a class="toc-backref" href="#id41">5.3 How can I sort one list by values from another list?</a></h2>
<p>Merge them into a single list of tuples, sort the resulting list,
and then pick out the element you want.</p>
<pre class="literal-block">
>>> list1 = ["what", "I'm", "sorting", "by"]
>>> list2 = ["something", "else", "to", "sort"]
>>> pairs = zip(list1, list2)
>>> pairs
[('what', 'something'), ("I'm", 'else'), ('sorting', 'to'), ('by', 'sort')]
>>> pairs.sort()
>>> result = [ x[1] for x in pairs ]
>>> result
['else', 'sort', 'to', 'something']
</pre>
<p>An alternative for the last step is:</p>
<pre class="literal-block">
result = []
for p in pairs: result.append(p[1])
</pre>
<p>If you find this more legible, you might prefer to use this instead of
the final list comprehension. However, it is almost twice as slow for
long lists. Why? First, the <tt class="docutils literal">append()</tt> operation has to reallocate
memory, and while it uses some tricks to avoid doing that each time,
it still has to do it occasionally, and that costs quite a bit.
Second, the expression "result.append" requires an extra attribute
lookup, and third, there's a speed reduction from having to make
all those function calls.</p>
</div>
</div>
<div class="section" id="objects">
<h1><a class="toc-backref" href="#id42">6 Objects</a></h1>
<div class="section" id="what-is-a-class">
<h2><a class="toc-backref" href="#id43">6.1 What is a class?</a></h2>
<p>A class is the particular object type created by executing
a class statement. Class objects are used as templates to create
instance objects, which embody both the data
(attributes) and code (methods) specific to a datatype.</p>
<p>A class can be based on one or more other classes, called its base
class(es). It then inherits the attributes and methods of its base
classes. This allows an object model to be successively refined by
inheritance. You might have a generic <tt class="docutils literal">Mailbox</tt> class that provides
basic accessor methods for a mailbox, and subclasses such as
<tt class="docutils literal">MboxMailbox</tt>, <tt class="docutils literal">MaildirMailbox</tt>, <tt class="docutils literal">OutlookMailbox</tt> that handle
various specific mailbox formats.</p>
</div>
<div class="section" id="what-is-a-method">
<h2><a class="toc-backref" href="#id44">6.2 What is a method?</a></h2>
<p>A method is a function on some object <tt class="docutils literal">x</tt> that you normally call as
<tt class="docutils literal"><span class="pre">x.name(arguments...)</span></tt>. Methods are defined as functions inside the
class definition:</p>
<pre class="literal-block">
class C:
def meth (self, arg):
return arg*2 + self.attribute
</pre>
</div>
<div class="section" id="what-is-self">
<h2><a class="toc-backref" href="#id45">6.3 What is self?</a></h2>
<p>Self is merely a conventional name for the first argument of a method.
A method defined as <tt class="docutils literal">meth(self, a, b, c)</tt> should be called as
<tt class="docutils literal">x.meth(a, b, c)</tt> for some instance <tt class="docutils literal">x</tt> of the class in which the
definition occurs; the called method will think it is called as
<tt class="docutils literal">meth(x, a, b, c)</tt>.</p>
<p>See also
<a class="reference external" href="general.html#why-must-self-be-used-explicitly-in-method-definitions-and-calls">Why must 'self' be used explicitly in method definitions and calls?</a></p>
</div>
<div class="section" id="how-do-i-check-if-an-object-is-an-instance-of-a-given-class-or-of-a-subclass-of-it">
<h2><a class="toc-backref" href="#id46">6.4 How do I check if an object is an instance of a given class or of a subclass of it?</a></h2>
<p>Use the built-in function <tt class="docutils literal">isinstance(obj, cls)</tt>. You can check if
an object is an instance of any of a number of classes by providing a tuple instead of a single class, e.g. <tt class="docutils literal">isinstance(obj, (class1, class2, <span class="pre">...))</span></tt>,
and can also check whether an object is one of Python's built-in types, e.g.
<tt class="docutils literal">isinstance(obj, str)</tt> or <tt class="docutils literal">isinstance(obj, (int, long, float, complex))</tt>.</p>
<p>Note that most programs do not use <tt class="docutils literal">isinstance()</tt> on user-defined
classes very often. If you are developing the classes yourself, a
more proper object-oriented style is to define methods on the classes
that encapsulate a particular behaviour, instead of checking the
object's class and doing a different thing based on what class it is.
For example, if you have a function that does something:</p>
<pre class="literal-block">
def search (obj):
if isinstance(obj, Mailbox):
# ... code to search a mailbox
elif isinstance(obj, Document):
# ... code to search a document
elif ...
</pre>
<p>A better approach is to define a <tt class="docutils literal">search()</tt> method on all the
classes and just call it:</p>
<pre class="literal-block">
class Mailbox:
def search(self):
# ... code to search a mailbox
class Document:
def search(self):
# ... code to search a document
obj.search()
</pre>
</div>
<div class="section" id="what-is-delegation">
<h2><a class="toc-backref" href="#id47">6.5 What is delegation?</a></h2>
<p>Delegation is an object oriented technique (also called a design
pattern). Let's say you have an object <tt class="docutils literal">x</tt> and want to change the
behaviour of just one of its methods. You can create a new class that
provides a new implementation of the method you're interested in changing
and delegates all other methods to the corresponding method of <tt class="docutils literal">x</tt>.</p>
<p>Python programmers can easily implement delegation. For example, the
following class implements a class that behaves like a file but
converts all written data to uppercase:</p>
<pre class="literal-block">
class UpperOut:
def __init__(self, outfile):
self.__outfile = outfile
def write(self, s):
self.__outfile.write(s.upper())
def __getattr__(self, name):
return getattr(self.__outfile, name)
</pre>
<p>Here the <tt class="docutils literal">UpperOut</tt> class redefines the <tt class="docutils literal">write()</tt> method to
convert the argument string to uppercase before calling the underlying
<tt class="docutils literal">self.__outfile.write()</tt> method. All other methods are delegated to
the underlying <tt class="docutils literal">self.__outfile</tt> object. The delegation is
accomplished via the <tt class="docutils literal">__getattr__</tt> method; consult <a class="reference external" href="../../doc/ref/attribute-access.html">the language
reference</a> for
more information about controlling attribute access.</p>
<p>Note that for more general cases delegation can get trickier. When
attributes must be set as well as retrieved, the class must define a
<tt class="docutils literal">__settattr__</tt> method too, and it must do so carefully. The basic
implementation of __setattr__ is roughly equivalent to the following:</p>
<pre class="literal-block">
class X:
...
def __setattr__(self, name, value):
self.__dict__[name] = value
...
</pre>
<p>Most __setattr__ implementations must modify
self.__dict__ to store local state for self without
causing an infinite recursion.</p>
</div>
<div class="section" id="how-do-i-call-a-method-defined-in-a-base-class-from-a-derived-class-that-overrides-it">
<h2><a class="toc-backref" href="#id48">6.6 How do I call a method defined in a base class from a derived class that overrides it?</a></h2>
<p>If you're using new-style classes, use the built-in <tt class="docutils literal">super()</tt> function:</p>
<pre class="literal-block">
class Derived(Base):
def meth (self):
super(Derived, self).meth()
</pre>
<p>If you're using classic classes: For a class definition such as
<tt class="docutils literal">class Derived(Base): ...</tt> you can call method <tt class="docutils literal">meth()</tt> defined in
<tt class="docutils literal">Base</tt> (or one of <tt class="docutils literal">Base</tt>'s base classes) as <tt class="docutils literal">Base.meth(self,
<span class="pre">arguments...)</span></tt>. Here, <tt class="docutils literal">Base.meth</tt> is an unbound method, so you
need to provide the <tt class="docutils literal">self</tt> argument.</p>
</div>
<div class="section" id="how-can-i-organize-my-code-to-make-it-easier-to-change-the-base-class">
<h2><a class="toc-backref" href="#id49">6.7 How can I organize my code to make it easier to change the base class?</a></h2>
<p>You could define an alias for the base class, assign the real base
class to it before your class definition, and use the alias throughout
your class. Then all you have to change is the value assigned to the
alias. Incidentally, this trick is also handy if you want to decide
dynamically (e.g. depending on availability of resources) which base
class to use. Example:</p>
<pre class="literal-block">
BaseAlias = <real base class>
class Derived(BaseAlias):
def meth(self):
BaseAlias.meth(self)
...
</pre>
</div>
<div class="section" id="how-do-i-create-static-class-data-and-static-class-methods">
<h2><a class="toc-backref" href="#id50">6.8 How do I create static class data and static class methods?</a></h2>
<p>Static data (in the sense of C++ or Java) is easy; static methods
(again in the sense of C++ or Java) are not supported directly.</p>
<p>For static data, simply define a class attribute. To assign a new
value to the attribute, you have to explicitly use the class name in
the assignment:</p>
<pre class="literal-block">
class C:
count = 0 # number of times C.__init__ called
def __init__(self):
C.count = C.count + 1
def getcount(self):
return C.count # or return self.count
</pre>
<p><tt class="docutils literal">c.count</tt> also refers to <tt class="docutils literal">C.count</tt> for any <tt class="docutils literal">c</tt> such that
<tt class="docutils literal">isinstance(c, C)</tt> holds, unless overridden by <tt class="docutils literal">c</tt> itself or by some
class on the base-class search path from <tt class="docutils literal">c.__class__</tt> back to <tt class="docutils literal">C</tt>.</p>
<p>Caution: within a method of C, an assignment like <tt class="docutils literal">self.count = 42</tt>
creates a new and unrelated instance vrbl named "count" in <tt class="docutils literal">self</tt>'s own dict.
Rebinding of a class-static data name must always specify the class
whether inside a method or not:</p>
<pre class="literal-block">
C.count = 314
</pre>
<p>Static methods are possible when you're using new-style classes:</p>
<pre class="literal-block">
class C:
def static(arg1, arg2, arg3):
# No 'self' parameter!
...
static = staticmethod(static)
</pre>
<p>However, a far more straightforward way to get the effect of a static
method is via a simple module-level function:</p>
<pre class="literal-block">
def getcount():
return C.count
</pre>
<p>If your code is structured so as to define one class (or tightly
related class hierarchy) per module, this supplies the desired
encapsulation.</p>
</div>
<div class="section" id="how-can-i-overload-constructors-or-methods-in-python">
<h2><a class="toc-backref" href="#id51">6.9 How can I overload constructors (or methods) in Python?</a></h2>
<p>This answer actually applies to all methods, but the question
usually comes up first in the context of constructors.</p>
<p>In C++ you'd write</p>
<pre class="literal-block">
class C {
C() { cout << "No arguments\n"; }
C(int i) { cout << "Argument is " << i << "\n"; }
}
</pre>
<p>in Python you have to write a single constructor that catches all
cases using default arguments. For example:</p>
<pre class="literal-block">
class C:
def __init__(self, i=None):
if i is None:
print "No arguments"
else:
print "Argument is", i
</pre>
<p>This is not entirely equivalent, but close enough in practice.</p>
<p>You could also try a variable-length argument list, e.g.</p>
<pre class="literal-block">
def __init__(self, *args):
....
</pre>
<p>The same approach works for all method definitions.</p>
</div>
<div class="section" id="i-try-to-use-spam-and-i-get-an-error-about-someclassname-spam">
<h2><a class="toc-backref" href="#id52">6.10 I try to use __spam and I get an error about _SomeClassName__spam.</a></h2>
<p>Variables with double leading underscore are "mangled" to provide a
simple but effective way to define class private variables. Any
identifier of the form <tt class="docutils literal">__spam</tt> (at least two leading
underscores, at most one trailing underscore) is textually
replaced with <tt class="docutils literal">_classname__spam</tt>, where <tt class="docutils literal">classname</tt> is the
current class name with any leading underscores stripped.</p>
<p>This doesn't guarantee privacy: an outside user can still deliberately
access the "_classname__spam" attribute, and private values are visible
in the object's <tt class="docutils literal">__dict__</tt>. Many Python programmers never bother to use
private variable names at all.</p>
</div>
<div class="section" id="my-class-defines-del-but-it-is-not-called-when-i-delete-the-object">
<h2><a class="toc-backref" href="#id53">6.11 My class defines __del__ but it is not called when I delete the object.</a></h2>
<p>There are several possible reasons for this.</p>
<p>The del statement does not necessarily call __del__ -- it simply
decrements the object's reference count, and if this reaches zero
__del__ is called.</p>
<p>If your data structures contain circular links (e.g. a tree where each
child has a parent reference and each parent has a list of children)
the reference counts will never go back to zero. Once in a while
Python runs an algorithm to detect such cycles, but the garbage
collector might run some time after the last reference to your data
structure vanishes, so your __del__ method may be called at an
inconvenient and random time. This is inconvenient if you're trying to
reproduce a problem. Worse, the order in which object's __del__
methods are executed is arbitrary. You can run <tt class="docutils literal">gc.collect()</tt> to
force a collection, but there <em>are</em> pathological cases where objects will
never be collected.</p>
<p>Despite the cycle collector, it's still a good idea to define an
explicit <tt class="docutils literal">close()</tt> method on objects to be called whenever you're
done with them. The <tt class="docutils literal">close()</tt> method can then remove attributes
that refer to subobjecs. Don't call <tt class="docutils literal">__del__</tt> directly --
<tt class="docutils literal">__del__</tt> should call <tt class="docutils literal">close()</tt> and <tt class="docutils literal">close()</tt> should make sure
that it can be called more than once for the same object.</p>
<p>Another way to avoid cyclical references is to use the "weakref"
module, which allows you to point to objects without incrementing
their reference count. Tree data structures, for instance, should use
weak references for their parent and sibling references (if they need
them!).</p>
<p>If the object has ever been a local variable in a function that caught
an expression in an except clause, chances are that a reference to the
object still exists in that function's stack frame as contained in the
stack trace. Normally, calling <tt class="docutils literal">sys.exc_clear()</tt> will take care of
this by clearing the last recorded exception.</p>
<p>Finally, if your __del__ method raises an exception, a warning message
is printed to sys.stderr.</p>
</div>
<div class="section" id="how-do-i-get-a-list-of-all-instances-of-a-given-class">
<h2><a class="toc-backref" href="#id54">6.12 How do I get a list of all instances of a given class?</a></h2>
<p>Python does not keep track of all instances of a class (or of a
built-in type). You can program the class's constructor to keep track
of all instances by keeping a list of weak references to each
instance.</p>
</div>
</div>
<div class="section" id="modules">
<h1><a class="toc-backref" href="#id55">7 Modules</a></h1>
<div class="section" id="how-do-i-create-a-pyc-file">
<h2><a class="toc-backref" href="#id56">7.1 How do I create a .pyc file?</a></h2>
<p>When a module is imported for the first time (or when the source is
more recent than the current compiled file) a <tt class="docutils literal">.pyc</tt> file containing
the compiled code should be created in the same directory as the
<tt class="docutils literal">.py</tt> file.</p>
<p>One reason that a <tt class="docutils literal">.pyc</tt> file may not be created is permissions
problems with the directory. This can happen, for example, if you
develop as one user but run as another, such as if you are testing
with a web server. Creation of a .pyc file is automatic if you're
importing a module and Python has the ability (permissions, free
space, etc...) to write the compiled module back to the directory.</p>
<p>Running Python on a top level script is not considered an import and
no <tt class="docutils literal">.pyc</tt> will be created. For example, if you have a top-level
module <tt class="docutils literal">abc.py</tt> that imports another module <tt class="docutils literal">xyz.py</tt>, when you run
abc, <tt class="docutils literal">xyz.pyc</tt> will be created since xyz is imported, but no
<tt class="docutils literal">abc.pyc</tt> file will be created since <tt class="docutils literal">abc.py</tt> isn't being
imported.</p>
<p>If you need to create abc.pyc -- that is, to create a .pyc file for a
module that is not imported -- you can, using the py_compile and
compileall modules.</p>
<p>The <tt class="docutils literal">py_compile</tt> module can manually compile any module. One way is
to use the <tt class="docutils literal">compile()</tt> function in that module interactively:</p>
<pre class="literal-block">
>>> import py_compile
>>> py_compile.compile('abc.py')
</pre>
<p>This will write the <tt class="docutils literal">.pyc</tt> to the same location as <tt class="docutils literal">abc.py</tt> (or
you can override that with the optional parameter <tt class="docutils literal">cfile</tt>).</p>
<p>You can also automatically compile all files in a directory or
directories using the <tt class="docutils literal">compileall</tt> module.
You can do it from the shell prompt by running <tt class="docutils literal">compileall.py</tt>
and providing the path of a directory containing Python files to compile:</p>
<pre class="literal-block">
python compileall.py .
</pre>
</div>
<div class="section" id="how-do-i-find-the-current-module-name">
<h2><a class="toc-backref" href="#id57">7.2 How do I find the current module name?</a></h2>
<p>A module can find out its own module name by looking at the predefined
global variable <tt class="docutils literal">__name__</tt>. If this has the value '__main__', the
program is running as a script. Many modules that are usually used by
importing them also provide a command-line interface or a self-test,
and only execute this code after checking <tt class="docutils literal">__name__</tt>:</p>
<pre class="literal-block">
def main():
print 'Running test...'
...
if __name__ == '__main__':
main()
</pre>
</div>
<div class="section" id="how-can-i-have-modules-that-mutually-import-each-other">
<h2><a class="toc-backref" href="#id58">7.3 How can I have modules that mutually import each other?</a></h2>
<p>Suppose you have the following modules:</p>
<p>foo.py:</p>
<pre class="literal-block">
from bar import bar_var
foo_var=1
</pre>
<p>bar.py:</p>
<pre class="literal-block">
from foo import foo_var
bar_var=2
</pre>
<p>The problem is that the interpreter will perform the following steps:</p>
<ul class="simple">
<li>main imports foo</li>
<li>Empty globals for foo are created</li>
<li>foo is compiled and starts executing</li>
<li>foo imports bar</li>
<li>Empty globals for bar are created</li>
<li>bar is compiled and starts executing</li>
<li>bar imports foo (which is a no-op since there already is a module named foo)</li>
<li>bar.foo_var = foo.foo_var</li>
</ul>
<p>The last step fails, because Python isn't done with interpreting <tt class="docutils literal">foo</tt>
yet and the global symbol dictionary for <tt class="docutils literal">foo</tt> is still empty.</p>
<p>The same thing happens when you use <tt class="docutils literal">import foo</tt>, and then try to
access <tt class="docutils literal">foo.foo_var</tt> in global code.</p>
<p>There are (at least) three possible workarounds for this problem.</p>
<p>Guido van Rossum recommends avoiding all uses of <tt class="docutils literal">from <module>
import ...</tt>, and placing all code inside functions. Initializations
of global variables and class variables should use constants or
built-in functions only. This means everything from an imported
module is referenced as <tt class="docutils literal"><span class="pre"><module>.<name></span></tt>.</p>
<p>Jim Roskind suggests performing steps in the following order in each
module:</p>
<ul class="simple">
<li>exports (globals, functions, and classes that don't need imported base classes)</li>
<li><tt class="docutils literal">import</tt> statements</li>
<li>active code (including globals that are initialized from imported values).</li>
</ul>
<p>van Rossum doesn't like this approach much because the imports
appear in a strange place, but it does work.</p>
<p>Matthias Urlichs recommends restructuring your code so that the
recursive import is not necessary in the first place.</p>
<p>These solutions are not mutually exclusive.</p>
</div>
<div class="section" id="import-x-y-z-returns-module-x-how-do-i-get-z">
<h2><a class="toc-backref" href="#id59">7.4 __import__('x.y.z') returns <module 'x'>; how do I get z?</a></h2>
<p>Try:</p>
<pre class="literal-block">
__import__('x.y.z').y.z
</pre>
<p>For more realistic situations, you may have to do something like</p>
<pre class="literal-block">
m = __import__(s)
for i in s.split(".")[1:]:
m = getattr(m, i)
</pre>
</div>
<div class="section" id="when-i-edit-an-imported-module-and-reimport-it-the-changes-don-t-show-up-why-does-this-happen">
<h2><a class="toc-backref" href="#id60">7.5 When I edit an imported module and reimport it, the changes don't show up. Why does this happen?</a></h2>
<p>For reasons of efficiency as well as consistency, Python only reads
the module file on the first time a module is imported. If it didn't,
in a program consisting of many modules where each one imports the
same basic module, the basic module would be parsed and re-parsed many
times. To force rereading of a changed module, do this:</p>
<pre class="literal-block">
import modname
reload(modname)
</pre>
<p>Warning: this technique is not 100% fool-proof. In particular,
modules containing statements like</p>
<pre class="literal-block">
from modname import some_objects
</pre>
<p>will continue to work with the old version of the imported objects.
If the module contains class definitions, existing class instances
will <em>not</em> be updated to use the new class definition. This can
result in the following paradoxical behaviour:</p>
<pre class="literal-block">
>>> import cls
>>> c = cls.C() # Create an instance of C
>>> reload(cls)
<module 'cls' from 'cls.pyc'>
>>> isinstance(c, cls.C) # isinstance is false?!?
False
</pre>
<p>The nature of the problem is made clear if you print out the class objects:</p>
<blockquote>
<pre class="doctest-block">
>>> c.__class__
<class cls.C at 0x7352a0>
>>> cls.C
<class cls.C at 0x4198d0>
</pre>
</blockquote>
</div>
</div>
</div>
</body>
</html>
|