home *** CD-ROM | disk | FTP | other *** search
/ Mac Easy 2010 May / Mac Life Ubuntu.iso / casper / filesystem.squashfs / usr / share / doc / python / faq / general.html < prev    next >
Encoding:
Extensible Markup Language  |  2009-04-19  |  90.7 KB  |  1,622 lines

  1. <?xml version="1.0" encoding="utf-8" ?>
  2. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  3. <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
  4. <head>
  5. <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  6. <meta name="generator" content="Docutils 0.5: http://docutils.sourceforge.net/" />
  7. <title>General Python FAQ</title>
  8. <meta name="date" content="2006-02-26" />
  9. <style type="text/css">
  10.  
  11. /*
  12. :Author: David Goodger (goodger@python.org)
  13. :Id: $Id: html4css1.css 5196 2007-06-03 20:25:28Z wiemann $
  14. :Copyright: This stylesheet has been placed in the public domain.
  15.  
  16. Default cascading style sheet for the HTML output of Docutils.
  17.  
  18. See http://docutils.sf.net/docs/howto/html-stylesheets.html for how to
  19. customize this style sheet.
  20. */
  21.  
  22. /* used to remove borders from tables and images */
  23. .borderless, table.borderless td, table.borderless th {
  24.   border: 0 }
  25.  
  26. table.borderless td, table.borderless th {
  27.   /* Override padding for "table.docutils td" with "! important".
  28.      The right padding separates the table cells. */
  29.   padding: 0 0.5em 0 0 ! important }
  30.  
  31. .first {
  32.   /* Override more specific margin styles with "! important". */
  33.   margin-top: 0 ! important }
  34.  
  35. .last, .with-subtitle {
  36.   margin-bottom: 0 ! important }
  37.  
  38. .hidden {
  39.   display: none }
  40.  
  41. a.toc-backref {
  42.   text-decoration: none ;
  43.   color: black }
  44.  
  45. blockquote.epigraph {
  46.   margin: 2em 5em ; }
  47.  
  48. dl.docutils dd {
  49.   margin-bottom: 0.5em }
  50.  
  51. /* Uncomment (and remove this text!) to get bold-faced definition list terms
  52. dl.docutils dt {
  53.   font-weight: bold }
  54. */
  55.  
  56. div.abstract {
  57.   margin: 2em 5em }
  58.  
  59. div.abstract p.topic-title {
  60.   font-weight: bold ;
  61.   text-align: center }
  62.  
  63. div.admonition, div.attention, div.caution, div.danger, div.error,
  64. div.hint, div.important, div.note, div.tip, div.warning {
  65.   margin: 2em ;
  66.   border: medium outset ;
  67.   padding: 1em }
  68.  
  69. div.admonition p.admonition-title, div.hint p.admonition-title,
  70. div.important p.admonition-title, div.note p.admonition-title,
  71. div.tip p.admonition-title {
  72.   font-weight: bold ;
  73.   font-family: sans-serif }
  74.  
  75. div.attention p.admonition-title, div.caution p.admonition-title,
  76. div.danger p.admonition-title, div.error p.admonition-title,
  77. div.warning p.admonition-title {
  78.   color: red ;
  79.   font-weight: bold ;
  80.   font-family: sans-serif }
  81.  
  82. /* Uncomment (and remove this text!) to get reduced vertical space in
  83.    compound paragraphs.
  84. div.compound .compound-first, div.compound .compound-middle {
  85.   margin-bottom: 0.5em }
  86.  
  87. div.compound .compound-last, div.compound .compound-middle {
  88.   margin-top: 0.5em }
  89. */
  90.  
  91. div.dedication {
  92.   margin: 2em 5em ;
  93.   text-align: center ;
  94.   font-style: italic }
  95.  
  96. div.dedication p.topic-title {
  97.   font-weight: bold ;
  98.   font-style: normal }
  99.  
  100. div.figure {
  101.   margin-left: 2em ;
  102.   margin-right: 2em }
  103.  
  104. div.footer, div.header {
  105.   clear: both;
  106.   font-size: smaller }
  107.  
  108. div.line-block {
  109.   display: block ;
  110.   margin-top: 1em ;
  111.   margin-bottom: 1em }
  112.  
  113. div.line-block div.line-block {
  114.   margin-top: 0 ;
  115.   margin-bottom: 0 ;
  116.   margin-left: 1.5em }
  117.  
  118. div.sidebar {
  119.   margin: 0 0 0.5em 1em ;
  120.   border: medium outset ;
  121.   padding: 1em ;
  122.   background-color: #ffffee ;
  123.   width: 40% ;
  124.   float: right ;
  125.   clear: right }
  126.  
  127. div.sidebar p.rubric {
  128.   font-family: sans-serif ;
  129.   font-size: medium }
  130.  
  131. div.system-messages {
  132.   margin: 5em }
  133.  
  134. div.system-messages h1 {
  135.   color: red }
  136.  
  137. div.system-message {
  138.   border: medium outset ;
  139.   padding: 1em }
  140.  
  141. div.system-message p.system-message-title {
  142.   color: red ;
  143.   font-weight: bold }
  144.  
  145. div.topic {
  146.   margin: 2em }
  147.  
  148. h1.section-subtitle, h2.section-subtitle, h3.section-subtitle,
  149. h4.section-subtitle, h5.section-subtitle, h6.section-subtitle {
  150.   margin-top: 0.4em }
  151.  
  152. h1.title {
  153.   text-align: center }
  154.  
  155. h2.subtitle {
  156.   text-align: center }
  157.  
  158. hr.docutils {
  159.   width: 75% }
  160.  
  161. img.align-left {
  162.   clear: left }
  163.  
  164. img.align-right {
  165.   clear: right }
  166.  
  167. ol.simple, ul.simple {
  168.   margin-bottom: 1em }
  169.  
  170. ol.arabic {
  171.   list-style: decimal }
  172.  
  173. ol.loweralpha {
  174.   list-style: lower-alpha }
  175.  
  176. ol.upperalpha {
  177.   list-style: upper-alpha }
  178.  
  179. ol.lowerroman {
  180.   list-style: lower-roman }
  181.  
  182. ol.upperroman {
  183.   list-style: upper-roman }
  184.  
  185. p.attribution {
  186.   text-align: right ;
  187.   margin-left: 50% }
  188.  
  189. p.caption {
  190.   font-style: italic }
  191.  
  192. p.credits {
  193.   font-style: italic ;
  194.   font-size: smaller }
  195.  
  196. p.label {
  197.   white-space: nowrap }
  198.  
  199. p.rubric {
  200.   font-weight: bold ;
  201.   font-size: larger ;
  202.   color: maroon ;
  203.   text-align: center }
  204.  
  205. p.sidebar-title {
  206.   font-family: sans-serif ;
  207.   font-weight: bold ;
  208.   font-size: larger }
  209.  
  210. p.sidebar-subtitle {
  211.   font-family: sans-serif ;
  212.   font-weight: bold }
  213.  
  214. p.topic-title {
  215.   font-weight: bold }
  216.  
  217. pre.address {
  218.   margin-bottom: 0 ;
  219.   margin-top: 0 ;
  220.   font-family: serif ;
  221.   font-size: 100% }
  222.  
  223. pre.literal-block, pre.doctest-block {
  224.   margin-left: 2em ;
  225.   margin-right: 2em }
  226.  
  227. span.classifier {
  228.   font-family: sans-serif ;
  229.   font-style: oblique }
  230.  
  231. span.classifier-delimiter {
  232.   font-family: sans-serif ;
  233.   font-weight: bold }
  234.  
  235. span.interpreted {
  236.   font-family: sans-serif }
  237.  
  238. span.option {
  239.   white-space: nowrap }
  240.  
  241. span.pre {
  242.   white-space: pre }
  243.  
  244. span.problematic {
  245.   color: red }
  246.  
  247. span.section-subtitle {
  248.   /* font-size relative to parent (h1..h6 element) */
  249.   font-size: 80% }
  250.  
  251. table.citation {
  252.   border-left: solid 1px gray;
  253.   margin-left: 1px }
  254.  
  255. table.docinfo {
  256.   margin: 2em 4em }
  257.  
  258. table.docutils {
  259.   margin-top: 0.5em ;
  260.   margin-bottom: 0.5em }
  261.  
  262. table.footnote {
  263.   border-left: solid 1px black;
  264.   margin-left: 1px }
  265.  
  266. table.docutils td, table.docutils th,
  267. table.docinfo td, table.docinfo th {
  268.   padding-left: 0.5em ;
  269.   padding-right: 0.5em ;
  270.   vertical-align: top }
  271.  
  272. table.docutils th.field-name, table.docinfo th.docinfo-name {
  273.   font-weight: bold ;
  274.   text-align: left ;
  275.   white-space: nowrap ;
  276.   padding-left: 0 }
  277.  
  278. h1 tt.docutils, h2 tt.docutils, h3 tt.docutils,
  279. h4 tt.docutils, h5 tt.docutils, h6 tt.docutils {
  280.   font-size: 100% }
  281.  
  282. ul.auto-toc {
  283.   list-style-type: none }
  284.  
  285. </style>
  286. </head>
  287. <body>
  288. <div class="document" id="general-python-faq">
  289. <h1 class="title">General Python FAQ</h1>
  290. <table class="docinfo" frame="void" rules="none">
  291. <col class="docinfo-name" />
  292. <col class="docinfo-content" />
  293. <tbody valign="top">
  294. <tr><th class="docinfo-name">Date:</th>
  295. <td>2006-02-26</td></tr>
  296. <tr><th class="docinfo-name">Version:</th>
  297. <td>8958</td></tr>
  298. <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>
  299. </tr>
  300. </tbody>
  301. </table>
  302. <div class="contents topic" id="contents">
  303. <p class="topic-title first">Contents</p>
  304. <ul class="auto-toc simple">
  305. <li><a class="reference internal" href="#general-information" id="id1">1   General Information</a><ul class="auto-toc">
  306. <li><a class="reference internal" href="#what-is-python" id="id2">1.1   What is Python?</a></li>
  307. <li><a class="reference internal" href="#why-was-python-created-in-the-first-place" id="id3">1.2   Why was Python created in the first place?</a></li>
  308. <li><a class="reference internal" href="#what-is-python-good-for" id="id4">1.3   What is Python good for?</a></li>
  309. <li><a class="reference internal" href="#how-does-the-python-version-numbering-scheme-work" id="id5">1.4   How does the Python version numbering scheme work?</a></li>
  310. <li><a class="reference internal" href="#are-there-copyright-restrictions-on-the-use-of-python" id="id6">1.5   Are there copyright restrictions on the use of Python?</a></li>
  311. <li><a class="reference internal" href="#how-do-i-obtain-a-copy-of-the-python-source" id="id7">1.6   How do I obtain a copy of the Python source?</a></li>
  312. <li><a class="reference internal" href="#how-do-i-get-documentation-on-python" id="id8">1.7   How do I get documentation on Python?</a></li>
  313. <li><a class="reference internal" href="#i-ve-never-programmed-before-is-there-a-python-tutorial" id="id9">1.8   I've never programmed before. Is there a Python tutorial?</a></li>
  314. <li><a class="reference internal" href="#are-there-other-ftp-sites-that-mirror-the-python-distribution" id="id10">1.9   Are there other FTP sites that mirror the Python distribution?</a></li>
  315. <li><a class="reference internal" href="#is-there-a-newsgroup-or-mailing-list-devoted-to-python" id="id11">1.10   Is there a newsgroup or mailing list devoted to Python?</a></li>
  316. <li><a class="reference internal" href="#how-do-i-get-a-beta-test-version-of-python" id="id12">1.11   How do I get a beta test version of Python?</a></li>
  317. <li><a class="reference internal" href="#how-do-i-submit-bug-reports-and-patches-for-python" id="id13">1.12   How do I submit bug reports and patches for Python?</a></li>
  318. <li><a class="reference internal" href="#are-there-any-published-articles-about-python-that-i-can-reference" id="id14">1.13   Are there any published articles about Python that I can reference?</a></li>
  319. <li><a class="reference internal" href="#are-there-any-books-on-python" id="id15">1.14   Are there any books on Python?</a></li>
  320. <li><a class="reference internal" href="#where-in-the-world-is-www-python-org-located" id="id16">1.15   Where in the world is www.python.org located?</a></li>
  321. <li><a class="reference internal" href="#why-is-it-called-python" id="id17">1.16   Why is it called Python?</a></li>
  322. <li><a class="reference internal" href="#do-i-have-to-like-monty-python-s-flying-circus" id="id18">1.17   Do I have to like "Monty Python's Flying Circus"?</a></li>
  323. </ul>
  324. </li>
  325. <li><a class="reference internal" href="#python-in-the-real-world" id="id19">2   Python in the real world</a><ul class="auto-toc">
  326. <li><a class="reference internal" href="#how-stable-is-python" id="id20">2.1   How stable is Python?</a></li>
  327. <li><a class="reference internal" href="#how-many-people-are-using-python" id="id21">2.2   How many people are using Python?</a></li>
  328. <li><a class="reference internal" href="#have-any-significant-projects-been-done-in-python" id="id22">2.3   Have any significant projects been done in Python?</a></li>
  329. <li><a class="reference internal" href="#what-new-developments-are-expected-for-python-in-the-future" id="id23">2.4   What new developments are expected for Python in the future?</a></li>
  330. <li><a class="reference internal" href="#is-it-reasonable-to-propose-incompatible-changes-to-python" id="id24">2.5   Is it reasonable to propose incompatible changes to Python?</a></li>
  331. <li><a class="reference internal" href="#what-is-the-python-software-foundation" id="id25">2.6   What is the Python Software Foundation?</a></li>
  332. <li><a class="reference internal" href="#is-python-y2k-year-2000-compliant" id="id26">2.7   Is Python Y2K (Year 2000) Compliant?</a></li>
  333. <li><a class="reference internal" href="#is-python-a-good-language-for-beginning-programmers" id="id27">2.8   Is Python a good language for beginning programmers?</a></li>
  334. </ul>
  335. </li>
  336. <li><a class="reference internal" href="#upgrading-python" id="id28">3   Upgrading Python</a><ul class="auto-toc">
  337. <li><a class="reference internal" href="#what-is-this-bsddb185-module-my-application-keeps-complaining-about" id="id29">3.1   What is this bsddb185 module my application keeps complaining about?</a></li>
  338. </ul>
  339. </li>
  340. <li><a class="reference internal" href="#python-s-design" id="id30">4   Python's Design</a><ul class="auto-toc">
  341. <li><a class="reference internal" href="#why-does-python-use-indentation-for-grouping-of-statements" id="id31">4.1   Why does Python use indentation for grouping of statements?</a></li>
  342. <li><a class="reference internal" href="#why-am-i-getting-strange-results-with-simple-arithmetic-operations" id="id32">4.2   Why am I getting strange results with simple arithmetic operations?</a></li>
  343. <li><a class="reference internal" href="#why-are-floating-point-calculations-so-inaccurate" id="id33">4.3   Why are floating point calculations so inaccurate?</a></li>
  344. <li><a class="reference internal" href="#why-are-python-strings-immutable" id="id34">4.4   Why are Python strings immutable?</a></li>
  345. <li><a class="reference internal" href="#why-must-self-be-used-explicitly-in-method-definitions-and-calls" id="id35">4.5   Why must 'self' be used explicitly in method definitions and calls?</a></li>
  346. <li><a class="reference internal" href="#why-can-t-i-use-an-assignment-in-an-expression" id="id36">4.6   Why can't I use an assignment in an expression?</a></li>
  347. <li><a class="reference internal" href="#why-does-python-use-methods-for-some-functionality-e-g-list-index-but-functions-for-other-e-g-len-list" id="id37">4.7   Why does Python use methods for some functionality (e.g. list.index()) but functions for other (e.g. len(list))?</a></li>
  348. <li><a class="reference internal" href="#why-is-join-a-string-method-instead-of-a-list-or-tuple-method" id="id38">4.8   Why is join() a string method instead of a list or tuple method?</a></li>
  349. <li><a class="reference internal" href="#how-fast-are-exceptions" id="id39">4.9   How fast are exceptions?</a></li>
  350. <li><a class="reference internal" href="#why-isn-t-there-a-switch-or-case-statement-in-python" id="id40">4.10   Why isn't there a switch or case statement in Python?</a></li>
  351. <li><a class="reference internal" href="#can-t-you-emulate-threads-in-the-interpreter-instead-of-relying-on-an-os-specific-thread-implementation" id="id41">4.11   Can't you emulate threads in the interpreter instead of relying on an OS-specific thread implementation?</a></li>
  352. <li><a class="reference internal" href="#why-can-t-lambda-forms-contain-statements" id="id42">4.12   Why can't lambda forms contain statements?</a></li>
  353. <li><a class="reference internal" href="#can-python-be-compiled-to-machine-code-c-or-some-other-language" id="id43">4.13   Can Python be compiled to machine code, C or some other language?</a></li>
  354. <li><a class="reference internal" href="#how-does-python-manage-memory" id="id44">4.14   How does Python manage memory?</a></li>
  355. <li><a class="reference internal" href="#why-isn-t-all-memory-freed-when-python-exits" id="id45">4.15   Why isn't all memory freed when Python exits?</a></li>
  356. <li><a class="reference internal" href="#why-are-there-separate-tuple-and-list-data-types" id="id46">4.16   Why are there separate tuple and list data types?</a></li>
  357. <li><a class="reference internal" href="#how-are-lists-implemented" id="id47">4.17   How are lists implemented?</a></li>
  358. <li><a class="reference internal" href="#how-are-dictionaries-implemented" id="id48">4.18   How are dictionaries implemented?</a></li>
  359. <li><a class="reference internal" href="#why-must-dictionary-keys-be-immutable" id="id49">4.19   Why must dictionary keys be immutable?</a></li>
  360. <li><a class="reference internal" href="#why-doesn-t-list-sort-return-the-sorted-list" id="id50">4.20   Why doesn't list.sort() return the sorted list?</a></li>
  361. <li><a class="reference internal" href="#how-do-you-specify-and-enforce-an-interface-spec-in-python" id="id51">4.21   How do you specify and enforce an interface spec in Python?</a></li>
  362. <li><a class="reference internal" href="#why-are-default-values-shared-between-objects" id="id52">4.22   Why are default values shared between objects?</a></li>
  363. <li><a class="reference internal" href="#why-is-there-no-goto" id="id53">4.23   Why is there no goto?</a></li>
  364. <li><a class="reference internal" href="#why-do-i-get-a-syntaxerror-for-a-continue-inside-a-try" id="id54">4.24   Why do I get a SyntaxError for a 'continue' inside a 'try'?</a></li>
  365. <li><a class="reference internal" href="#why-can-t-raw-strings-r-strings-end-with-a-backslash" id="id55">4.25   Why can't raw strings (r-strings) end with a backslash?</a></li>
  366. <li><a class="reference internal" href="#why-doesn-t-python-have-a-with-statement-like-some-other-languages" id="id56">4.26   Why doesn't Python have a "with" statement like some other languages?</a></li>
  367. <li><a class="reference internal" href="#why-are-colons-required-for-the-if-while-def-class-statements" id="id57">4.27   Why are colons required for the if/while/def/class statements?</a></li>
  368. </ul>
  369. </li>
  370. </ul>
  371. </div>
  372. <div class="section" id="general-information">
  373. <h1><a class="toc-backref" href="#id1">1   General Information</a></h1>
  374. <div class="section" id="what-is-python">
  375. <h2><a class="toc-backref" href="#id2">1.1   What is Python?</a></h2>
  376. <p>Python is an interpreted, interactive, object-oriented programming
  377. language.  It incorporates modules, exceptions, dynamic typing, very
  378. high level dynamic data types, and classes.  Python combines
  379. remarkable power with very clear syntax.  It has interfaces to many
  380. system calls and libraries, as well as to various window systems, and
  381. is extensible in C or C++.  It is also usable as an extension language
  382. for applications that need a programmable interface.  Finally, Python
  383. is portable: it runs on many Unix variants, on the Mac, and on PCs
  384. under MS-DOS, Windows, Windows NT, and OS/2.</p>
  385. <p>To find out more, start
  386. with the <a class="reference external" href="http://www.python.org/moin/BeginnersGuide">Beginner's Guide to Python</a>.</p>
  387. </div>
  388. <div class="section" id="why-was-python-created-in-the-first-place">
  389. <h2><a class="toc-backref" href="#id3">1.2   Why was Python created in the first place?</a></h2>
  390. <p>Here's a <em>very</em> brief summary of what started it all, written
  391. by Guido van Rossum:</p>
  392. <blockquote>
  393. <p>I had extensive experience with implementing an interpreted language
  394. in the ABC group at CWI, and from working with this group I had
  395. learned a lot about language design.  This is the origin of many
  396. Python features, including the use of indentation for statement
  397. grouping and the inclusion of very-high-level data types (although the
  398. details are all different in Python).</p>
  399. <p>I had a number of gripes about the ABC language, but also liked many
  400. of its features.  It was impossible to extend the ABC language (or its
  401. implementation) to remedy my complaints -- in fact its lack of
  402. extensibility was one of its biggest problems.  I had some experience
  403. with using Modula-2+ and talked with the designers of Modula-3 and
  404. read the Modula-3 report.  Modula-3 is the origin of the syntax and
  405. semantics used for exceptions, and some other Python features.</p>
  406. <p>I was working in the Amoeba distributed operating system group at
  407. CWI.  We needed a better way to do system administration than by
  408. writing either C programs or Bourne shell scripts, since Amoeba had
  409. its own system call interface which wasn't easily accessible from the
  410. Bourne shell.  My experience with error handling in Amoeba made me
  411. acutely aware of the importance of exceptions as a programming
  412. language feature.</p>
  413. <p>It occurred to me that a scripting language with a syntax like ABC
  414. but with access to the Amoeba system calls would fill the need.  I
  415. realized that it would be foolish to write an Amoeba-specific
  416. language, so I decided that I needed a language that was generally
  417. extensible.</p>
  418. <p>During the 1989 Christmas holidays, I had a lot of time on my hand,
  419. so I decided to give it a try.  During the next year, while still
  420. mostly working on it in my own time, Python was used in the Amoeba
  421. project with increasing success, and the feedback from colleagues made
  422. me add many early improvements.</p>
  423. <p>In February 1991, after just over a year of development, I decided
  424. to post to USENET.  The rest is in the Misc/HISTORY file.</p>
  425. </blockquote>
  426. </div>
  427. <div class="section" id="what-is-python-good-for">
  428. <h2><a class="toc-backref" href="#id4">1.3   What is Python good for?</a></h2>
  429. <p>Python is a high-level general-purpose programming language
  430. that can be applied to many different classes of problems.</p>
  431. <p>The language comes with a large standard library that covers areas
  432. such as string processing (regular expressions, Unicode, calculating
  433. differences between files), Internet protocols (HTTP, FTP, SMTP,
  434. XML-RPC, POP, IMAP, CGI programming), software engineering (unit testing,
  435. logging, profiling, parsing Python code), and operating system
  436. interfaces (system calls, filesystems, TCP/IP sockets).  Look at the
  437. table of contents for <a class="reference external" href="http://docs.python.org/lib/">the Library Reference</a> to get an idea of what's available.
  438. A wide variety of third-party extensions are also available.
  439. Consult <a class="reference external" href="http://cheeseshop.python.org/pypi">the Python Package Index</a> to find
  440. packages of interest to you.</p>
  441. </div>
  442. <div class="section" id="how-does-the-python-version-numbering-scheme-work">
  443. <h2><a class="toc-backref" href="#id5">1.4   How does the Python version numbering scheme work?</a></h2>
  444. <p>Python versions are numbered A.B.C or A.B.  A is the major version
  445. number -- it is only incremented for really major changes in
  446. the language.  B is the minor version number, incremented for less
  447. earth-shattering changes.  C is the micro-level -- it is incremented
  448. for each bugfix release.  See <a class="reference external" href="../../peps/pep-0006.html">PEP 6</a>
  449. for more information about bugfix releases.</p>
  450. <p>Not all releases are bugfix releases.  In the run-up to a new major
  451. release, a series of development releases are made, denoted as alpha,
  452. beta, or release candidate.  Alphas are early releases in which
  453. interfaces aren't yet finalized; it's not unexpected to see an
  454. interface change between two alpha releases.  Betas are more stable,
  455. preserving existing interfaces but possibly adding new modules, and
  456. release candidates are frozen, making no changes except as needed to
  457. fix critical bugs.</p>
  458. <p>Alpha, beta and release candidate versions have an additional
  459. suffix.  The suffix for an alpha version is "aN" for some small
  460. number N, the suffix for a beta version is "bN" for some small number
  461. N, and the suffix for a release candidate version is "cN" for some
  462. small number N.  In other words, all versions labeled 2.0aN precede
  463. the versions labeled 2.0bN, which precede versions labeled 2.0cN, and
  464. <em>those</em> precede 2.0.</p>
  465. <p>You may also find version numbers with a "+" suffix, e.g. "2.2+".
  466. These are unreleased versions, built directly from the subversion trunk.
  467. In practice, after a final minor release is made, the subversion trunk is
  468. incremented to the next minor version, which becomes the "a0" version,
  469. e.g. "2.4a0".</p>
  470. <p>See also the documentation for <tt class="docutils literal"><span class="pre">sys.version</span></tt>, <tt class="docutils literal"><span class="pre">sys.hexversion</span></tt>, and
  471. <tt class="docutils literal"><span class="pre">sys.version_info</span></tt>.</p>
  472. </div>
  473. <div class="section" id="are-there-copyright-restrictions-on-the-use-of-python">
  474. <h2><a class="toc-backref" href="#id6">1.5   Are there copyright restrictions on the use of Python?</a></h2>
  475. <p>Not really.  You can do anything you want with the source, as long as
  476. you leave the copyrights in and display those copyrights in any
  477. documentation about Python that you produce.  If you honor the
  478. copyright rules, it's OK to use Python for commercial use, to sell
  479. copies of Python in source or binary form (modified or unmodified), or
  480. to sell products that incorporate Python in some form.  We would still
  481. like to know about all commercial use of Python, of course.</p>
  482. <p>See <a class="reference external" href="../../psf/license.html">the PSF license page</a>
  483. to find further explanations and a link to the full text of the
  484. license.</p>
  485. </div>
  486. <div class="section" id="how-do-i-obtain-a-copy-of-the-python-source">
  487. <h2><a class="toc-backref" href="#id7">1.6   How do I obtain a copy of the Python source?</a></h2>
  488. <p>The latest Python source distribution is always available from
  489. python.org, at <a class="reference external" href="http://www.python.org/download/">http://www.python.org/download/</a>.  The latest
  490. development sources can be obtained via anonymous subversion from
  491. SourceForge, at <a class="reference external" href="http://svn.python.org/projects/python/trunk">http://svn.python.org/projects/python/trunk</a>.</p>
  492. <p>The source distribution is a gzipped tar file containing the complete
  493. C source, LaTeX documentation, Python library modules, example
  494. programs, and several useful pieces of freely distributable software.
  495. This will compile and run out of the box on most UNIX platforms.</p>
  496. <p>Older versions of Python are also available from python.org.</p>
  497. </div>
  498. <div class="section" id="how-do-i-get-documentation-on-python">
  499. <h2><a class="toc-backref" href="#id8">1.7   How do I get documentation on Python?</a></h2>
  500. <p>All documentation is available on-line, starting at
  501. <a class="reference external" href="http://www.python.org/doc/">http://www.python.org/doc/</a>.</p>
  502. <p>The standard documentation for the current stable version of Python is
  503. also available at <a class="reference external" href="http://docs.python.org/">http://docs.python.org/</a>.</p>
  504. <p>The LaTeX source for the documentation is part of the source
  505. distribution.  If you don't have LaTeX, the latest Python
  506. documentation set is available by anonymous FTP in various formats
  507. such as PostScript and HTML.  Visit the above URL for links to the
  508. current versions.</p>
  509. </div>
  510. <div class="section" id="i-ve-never-programmed-before-is-there-a-python-tutorial">
  511. <h2><a class="toc-backref" href="#id9">1.8   I've never programmed before. Is there a Python tutorial?</a></h2>
  512. <p>There are numerous tutorials and books available.  Consult <a class="reference external" href="http://www.python.org/moin/BeginnersGuide">the
  513. Beginner's Guide</a> to find
  514. information for beginning Python programmers, including lists of
  515. tutorials.</p>
  516. </div>
  517. <div class="section" id="are-there-other-ftp-sites-that-mirror-the-python-distribution">
  518. <h2><a class="toc-backref" href="#id10">1.9   Are there other FTP sites that mirror the Python distribution?</a></h2>
  519. <p>Consult the list of python.org mirrors at <a class="reference external" href="http://www.python.org/Mirrors.html">http://www.python.org/Mirrors.html</a>.</p>
  520. </div>
  521. <div class="section" id="is-there-a-newsgroup-or-mailing-list-devoted-to-python">
  522. <h2><a class="toc-backref" href="#id11">1.10   Is there a newsgroup or mailing list devoted to Python?</a></h2>
  523. <p>There is a newsgroup, comp.lang.python, and a mailing list,
  524. <a class="reference external" href="http://mail.python.org/mailman/listinfo/python-list">python-list</a>.
  525. The newsgroup and mailing list are gatewayed into each other -- if you
  526. can read news it's unnecessary to subscribe to the mailing list.
  527. comp.lang.python is high-traffic, receiving hundreds of postings every day,
  528. and Usenet readers are often more able to cope with this volume.</p>
  529. <p>Announcements of new software releases and events can be found in
  530. comp.lang.python.announce, a low-traffic moderated list that receives
  531. about five postings per day.
  532. It's available as
  533. <a class="reference external" href="http://mail.python.org/mailman/listinfo/python-announce-list">the python-announce mailing list</a>.</p>
  534. <p>More info about other mailing lists and newsgroups
  535. can be found at <a class="reference external" href="http://www.python.org/community/lists.html">http://www.python.org/community/lists.html</a>.</p>
  536. </div>
  537. <div class="section" id="how-do-i-get-a-beta-test-version-of-python">
  538. <h2><a class="toc-backref" href="#id12">1.11   How do I get a beta test version of Python?</a></h2>
  539. <p>All releases, including alphas, betas and release candidates, are
  540. announced on the comp.lang.python and comp.lang.python.announce
  541. newsgroups.  All announcements also appear on the Python
  542. home page, at <a class="reference external" href="http://www.python.org/">http://www.python.org/</a>; an RSS feed of news is available.</p>
  543. <p>You can also access the development version of Python through subversion.
  544. See <a class="reference external" href="http://www.python.org/dev/devfaq.html#subversion-svn">http://www.python.org/dev/devfaq.html#subversion-svn</a> for details.</p>
  545. </div>
  546. <div class="section" id="how-do-i-submit-bug-reports-and-patches-for-python">
  547. <h2><a class="toc-backref" href="#id13">1.12   How do I submit bug reports and patches for Python?</a></h2>
  548. <p>To report a bug or submit a patch, please use the relevant service
  549. from the Python project at SourceForge.</p>
  550. <p>Bugs: <a class="reference external" href="http://sourceforge.net/tracker/?group_id=5470&atid=105470">http://sourceforge.net/tracker/?group_id=5470&atid=105470</a></p>
  551. <p>Patches: <a class="reference external" href="http://sourceforge.net/tracker/?group_id=5470&atid=305470">http://sourceforge.net/tracker/?group_id=5470&atid=305470</a></p>
  552. <p>You must have a SourceForge account to report bugs; this makes it
  553. possible for us to contact you if we have follow-up questions.  It
  554. will also enable SourceForge to send you updates as we act on your
  555. bug.</p>
  556. <p>For more information on how Python is developed, consult
  557. <a class="reference external" href="../../dev/">the Python Developer's Guide</a>.</p>
  558. </div>
  559. <div class="section" id="are-there-any-published-articles-about-python-that-i-can-reference">
  560. <h2><a class="toc-backref" href="#id14">1.13   Are there any published articles about Python that I can reference?</a></h2>
  561. <p>It's probably best to reference your favorite book about Python.</p>
  562. <p>The very first article about Python is this very old article
  563. that's now quite outdated.</p>
  564. <blockquote>
  565. Guido van Rossum and Jelke de Boer, "Interactively Testing Remote
  566. Servers Using the Python Programming Language", CWI Quarterly, Volume
  567. 4, Issue 4 (December 1991), Amsterdam, pp 283-303.</blockquote>
  568. </div>
  569. <div class="section" id="are-there-any-books-on-python">
  570. <h2><a class="toc-backref" href="#id15">1.14   Are there any books on Python?</a></h2>
  571. <p>Yes, there are many, and more are being published.  See
  572. the python.org Wiki at <a class="reference external" href="http://www.python.org/moin/PythonBooks">http://www.python.org/moin/PythonBooks</a> for a list.</p>
  573. <p>You can also search online bookstores for "Python"
  574. and filter out the Monty Python references; or
  575. perhaps search for "Python" and "language".</p>
  576. </div>
  577. <div class="section" id="where-in-the-world-is-www-python-org-located">
  578. <h2><a class="toc-backref" href="#id16">1.15   Where in the world is www.python.org located?</a></h2>
  579. <p>It's currently in Amsterdam, graciously hosted by <a class="reference external" href="http://www.xs4all.nl">XS4ALL</a>.  Thanks to Thomas Wouters for his work in
  580. arranging python.org's hosting.</p>
  581. </div>
  582. <div class="section" id="why-is-it-called-python">
  583. <h2><a class="toc-backref" href="#id17">1.16   Why is it called Python?</a></h2>
  584. <p>At the same time he began implementing Python, Guido van Rossum was
  585. also reading the published scripts from "Monty Python's Flying Circus"
  586. (a BBC comedy series from the seventies, in the unlikely case you
  587. didn't know).  It occurred to him that he needed a name that was
  588. short, unique, and slightly mysterious, so he decided to call the
  589. language Python.</p>
  590. </div>
  591. <div class="section" id="do-i-have-to-like-monty-python-s-flying-circus">
  592. <h2><a class="toc-backref" href="#id18">1.17   Do I have to like "Monty Python's Flying Circus"?</a></h2>
  593. <p>No, but it helps.  :)</p>
  594. </div>
  595. </div>
  596. <div class="section" id="python-in-the-real-world">
  597. <h1><a class="toc-backref" href="#id19">2   Python in the real world</a></h1>
  598. <div class="section" id="how-stable-is-python">
  599. <h2><a class="toc-backref" href="#id20">2.1   How stable is Python?</a></h2>
  600. <p>Very stable.  New, stable releases have been coming out roughly every
  601. 6 to 18 months since 1991, and this seems likely to continue.
  602. Currently there are usually around 18 months between major releases.</p>
  603. <p>With the introduction of retrospective "bugfix" releases the stability
  604. of existing releases is being improved.  Bugfix releases, indicated by
  605. a third component of the version number (e.g. 2.1.3, 2.2.2), are
  606. managed for stability; only fixes for known problems are included in a
  607. bugfix release, and it's guaranteed that interfaces will remain the
  608. same throughout a series of bugfix releases.</p>
  609. <p>The <a class="reference external" href="../../2.4.2/">2.4.2 release</a> is the most stable
  610. version at this point in time.</p>
  611. </div>
  612. <div class="section" id="how-many-people-are-using-python">
  613. <h2><a class="toc-backref" href="#id21">2.2   How many people are using Python?</a></h2>
  614. <p>Probably tens of thousands of users, though it's difficult to obtain
  615. an exact count.  Python is available for free download, so there are
  616. no sales figures, and it's available from many different sites and
  617. packaged with many Linux distributions, so download statistics don't
  618. tell the whole story either.  The comp.lang.python newsgroup is very
  619. active, but not all Python users post to the group or even read it.
  620. Overall there is no accurate estimate of the number of subscribers or
  621. Python users.</p>
  622. </div>
  623. <div class="section" id="have-any-significant-projects-been-done-in-python">
  624. <h2><a class="toc-backref" href="#id22">2.3   Have any significant projects been done in Python?</a></h2>
  625. <p>See <a class="reference external" href="http://www.pythonology.org/success">http://www.pythonology.org/success</a> for a list of projects that
  626. use Python.  Consulting the proceedings for <a class="reference external" href="../../workshops/">past Python conferences</a> will reveal contributions from
  627. many different companies and organizations.</p>
  628. <p>High-profile Python projects include <a class="reference external" href="http://www.list.org">the Mailman mailing list manager</a> and <a class="reference external" href="http://www.zope.org">the Zope application server</a>.  Several Linux distributions, most
  629. notably <a class="reference external" href="http://www.redhat.com">Red Hat</a>, have written part or all
  630. of their installer and system administration software in Python.  Companies
  631. that use Python internally include Google,
  632. Yahoo, and Industrial Light & Magic.</p>
  633. </div>
  634. <div class="section" id="what-new-developments-are-expected-for-python-in-the-future">
  635. <h2><a class="toc-backref" href="#id23">2.4   What new developments are expected for Python in the future?</a></h2>
  636. <p>See <a class="reference external" href="http://www.python.org/peps">http://www.python.org/peps</a> for the Python Enhancement Proposals
  637. (PEPs). PEPs are design documents describing a suggested new feature
  638. for Python, providing a concise technical specification and a
  639. rationale.
  640. <a class="reference external" href="../../peps/pep-0001.html">PEP 1</a>
  641. explains the PEP process and PEP format; read it
  642. first if you want to submit a PEP.</p>
  643. <p>New developments are discussed on <a class="reference external" href="http://mail.python.org/mailman/listinfo/python-dev/">the python-dev mailing list</a>.</p>
  644. </div>
  645. <div class="section" id="is-it-reasonable-to-propose-incompatible-changes-to-python">
  646. <h2><a class="toc-backref" href="#id24">2.5   Is it reasonable to propose incompatible changes to Python?</a></h2>
  647. <p>In general, no.  There are already millions of lines of Python code
  648. around the world, so any change in the language that invalidates more
  649. than a very small fraction of existing programs has to be frowned
  650. upon.  Even if you can provide a conversion program, there still is
  651. the problem of updating all documentation; many books have been
  652. written about Python, and we don't want to invalidate them all at a
  653. single stroke.</p>
  654. <p>Providing a gradual upgrade path is necessary if a feature has to be
  655. changed.  <a class="reference external" href="../../peps/pep-0005.html">PEP 5</a>
  656. describes the procedure followed for introducing backward-incompatible
  657. changes while minimizing disruption for users.</p>
  658. </div>
  659. <div class="section" id="what-is-the-python-software-foundation">
  660. <h2><a class="toc-backref" href="#id25">2.6   What is the Python Software Foundation?</a></h2>
  661. <p>The Python Software Foundation is an independent non-profit
  662. organization that holds the copyright on Python versions 2.1 and
  663. newer.  The PSF's mission is to advance open source technology related
  664. to the Python programming language and to publicize the use of
  665. Python.  The PSF's home page is at <a class="reference external" href="http://www.python.org/psf/">http://www.python.org/psf/</a>.</p>
  666. <p>Donations to the PSF are tax-exempt in the US.  If you use Python and
  667. find it helpful, please contribute via <a class="reference external" href="../../psf/donations.html">the PSF donation page</a>.</p>
  668. </div>
  669. <div class="section" id="is-python-y2k-year-2000-compliant">
  670. <h2><a class="toc-backref" href="#id26">2.7   Is Python Y2K (Year 2000) Compliant?</a></h2>
  671. <p>As of August, 2003 no major problems have been reported and Y2K
  672. compliance seems to be a non-issue.</p>
  673. <p>Python does very few date calculations and for those it does perform relies
  674. on the C library functions.  Python generally represents times either
  675. as seconds since 1970 or as a <tt class="docutils literal"><span class="pre">(year,</span> <span class="pre">month,</span> <span class="pre">day,</span> <span class="pre">...)</span></tt> tuple where the
  676. year is expressed with four digits, which makes Y2K bugs unlikely.  So
  677. as long as your C library is okay, Python should be okay.  Of course,
  678. it's possible that a particular application written in Python
  679. makes assumptions about 2-digit years.</p>
  680. <p>Because Python is available free of charge, there are no absolute
  681. guarantees.  If there <em>are</em> unforseen problems, liability is the
  682. user's problem rather than the developers', and there is nobody you can sue
  683. for damages.  The Python copyright notice contains the following
  684. disclaimer:</p>
  685. <blockquote>
  686. <p>4. PSF is making Python 2.3 available to Licensee on an "AS IS"
  687. basis.  PSF MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR
  688. IMPLIED.  BY WAY OF EXAMPLE, BUT NOT LIMITATION, PSF MAKES NO AND
  689. DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS
  690. FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF PYTHON 2.3 WILL NOT
  691. INFRINGE ANY THIRD PARTY RIGHTS.</p>
  692. <p>5. PSF SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON
  693. 2.3 FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS
  694. A RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON 2.3,
  695. OR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF.</p>
  696. </blockquote>
  697. <p>The good news is that <em>if</em> you encounter a problem, you have full
  698. source available to track it down and fix it.  This is one advantage of
  699. an open source programming environment.</p>
  700. </div>
  701. <div class="section" id="is-python-a-good-language-for-beginning-programmers">
  702. <h2><a class="toc-backref" href="#id27">2.8   Is Python a good language for beginning programmers?</a></h2>
  703. <p>Yes.  If you want to discuss Python's use in education, then you may
  704. be interested in joining <a class="reference external" href="../../sigs/edu-sig">the edu-sig mailing list</a>.</p>
  705. <p>It is still common to start students with a procedural (subset of a)
  706. statically typed language such as Pascal, C, or a subset of C++ or
  707. Java.  Students may be better served by learning Python as their first
  708. language.  Python has a very simple and consistent syntax and a large
  709. standard library and, most importantly, using Python in a beginning
  710. programming course permits students to concentrate on important
  711. programming skills such as problem decomposition and data type design.
  712. With Python, students can be quickly introduced to basic concepts such
  713. as loops and procedures.  They can even probably work with
  714. user-defined objects in their very first course.</p>
  715. <p>For a student who has never programmed before, using a statically
  716. typed language seems unnatural.  It presents additional complexity
  717. that the student must master and slows the pace of the course.  The
  718. students are trying to learn to think like a computer, decompose
  719. problems, design consistent interfaces, and encapsulate data.  While
  720. learning to use a statically typed language is important in the long
  721. term, it is not necessarily the best topic to address in the students'
  722. first programming course.</p>
  723. <p>Many other aspects of Python make it a good first language.
  724. Like Java, Python has a large standard library so that
  725. students can be assigned programming projects very early in the
  726. course that <em>do</em> something.  Assignments aren't restricted to the
  727. standard four-function calculator and check balancing programs.
  728. By using the standard library, students can gain the satisfaction
  729. of working on realistic applications as they learn the fundamentals
  730. of programming.  Using the standard library also teaches students
  731. about code reuse.  Third-party modules such as PyGame are also helpful in
  732. extending the students' reach.</p>
  733. <p>Python's interactive interpreter enables students to
  734. test language features while they're programming.  They can keep
  735. a window with the interpreter running while they enter their
  736. program's source in another window.  If they can't remember the
  737. methods for a list, they can do something like this:</p>
  738. <pre class="literal-block">
  739. >>> L = []
  740. >>> dir(L)
  741. ['append', 'count', 'extend', 'index', 'insert', 'pop', 'remove',
  742. 'reverse', 'sort']
  743. >>> help(L.append)
  744. Help on built-in function append:
  745.  
  746. append(...)
  747.     L.append(object) -- append object to end
  748. >>> L.append(1)
  749. >>> L
  750. [1]
  751. </pre>
  752. <p>With the interpreter, documentation is never far from the
  753. student as he's programming.</p>
  754. <p>There are also good IDEs for Python.  IDLE is a cross-platform IDE for
  755. Python that is written in Python using Tkinter.  PythonWin is a
  756. Windows-specific IDE.  Emacs users will be happy to know that there is
  757. a very good Python mode for Emacs.  All of these programming
  758. environments provide syntax highlighting, auto-indenting, and access
  759. to the interactive interpreter while coding.  Consult
  760. <a class="reference external" href="http://www.python.org/editors/">http://www.python.org/editors/</a> for a full list of Python editing
  761. environments.</p>
  762. </div>
  763. </div>
  764. <div class="section" id="upgrading-python">
  765. <h1><a class="toc-backref" href="#id28">3   Upgrading Python</a></h1>
  766. <div class="section" id="what-is-this-bsddb185-module-my-application-keeps-complaining-about">
  767. <h2><a class="toc-backref" href="#id29">3.1   What is this bsddb185 module my application keeps complaining about?</a></h2>
  768. <p>Starting with Python2.3, the distribution includes the <cite>PyBSDDB package
  769. <http://pybsddb.sf.net/></cite> as a replacement for the old bsddb module.  It
  770. includes functions which provide backward compatibility at the API level,
  771. but requires a newer version of the underlying <a class="reference external" href="http://www.sleepycat.com">Berkeley DB</a> library.  Files created with the older bsddb
  772. module can't be opened directly using the new module.</p>
  773. <p>Using your old version of Python and a pair of scripts which are part of
  774. Python 2.3 (db2pickle.py and pickle2db.py, in the Tools/scripts directory)
  775. you can convert your old database files to the new format.  Using your old
  776. Python version, run the db2pickle.py script to convert it to a pickle,
  777. e.g.:</p>
  778. <pre class="literal-block">
  779. python2.2 <pathto>/db2pickley.py database.db database.pck
  780. </pre>
  781. <p>Rename your database file:</p>
  782. <pre class="literal-block">
  783. mv database.db olddatabase.db
  784. </pre>
  785. <p>Now convert the pickle file to a new format database:</p>
  786. <pre class="literal-block">
  787. python2.3 <pathto>/pickle2db.py database.db database.pck
  788. </pre>
  789. <p>The precise commands you use will vary depending on the particulars of your
  790. installation.  For full details about operation of these two scripts check
  791. the doc string at the start of each one.</p>
  792. </div>
  793. </div>
  794. <div class="section" id="python-s-design">
  795. <h1><a class="toc-backref" href="#id30">4   Python's Design</a></h1>
  796. <div class="section" id="why-does-python-use-indentation-for-grouping-of-statements">
  797. <h2><a class="toc-backref" href="#id31">4.1   Why does Python use indentation for grouping of statements?</a></h2>
  798. <p>Guido van Rossum believes that using indentation for grouping is extremely elegant
  799. and contributes a lot to the clarity of the average Python program.  Most
  800. people learn to love this feature after awhile.</p>
  801. <p>Since there are no begin/end brackets there cannot be a disagreement between
  802. grouping perceived by the parser and the human reader.  Occasionally C
  803. programmers will encounter a fragment of code like this:</p>
  804. <pre class="literal-block">
  805. if (x <= y)
  806.         x++;
  807.         y--;
  808. z++;
  809. </pre>
  810. <p>Only the <tt class="docutils literal"><span class="pre">x++</span></tt> statement is executed if the condition is true, but
  811. the indentation leads you to believe otherwise.
  812. Even experienced C programmers will sometimes
  813. stare a long time at it wondering why y is being decremented even for
  814. <tt class="docutils literal"><span class="pre">x</span> <span class="pre">></span> <span class="pre">y</span></tt>.</p>
  815. <p>Because there are no begin/end brackets, Python is much less prone to
  816. coding-style conflicts.  In C there are many different ways to place the
  817. braces.  If you're used to reading
  818. and writing code that uses one style, you will feel at least slightly
  819. uneasy when reading (or being required to write) another style.</p>
  820. <p>Many coding styles place begin/end brackets on a line by themself.  This
  821. makes programs considerably longer and wastes valuable screen space, making
  822. it harder to get a good overview of a program.  Ideally, a function should
  823. fit on onescreen (say, 20-30 lines).  20 lines of Python can do
  824. a lot more work than 20 lines of C.  This is not solely due to the lack of
  825. begin/end brackets -- the lack of declarations and the high-level data types
  826. are also responsible -- but the indentation-based syntax certainly helps.</p>
  827. </div>
  828. <div class="section" id="why-am-i-getting-strange-results-with-simple-arithmetic-operations">
  829. <h2><a class="toc-backref" href="#id32">4.2   Why am I getting strange results with simple arithmetic operations?</a></h2>
  830. <p>See the next question.</p>
  831. </div>
  832. <div class="section" id="why-are-floating-point-calculations-so-inaccurate">
  833. <h2><a class="toc-backref" href="#id33">4.3   Why are floating point calculations so inaccurate?</a></h2>
  834. <p>People are often very surprised by results like this:</p>
  835. <pre class="literal-block">
  836. >>> 1.2-1.0
  837. 0.199999999999999996
  838. </pre>
  839. <p>and think it is a bug in Python. It's not. It's a problem caused by
  840. the internal representation of floating point numbers, which uses a
  841. fixed number of binary digits to represent a decimal number.  Some
  842. decimal numbers can't be represented exactly in binary, resulting in
  843. small roundoff errors.</p>
  844. <p>In decimal math, there are many numbers that can't be represented with a
  845. fixed number of decimal digits, e.g.  1/3 = 0.3333333333.......</p>
  846. <p>In base 2, 1/2 = 0.1, 1/4 = 0.01, 1/8 = 0.001, etc.
  847. .2 equals 2/10 equals 1/5, resulting in the binary fractional number
  848. 0.001100110011001...</p>
  849. <p>Floating point numbers only have 32 or 64 bits of precision, so the digits are cut off at some point,
  850. and the resulting number is 0.199999999999999996 in decimal, not 0.2.</p>
  851. <p>A floating point's <tt class="docutils literal"><span class="pre">repr()</span></tt> function prints as many digits are
  852. necessary to make <tt class="docutils literal"><span class="pre">eval(repr(f))</span> <span class="pre">==</span> <span class="pre">f</span></tt> true for any float f.  The
  853. <tt class="docutils literal"><span class="pre">str()</span></tt> function prints fewer digits and this often results in the
  854. more sensible number that was probably intended:</p>
  855. <pre class="literal-block">
  856. >>> 0.2
  857. 0.20000000000000001
  858. >>> print 0.2
  859. 0.2
  860. </pre>
  861. <p>Again, this has nothing to do with Python, but with the way the underlying C
  862. platform handles floating point numbers, and ultimately with the inaccuracy
  863. you'll always have when writing down numbers as a string of a fixed number
  864. of digits.</p>
  865. <p>One of the consequences of this is that it is dangerous to compare the
  866. result of some computation to a float with == !  Tiny inaccuracies may mean
  867. that == fails.
  868. Instead, you have to check that the difference between the
  869. two numbers is less than a certain threshold:</p>
  870. <pre class="literal-block">
  871. epsilon = 0.0000000000001 # Tiny allowed error
  872. expected_result = 0.4
  873.  
  874. if expected_result-epsilon <= computation() <= expected_result+epsilon:
  875.    ...
  876. </pre>
  877. <p>Please see the chapter on
  878. <a class="reference external" href="http://docs.python.org/tut/node16.html">floating point arithmetic</a>
  879. in the Python tutorial for more information.</p>
  880. </div>
  881. <div class="section" id="why-are-python-strings-immutable">
  882. <h2><a class="toc-backref" href="#id34">4.4   Why are Python strings immutable?</a></h2>
  883. <p>There are several advantages.</p>
  884. <p>One is performance: knowing that a string is
  885. immutable makes it easy to lay it out at construction time -- fixed and
  886. unchanging storage requirements.  This is also one of the reasons for the
  887. distinction between tuples and lists.</p>
  888. <p>The other is that strings in Python are considered as "elemental" as
  889. numbers.  No amount of activity will change the value 8 to anything
  890. else, and in Python, no amount of activity will change the string
  891. "eight" to anything else.</p>
  892. </div>
  893. <div class="section" id="why-must-self-be-used-explicitly-in-method-definitions-and-calls">
  894. <h2><a class="toc-backref" href="#id35">4.5   Why must 'self' be used explicitly in method definitions and calls?</a></h2>
  895. <p>The idea was borrowed from Modula-3.  It turns out to be very useful,
  896. for a variety of reasons.</p>
  897. <p>First, it's more obvious that you are using a method or instance
  898. attribute instead of a local variable.  Reading <tt class="docutils literal"><span class="pre">self.x</span></tt> or <tt class="docutils literal"><span class="pre">self.meth()</span></tt>
  899. makes it absolutely clear that an instance variable or method is used even
  900. if you don't know the class definition by heart.  In C++, you can sort of
  901. tell by the lack of a local variable declaration (assuming globals are rare
  902. or easily recognizable) -- but in Python, there are no local variable
  903. declarations, so you'd have to look up the class definition to be sure.
  904. Some C++ and Java coding standards call for instance attributes to have an
  905. <tt class="docutils literal"><span class="pre">m_</span></tt> prefix, so this explicitness is still useful in those languages, too.</p>
  906. <p>Second, it means that no special syntax is necessary if you want to
  907. explicitly reference or call the method from a particular class.  In C++, if
  908. you want to use a method from a base class which is overridden in a derived
  909. class, you have to use the :: operator -- in Python you can write
  910. baseclass.methodname(self, <argument list>).  This is particularly useful
  911. for __init__() methods, and in general in cases where a derived class method
  912. wants to extend the base class method of the same name and thus has to call
  913. the base class method somehow.</p>
  914. <p>Finally, for instance variables it solves a syntactic problem with
  915. assignment: since local variables in Python are (by definition!) those
  916. variables to which a value assigned in a function body (and that aren't
  917. explicitly declared global), there has to be some way to tell the
  918. interpreter that an assignment was meant to assign to an instance variable
  919. instead of to a local variable, and it should preferably be syntactic (for
  920. efficiency reasons).  C++ does this through declarations, but Python doesn't
  921. have declarations and it would be a pity having to introduce them just for
  922. this purpose.  Using the explicit "self.var" solves this nicely.  Similarly,
  923. for using instance variables, having to write "self.var" means that
  924. references to unqualified names inside a method don't have to search the
  925. instance's directories.  To put it another way, local variables and
  926. instance variables live in two different namespaces, and you need to
  927. tell Python which namespace to use.</p>
  928. </div>
  929. <div class="section" id="why-can-t-i-use-an-assignment-in-an-expression">
  930. <h2><a class="toc-backref" href="#id36">4.6   Why can't I use an assignment in an expression?</a></h2>
  931. <p>Many people used to C or Perl complain that they want to
  932. use this C idiom:</p>
  933. <pre class="literal-block">
  934. while (line = readline(f)) {
  935.     ...do something with line...
  936. }
  937. </pre>
  938. <p>where in Python you're forced to write this:</p>
  939. <pre class="literal-block">
  940. while True:
  941.     line = f.readline()
  942.     if not line:
  943.         break
  944.     ...do something with line...
  945. </pre>
  946. <p>The reason for not allowing assignment in Python expressions
  947. is a common, hard-to-find bug in those other languages,
  948. caused by this construct:</p>
  949. <pre class="literal-block">
  950. if (x = 0) {
  951.     ...error handling...
  952. }
  953. else {
  954.     ...code that only works for nonzero x...
  955. }
  956. </pre>
  957. <p>The error is a simple typo: <tt class="docutils literal"><span class="pre">x</span> <span class="pre">=</span> <span class="pre">0</span></tt>, which assigns 0 to the variable <tt class="docutils literal"><span class="pre">x</span></tt>,
  958. was written while the comparison <tt class="docutils literal"><span class="pre">x</span> <span class="pre">==</span> <span class="pre">0</span></tt> is certainly what was intended.</p>
  959. <p>Many alternatives have been proposed.  Most are hacks that save some
  960. typing but use arbitrary or cryptic syntax or keywords,
  961. and fail the simple criterion for language change proposals:
  962. it should intuitively suggest the proper meaning to a human reader
  963. who has not yet been introduced to the construct.</p>
  964. <p>An interesting phenomenon is that most experienced Python programmers
  965. recognize the "while True" idiom and don't seem to be missing the
  966. assignment in expression construct much; it's only newcomers
  967. who express a strong desire to add this to the language.</p>
  968. <p>There's an alternative way of spelling this that seems
  969. attractive but is generally less robust than the "while True" solution:</p>
  970. <pre class="literal-block">
  971. line = f.readline()
  972. while line:
  973.     ...do something with line...
  974.     line = f.readline()
  975. </pre>
  976. <p>The problem with this is that if you change your mind about exactly
  977. how you get the next line (e.g. you want to change it into
  978. <tt class="docutils literal"><span class="pre">sys.stdin.readline()</span></tt>) you have to remember to change two places in
  979. your program -- the second occurrence is hidden at the bottom of the
  980. loop.</p>
  981. <p>The best approach is to use iterators, making it possible to loop
  982. through objects using the <tt class="docutils literal"><span class="pre">for</span></tt> statement.  For example, in the
  983. current version of Python file objects support the iterator protocol, so you
  984. can now write simply:</p>
  985. <pre class="literal-block">
  986. for line in f:
  987.     ... do something with line...
  988. </pre>
  989. </div>
  990. <div class="section" id="why-does-python-use-methods-for-some-functionality-e-g-list-index-but-functions-for-other-e-g-len-list">
  991. <h2><a class="toc-backref" href="#id37">4.7   Why does Python use methods for some functionality (e.g. list.index()) but functions for other (e.g. len(list))?</a></h2>
  992. <p>The major reason is history. Functions were used for those operations
  993. that were generic for a group of types and which were intended to work
  994. even for objects that didn't have methods at all (e.g. tuples).  It is
  995. also convenient to have a function that can readily be applied to an
  996. amorphous collection of objects when you use the functional features
  997. of Python (<tt class="docutils literal"><span class="pre">map()</span></tt>, <tt class="docutils literal"><span class="pre">apply()</span></tt> et al).</p>
  998. <p>In fact, implementing <tt class="docutils literal"><span class="pre">len()</span></tt>, <tt class="docutils literal"><span class="pre">max()</span></tt>, <tt class="docutils literal"><span class="pre">min()</span></tt> as a built-in
  999. function is actually less code than implementing them as methods for
  1000. each type.  One can quibble about individual cases but it's a part of
  1001. Python, and it's too late to make such fundamental changes now. The
  1002. functions have to remain to avoid massive code breakage.</p>
  1003. <p>Note that for string operations Python has moved from external functions
  1004. (the <tt class="docutils literal"><span class="pre">string</span></tt> module) to methods.  However, <tt class="docutils literal"><span class="pre">len()</span></tt> is still a function.</p>
  1005. </div>
  1006. <div class="section" id="why-is-join-a-string-method-instead-of-a-list-or-tuple-method">
  1007. <h2><a class="toc-backref" href="#id38">4.8   Why is join() a string method instead of a list or tuple method?</a></h2>
  1008. <p>Strings became much more like other standard types starting in Python
  1009. 1.6, when methods were added which give the same functionality that
  1010. has always been available using the functions of the string module.
  1011. Most of these new methods have been widely accepted, but the one which
  1012. appears to make some programmers feel uncomfortable is:</p>
  1013. <pre class="literal-block">
  1014. ", ".join(['1', '2', '4', '8', '16'])
  1015. </pre>
  1016. <p>which gives the result:</p>
  1017. <pre class="literal-block">
  1018. "1, 2, 4, 8, 16"
  1019. </pre>
  1020. <p>There are two usual arguments against this usage.</p>
  1021. <p>The first runs along the lines of: "It looks really ugly using a method of a
  1022. string literal (string constant)", to which the answer is that it might, but
  1023. a string literal is just a fixed value. If the methods are to be allowed on
  1024. names bound to strings there is no logical reason to make them unavailable
  1025. on literals.</p>
  1026. <p>The second objection is typically cast as: "I am really telling a sequence
  1027. to join its members together with a string constant". Sadly, you aren't. For
  1028. some reason there seems to be much less difficulty with having split() as a
  1029. string method, since in that case it is easy to see that</p>
  1030. <pre class="literal-block">
  1031. "1, 2, 4, 8, 16".split(", ")
  1032. </pre>
  1033. <p>is an instruction to a string literal to return the substrings delimited by
  1034. the given separator (or, by default, arbitrary runs of white space). In this
  1035. case a Unicode string returns a list of Unicode strings, an ASCII string
  1036. returns a list of ASCII strings, and everyone is happy.</p>
  1037. <p>join() is a string method because in using it you are telling the separator
  1038. string to iterate over an arbitrary sequence, forming string representations
  1039. of each of the elements, and inserting itself between the elements'
  1040. representations.  This method can be used with any argument which obeys the
  1041. rules for sequence objects, inluding any new classes you might define
  1042. yourself.</p>
  1043. <p>Because this is a string method it can work for Unicode strings as well as
  1044. plain ASCII strings. If join() were a method of the sequence types then the
  1045. sequence types would have to decide which type of string to return depending
  1046. on the type of the separator.</p>
  1047. <p>If none of these arguments persuade you, then for the moment you can
  1048. continue to use the join() function from the string module, which allows you
  1049. to write</p>
  1050. <pre class="literal-block">
  1051. string.join(['1', '2', '4', '8', '16'], ", ")
  1052. </pre>
  1053. </div>
  1054. <div class="section" id="how-fast-are-exceptions">
  1055. <h2><a class="toc-backref" href="#id39">4.9   How fast are exceptions?</a></h2>
  1056. <p>A try/except block is extremely efficient.  Actually executing an exception
  1057. is expensive.  In versions of Python prior to 2.0 it was common to use this
  1058. idiom:</p>
  1059. <pre class="literal-block">
  1060. try:
  1061.     value = dict[key]
  1062. except KeyError:
  1063.     dict[key] = getvalue(key)
  1064.     value = dict[key]
  1065. </pre>
  1066. <p>This only made sense when you expected the dict to have the key almost all
  1067. the time.  If that wasn't the case, you coded it like this:</p>
  1068. <pre class="literal-block">
  1069. if dict.has_key(key):
  1070.     value = dict[key]
  1071. else:
  1072.     dict[key] = getvalue(key)
  1073.     value = dict[key]
  1074. </pre>
  1075. <p>(In Python 2.0 and higher, you can code this as
  1076. <tt class="docutils literal"><span class="pre">value</span> <span class="pre">=</span> <span class="pre">dict.setdefault(key,</span> <span class="pre">getvalue(key))</span></tt>.)</p>
  1077. </div>
  1078. <div class="section" id="why-isn-t-there-a-switch-or-case-statement-in-python">
  1079. <h2><a class="toc-backref" href="#id40">4.10   Why isn't there a switch or case statement in Python?</a></h2>
  1080. <p>You can do this easily enough with a sequence of <tt class="docutils literal"><span class="pre">if...</span> <span class="pre">elif...</span> <span class="pre">elif...</span> <span class="pre">else</span></tt>.
  1081. There have been some proposals for switch statement syntax, but there is no
  1082. consensus (yet) on whether and how to do range tests.  See <a class="reference external" href="../../peps/pep-0275.html">PEP 275</a> for complete details and
  1083. the current status.</p>
  1084. <p>For cases where you need to choose from a very large number of
  1085. possibilities, you can create a dictionary mapping case values to
  1086. functions to call.  For example:</p>
  1087. <pre class="literal-block">
  1088. def function_1 (...):
  1089.     ...
  1090.  
  1091. functions = {'a': function_1,
  1092.              'b': function_2,
  1093.              'c': self.method_1, ...}
  1094.  
  1095. func = functions[value]
  1096. func()
  1097. </pre>
  1098. <p>For calling methods on objects, you can simplify yet further by using
  1099. the <tt class="docutils literal"><span class="pre">getattr()</span></tt> built-in to retrieve methods with a particular name:</p>
  1100. <pre class="literal-block">
  1101. def visit_a (self, ...):
  1102.     ...
  1103. ...
  1104.  
  1105. def dispatch (self, value):
  1106.     method_name = 'visit_' + str(value)
  1107.     method = getattr(self, method_name)
  1108.     method()
  1109. </pre>
  1110. <p>It's suggested that you use a prefix for the method names, such as
  1111. <tt class="docutils literal"><span class="pre">visit_</span></tt> in this example.  Without such a prefix, if values are coming
  1112. from an untrusted source, an attacker would be able to call any method
  1113. on your object.</p>
  1114. </div>
  1115. <div class="section" id="can-t-you-emulate-threads-in-the-interpreter-instead-of-relying-on-an-os-specific-thread-implementation">
  1116. <h2><a class="toc-backref" href="#id41">4.11   Can't you emulate threads in the interpreter instead of relying on an OS-specific thread implementation?</a></h2>
  1117. <p>Answer 1: Unfortunately, the interpreter pushes at least one C stack frame
  1118. for each Python stack frame.  Also, extensions can call back into Python at
  1119. almost random moments.  Therefore, a complete threads implementation
  1120. requires thread support for C.</p>
  1121. <p>Answer 2: Fortunately, there is <a class="reference external" href="http://www.stackless.com">Stackless Python</a>, which has a completely redesigned interpreter
  1122. loop that avoids the C stack.  It's still experimental but looks very
  1123. promising.  Although it is binary compatible with standard Python, it's
  1124. still unclear whether Stackless will make it into the core -- maybe it's
  1125. just too revolutionary.</p>
  1126. </div>
  1127. <div class="section" id="why-can-t-lambda-forms-contain-statements">
  1128. <h2><a class="toc-backref" href="#id42">4.12   Why can't lambda forms contain statements?</a></h2>
  1129. <p>Python lambda forms cannot contain statements because Python's syntactic
  1130. framework can't handle statements nested inside expressions.  However, in
  1131. Python, this is not a serious problem.  Unlike lambda forms in other
  1132. languages, where they add functionality, Python lambdas are only a shorthand
  1133. notation if you're too lazy to define a function.</p>
  1134. <p>Functions are already first class objects in Python, and can be declared in
  1135. a local scope.  Therefore the only advantage of using a lambda form instead
  1136. of a locally-defined function is that you don't need to invent a name for
  1137. the function -- but that's just a local variable to which the function
  1138. object (which is exactly the same type of object that a lambda form yields)
  1139. is assigned!</p>
  1140. </div>
  1141. <div class="section" id="can-python-be-compiled-to-machine-code-c-or-some-other-language">
  1142. <h2><a class="toc-backref" href="#id43">4.13   Can Python be compiled to machine code, C or some other language?</a></h2>
  1143. <p>Not easily.  Python's high level data types, dynamic typing of objects and
  1144. run-time invocation of the interpreter (using <tt class="docutils literal"><span class="pre">eval()</span></tt> or <tt class="docutils literal"><span class="pre">exec</span></tt>) together mean
  1145. that a "compiled" Python program would probably consist mostly of calls into
  1146. the Python run-time system, even for seemingly simple operations like
  1147. <tt class="docutils literal"><span class="pre">x+1</span></tt>.</p>
  1148. <p>Several projects described in the Python newsgroup or at past <a class="reference external" href="../../workshops/">Python
  1149. conferences</a> have shown that this
  1150. approach is feasible, although the speedups reached so far are only
  1151. modest (e.g. 2x).  Jython uses the same strategy for compiling to Java
  1152. bytecode.  (Jim Hugunin has demonstrated that in combination with
  1153. whole-program analysis, speedups of 1000x are feasible for small demo
  1154. programs.  See the proceedings from the <a class="reference external" href="../../workshops/1997-10/proceedings/">1997 Python conference</a> for more
  1155. information.)</p>
  1156. <p>Internally, Python source code is always translated into a bytecode
  1157. representation, and this bytecode is then executed by the Python
  1158. virtual machine.  In order to avoid the overhead of repeatedly parsing
  1159. and translating modules that rarely change, this byte code is written
  1160. into a file whose name ends in ".pyc" whenever a module is parsed.
  1161. When the corresponding .py file is changed, it is parsed and
  1162. translated again and the .pyc file is rewritten.</p>
  1163. <p>There is no performance difference once the .pyc file has been loaded,
  1164. as the bytecode read from the .pyc file is exactly the same as the
  1165. bytecode created by direct translation.  The only difference is that
  1166. loading code from a .pyc file is faster than parsing and translating a
  1167. .py file, so the presence of precompiled .pyc files improves the
  1168. start-up time of Python scripts.  If desired, the Lib/compileall.py
  1169. module can be used to create valid .pyc files for a given set of
  1170. modules.</p>
  1171. <p>Note that the main script executed by Python, even if its filename
  1172. ends in .py, is not compiled to a .pyc file.  It is compiled to
  1173. bytecode, but the bytecode is not saved to a file.  Usually main
  1174. scripts are quite short, so this doesn't cost much speed.</p>
  1175. <p>There are also several programs which make it easier to intermingle
  1176. Python and C code in various ways to increase performance.  See, for
  1177. example, <a class="reference external" href="http://psyco.sourceforge.net/">Psyco</a>,
  1178. <a class="reference external" href="http://www.cosc.canterbury.ac.nz/~greg/python/Pyrex/">Pyrex</a>, <a class="reference external" href="http://pyinline.sourceforge.net/">PyInline</a>, <a class="reference external" href="http://sourceforge.net/projects/py2cmod/">Py2Cmod</a>, and <a class="reference external" href="http://www.scipy.org/site_content/weave">Weave</a>.</p>
  1179. </div>
  1180. <div class="section" id="how-does-python-manage-memory">
  1181. <h2><a class="toc-backref" href="#id44">4.14   How does Python manage memory?</a></h2>
  1182. <p>The details of Python memory management depend on the implementation.
  1183. The standard C implementation of Python uses reference counting to
  1184. detect inaccessible objects, and another mechanism to collect
  1185. reference cycles, periodically executing a cycle detection algorithm
  1186. which looks for inaccessible cycles and deletes the objects
  1187. involved. The <tt class="docutils literal"><span class="pre">gc</span></tt> module provides functions to perform a garbage
  1188. collection, obtain debugging statistics, and tune the collector's
  1189. parameters.</p>
  1190. <p>Jython relies on the Java runtime so the JVM's garbage collector is
  1191. used.  This difference can cause some subtle porting problems if your
  1192. Python code depends on the behavior of the reference counting
  1193. implementation.</p>
  1194. <p>Sometimes objects get stuck in tracebacks temporarily and hence are not
  1195. deallocated when you might expect.  Clear the tracebacks with:</p>
  1196. <pre class="literal-block">
  1197. import sys
  1198. sys.exc_clear()
  1199. sys.exc_traceback = sys.last_traceback = None
  1200. </pre>
  1201. <p>Tracebacks are used for reporting errors, implementing debuggers and related
  1202. things.  They contain a portion of the program state extracted during the
  1203. handling of an exception (usually the most recent exception).</p>
  1204. <p>In the absence of circularities and tracebacks, Python programs need
  1205. not explicitly manage memory.</p>
  1206. <p>Why doesn't Python use a more traditional garbage collection scheme?
  1207. For one thing, this is not a C standard feature and hence it's not
  1208. portable.  (Yes, we know about the Boehm GC library.  It has bits of
  1209. assembler code for <em>most</em> common platforms, not for all of them, and
  1210. although it is mostly transparent, it isn't completely transparent;
  1211. patches are required to get Python to work with it.)</p>
  1212. <p>Traditional GC also becomes a problem when Python is embedded into other
  1213. applications.  While in a standalone Python it's fine to replace the
  1214. standard malloc() and free() with versions provided by the GC library, an
  1215. application embedding Python may want to have its <em>own</em> substitute for
  1216. malloc() and free(), and may not want Python's.  Right now, Python works
  1217. with anything that implements malloc() and free() properly.</p>
  1218. <p>In Jython, the following code (which is fine in CPython) will probably run
  1219. out of file descriptors long before it runs out of memory:</p>
  1220. <pre class="literal-block">
  1221. for file in <very long list of files>:
  1222.     f = open(file)
  1223.     c = f.read(1)
  1224. </pre>
  1225. <p>Using the current reference counting and destructor scheme, each new
  1226. assignment to f closes the previous file.  Using GC, this is not
  1227. guaranteed.  If you want to write code that will work with any Python
  1228. implementation, you should explicitly close the file; this will work
  1229. regardless of GC:</p>
  1230. <pre class="literal-block">
  1231. for file in <very long list of files>:
  1232.     f = open(file)
  1233.     c = f.read(1)
  1234.     f.close()
  1235. </pre>
  1236. </div>
  1237. <div class="section" id="why-isn-t-all-memory-freed-when-python-exits">
  1238. <h2><a class="toc-backref" href="#id45">4.15   Why isn't all memory freed when Python exits?</a></h2>
  1239. <p>Objects referenced from the global namespaces of
  1240. Python modules are not always deallocated when Python exits.
  1241. This may happen if there are circular references.  There are also
  1242. certain bits of memory that are allocated by the C library that are
  1243. impossible to free (e.g. a tool like Purify will complain about
  1244. these).  Python is, however, aggressive about cleaning up memory on
  1245. exit and does try to destroy every single object.</p>
  1246. <p>If you want to force Python to delete certain things on deallocation
  1247. use the <tt class="docutils literal"><span class="pre">sys.exitfunc()</span></tt> hook to run a function that will force
  1248. those deletions.</p>
  1249. </div>
  1250. <div class="section" id="why-are-there-separate-tuple-and-list-data-types">
  1251. <h2><a class="toc-backref" href="#id46">4.16   Why are there separate tuple and list data types?</a></h2>
  1252. <p>Lists and tuples, while similar in many respects, are generally used
  1253. in fundamentally different ways.  Tuples can be thought of as being
  1254. similar to Pascal records or C structs; they're small collections of
  1255. related data which may be of different types which are operated on as
  1256. a group.  For example, a Cartesian coordinate is appropriately
  1257. represented as a tuple of two or three numbers.</p>
  1258. <p>Lists, on the other hand, are more like arrays in other languages.  They
  1259. tend to hold a varying number of objects all of which have the same type and
  1260. which are operated on one-by-one.  For example, <tt class="docutils literal"><span class="pre">os.listdir('.')</span></tt> returns
  1261. a list of strings representing the files in the current directory.
  1262. Functions which operate on this output would generally not break if you
  1263. added another file or two to the directory.</p>
  1264. <p>Tuples are immutable, meaning that once a tuple has been created, you
  1265. can't replace any of its elements with a new value.  Lists are
  1266. mutable, meaning that you can always change a list's elements.  Only
  1267. immutable elements can be used as dictionary keys, and hence only
  1268. tuples and not lists can be used as keys.</p>
  1269. </div>
  1270. <div class="section" id="how-are-lists-implemented">
  1271. <h2><a class="toc-backref" href="#id47">4.17   How are lists implemented?</a></h2>
  1272. <p>Python's lists are really variable-length arrays, not Lisp-style
  1273. linked lists.  The implementation uses a contiguous array of
  1274. references to other objects, and keeps a pointer to this array and the
  1275. array's length in a list head structure.</p>
  1276. <p>This makes indexing a list <tt class="docutils literal"><span class="pre">a[i]</span></tt> an operation whose cost is independent of
  1277. the size of the list or the value of the index.</p>
  1278. <p>When items are appended or inserted, the array of references is resized.
  1279. Some cleverness is applied to improve the performance of appending items
  1280. repeatedly; when the array must be grown, some extra space is allocated so
  1281. the next few times don't require an actual resize.</p>
  1282. </div>
  1283. <div class="section" id="how-are-dictionaries-implemented">
  1284. <h2><a class="toc-backref" href="#id48">4.18   How are dictionaries implemented?</a></h2>
  1285. <p>Python's dictionaries are implemented as resizable hash tables.
  1286. Compared to B-trees, this gives better performance for lookup
  1287. (the most common operation by far) under most circumstances,
  1288. and the implementation is simpler.</p>
  1289. <p>Dictionaries work by computing a hash code for each key stored in the
  1290. dictionary using the <tt class="docutils literal"><span class="pre">hash()</span></tt> built-in function.  The hash code
  1291. varies widely depending on the key; for example, "Python" hashes to
  1292. -539294296 while "python", a string that differs by a single bit,
  1293. hashes to 1142331976.  The hash code is then used to calculate a
  1294. location in an internal array where the value will be stored.
  1295. Assuming that you're storing keys that all have different hash values,
  1296. this means that dictionaries take constant time -- O(1), in computer
  1297. science notation -- to retrieve a key.  It also means that no sorted
  1298. order of the keys is maintained, and traversing the array as the
  1299. <tt class="docutils literal"><span class="pre">.keys()</span></tt> and <tt class="docutils literal"><span class="pre">.items()</span></tt> do will output the dictionary's content
  1300. in some arbitrary jumbled order.</p>
  1301. </div>
  1302. <div class="section" id="why-must-dictionary-keys-be-immutable">
  1303. <h2><a class="toc-backref" href="#id49">4.19   Why must dictionary keys be immutable?</a></h2>
  1304. <p>The hash table implementation of dictionaries uses a hash value
  1305. calculated from the key value to find the key.  If the key were a
  1306. mutable object, its value could change, and thus its hash could also
  1307. change.  But since whoever changes the key object can't tell that it
  1308. was being used as a dictionary key, it can't move the entry around in the
  1309. dictionary.  Then, when you try to look up the same object in the
  1310. dictionary it won't be found because its hash value is different.
  1311. If you tried to look up the old value it wouldn't be found either, because
  1312. the value of the object found in that hash bin would be different.</p>
  1313. <p>If you want a dictionary indexed with a list, simply convert the list
  1314. to a tuple first; the function <tt class="docutils literal"><span class="pre">tuple(L)</span></tt> creates a tuple with the
  1315. same entries as the list <tt class="docutils literal"><span class="pre">L</span></tt>.  Tuples are immutable and can
  1316. therefore be used as dictionary keys.</p>
  1317. <p>Some unacceptable solutions that have been proposed:</p>
  1318. <ul>
  1319. <li><p class="first">Hash lists by their address (object ID).  This doesn't work because
  1320. if you construct a new list with the same value it won't be found;
  1321. e.g.:</p>
  1322. <pre class="literal-block">
  1323. d = {[1,2]: '12'}
  1324. print d[[1,2]]
  1325. </pre>
  1326. <p>would raise a KeyError exception because the id of the <tt class="docutils literal"><span class="pre">[1,2]</span></tt> used in
  1327. the second line differs from that in the first line.  In other
  1328. words, dictionary keys should be compared using <tt class="docutils literal"><span class="pre">==</span></tt>, not using
  1329. 'is'.</p>
  1330. </li>
  1331. <li><p class="first">Make a copy when using a list as a key.  This doesn't work because
  1332. the list, being a mutable object, could contain a reference to
  1333. itself, and then the copying code would run into an infinite loop.</p>
  1334. </li>
  1335. <li><p class="first">Allow lists as keys but tell the user not to modify them.  This
  1336. would allow a class of hard-to-track bugs in programs when you forgot
  1337. or modified a list by accident. It also
  1338. invalidates an important invariant of
  1339. dictionaries: every value in <tt class="docutils literal"><span class="pre">d.keys()</span></tt> is usable as a key of the
  1340. dictionary.</p>
  1341. </li>
  1342. <li><p class="first">Mark lists as read-only once they are used as a dictionary key.  The
  1343. problem is that it's not just the top-level object that could change
  1344. its value; you could use a tuple containing a list as a key.
  1345. Entering anything as a key into a dictionary would require marking
  1346. all objects reachable from there as read-only -- and again,
  1347. self-referential objects could cause an infinite loop.</p>
  1348. </li>
  1349. </ul>
  1350. <p>There is a trick to get around this if you need to, but
  1351. use it at your own risk:  You
  1352. can wrap a mutable structure inside a class instance which
  1353. has both a __cmp__ and a __hash__ method.
  1354. You must then make sure that the hash value for all such wrapper objects
  1355. that reside in a dictionary (or other hash based structure), remain
  1356. fixed while the object is in the dictionary (or other structure).:</p>
  1357. <pre class="literal-block">
  1358. class ListWrapper:
  1359.      def __init__(self, the_list):
  1360.            self.the_list = the_list
  1361.      def __cmp__(self, other):
  1362.            return self.the_list == other.the_list
  1363.      def __hash__(self):
  1364.            l = self.the_list
  1365.            result = 98767 - len(l)*555
  1366.            for i in range(len(l)):
  1367.                 try:
  1368.                      result = result + (hash(l[i]) % 9999999) * 1001 + i
  1369.                 except:
  1370.                      result = (result % 7777777) + i * 333
  1371.            return result
  1372. </pre>
  1373. <p>Note that the hash computation is complicated by the
  1374. possibility that some members of the list may be unhashable
  1375. and also by the possibility of arithmetic overflow.</p>
  1376. <p>Furthermore it must always be the case that if
  1377. <tt class="docutils literal"><span class="pre">o1</span> <span class="pre">==</span> <span class="pre">o2</span></tt> (ie <tt class="docutils literal"><span class="pre">o1.__cmp__(o2)==0</span></tt>) then <tt class="docutils literal"><span class="pre">hash(o1)==hash(o2)</span></tt>
  1378. (ie, <tt class="docutils literal"><span class="pre">o1.__hash__()</span> <span class="pre">==</span> <span class="pre">o2.__hash__()</span></tt>), regardless of whether
  1379. the object is in a dictionary or not.
  1380. If you fail to meet these restrictions dictionaries and other
  1381. hash based structures will misbehave.</p>
  1382. <p>In the case of ListWrapper, whenever the wrapper
  1383. object is in a dictionary the wrapped list must not change
  1384. to avoid anomalies.  Don't do this unless you are prepared
  1385. to think hard about the requirements and the consequences
  1386. of not meeting them correctly.  Consider yourself warned.</p>
  1387. </div>
  1388. <div class="section" id="why-doesn-t-list-sort-return-the-sorted-list">
  1389. <h2><a class="toc-backref" href="#id50">4.20   Why doesn't list.sort() return the sorted list?</a></h2>
  1390. <p>In situations where performance matters, making a copy
  1391. of the list just to sort it would be wasteful. Therefore,
  1392. list.sort() sorts the list in place. In order to remind you
  1393. of that fact, it does not return the sorted list. This way,
  1394. you won't be fooled into accidentally overwriting a list
  1395. when you need a sorted copy but also need to keep the
  1396. unsorted version around.</p>
  1397. <p>In Python 2.4 a new builtin - sorted() - has been added.
  1398. This function creates a new list from a passed
  1399. iterable, sorts it and returns it.</p>
  1400. <p>As a result, here's the idiom to iterate over the keys of a
  1401. dictionary in sorted order:</p>
  1402. <pre class="literal-block">
  1403. for key in sorted(dict.iterkeys()):
  1404.     ...do whatever with dict[key]...
  1405. </pre>
  1406. <p>Versions of Python prior to 2.4 need to use the following idiom:</p>
  1407. <pre class="literal-block">
  1408. keys = dict.keys()
  1409. keys.sort()
  1410. for key in keys:
  1411.     ...do whatever with dict[key]...
  1412. </pre>
  1413. </div>
  1414. <div class="section" id="how-do-you-specify-and-enforce-an-interface-spec-in-python">
  1415. <h2><a class="toc-backref" href="#id51">4.21   How do you specify and enforce an interface spec in Python?</a></h2>
  1416. <p>An interface specification for a module as provided by languages such
  1417. as C++ and Java describes the prototypes for the methods and functions
  1418. of the module.  Many feel that compile-time enforcement of interface
  1419. specifications help in the construction of large programs.  Python
  1420. does not support interface specifications directly, but many of their
  1421. advantages can be obtained by an appropriate test discipline for
  1422. components, which can often be very easily accomplished in Python.
  1423. There is also a tool, PyChecker, which can be used to find problems
  1424. due to subclassing.</p>
  1425. <p>A good test suite for a module can at once provide a regression test
  1426. and serve as both a module interface specification and a set of
  1427. examples.  Many Python modules can be run as a script to provide a
  1428. simple "self test."  Even modules which use complex external
  1429. interfaces can often be tested in isolation using trivial "stub"
  1430. emulations of the external interface.  The <tt class="docutils literal"><span class="pre">doctest</span></tt> and
  1431. <tt class="docutils literal"><span class="pre">unittest</span></tt> modules or third-party test frameworks can be used to construct
  1432. exhaustive test suites that exercise every line of code in a module.</p>
  1433. <p>An appropriate testing discipline can help build large complex
  1434. applications in Python as well as having interface specifications
  1435. would.  In fact, it can be better because an interface specification
  1436. cannot test certain properties of a program.  For example, the
  1437. <tt class="docutils literal"><span class="pre">append()</span></tt> method is expected to add new elements to the end of some
  1438. internal list; an interface specification cannot test that your
  1439. <tt class="docutils literal"><span class="pre">append()</span></tt> implementation will actually do this correctly, but it's
  1440. trivial to check this property in a test suite.</p>
  1441. <p>Writing test suites is very helpful, and you might want to design your
  1442. code with an eye to making it easily tested.  One increasingly popular
  1443. technique, test-directed development, calls for writing parts of the
  1444. test suite first, before you write any of the actual code.  Of course
  1445. Python allows you to be sloppy and not write test cases at all.</p>
  1446. </div>
  1447. <div class="section" id="why-are-default-values-shared-between-objects">
  1448. <h2><a class="toc-backref" href="#id52">4.22   Why are default values shared between objects?</a></h2>
  1449. <p>This type of bug commonly bites neophyte programmers.  Consider this function:</p>
  1450. <pre class="literal-block">
  1451. def foo(D={}):  # Danger: shared reference to one dict for all calls
  1452.     ... compute something ...
  1453.     D[key] = value
  1454.     return D
  1455. </pre>
  1456. <p>The first time you call this function, <tt class="docutils literal"><span class="pre">D</span></tt> contains a single item.
  1457. The second time, <tt class="docutils literal"><span class="pre">D</span></tt> contains two items because when <tt class="docutils literal"><span class="pre">foo()</span></tt> begins executing,
  1458. <tt class="docutils literal"><span class="pre">D</span></tt> starts out with an item already in it.</p>
  1459. <p>It is often expected that a function call creates new objects for
  1460. default values. This is not what happens. Default values are created
  1461. exactly once, when the function is defined.  If that object is
  1462. changed, like the dictionary in this example, subsequent calls to the
  1463. function will refer to this changed object.</p>
  1464. <p>By definition, immutable objects such as numbers, strings, tuples, and
  1465. <tt class="docutils literal"><span class="pre">None</span></tt>, are safe from change. Changes to mutable objects such as
  1466. dictionaries, lists, and class instances can lead to confusion.</p>
  1467. <p>Because of this feature, it is good programming practice to not use mutable
  1468. objects as default values.  Instead, use <tt class="docutils literal"><span class="pre">None</span></tt> as the default value
  1469. and inside the function, check if the parameter is <tt class="docutils literal"><span class="pre">None</span></tt> and create a new list/dictionary/whatever
  1470. if it is.  For example, don't write:</p>
  1471. <pre class="literal-block">
  1472. def foo(dict={}):
  1473.     ...
  1474. </pre>
  1475. <p>but:</p>
  1476. <pre class="literal-block">
  1477. def foo(dict=None):
  1478.     if dict is None:
  1479.         dict = {} # create a new dict for local namespace
  1480. </pre>
  1481. <p>This feature can be useful.  When you have a function that's time-consuming to compute,
  1482. a common technique is to cache the parameters and the resulting value of each
  1483. call to the function, and return the cached value if the same value is requested again.
  1484. This is called "memoizing", and can be implemented like this:</p>
  1485. <pre class="literal-block">
  1486. # Callers will never provide a third parameter for this function.
  1487. def expensive (arg1, arg2, _cache={}):
  1488.     if _cache.has_key((arg1, arg2)):
  1489.         return _cache[(arg1, arg2)]
  1490.  
  1491.     # Calculate the value
  1492.     result = ... expensive computation ...
  1493.     _cache[(arg1, arg2)] = result           # Store result in the cache
  1494.     return result
  1495. </pre>
  1496. <p>You could use a global variable containing a dictionary instead of
  1497. the default value; it's a matter of taste.</p>
  1498. </div>
  1499. <div class="section" id="why-is-there-no-goto">
  1500. <h2><a class="toc-backref" href="#id53">4.23   Why is there no goto?</a></h2>
  1501. <p>You can use exceptions to provide a "structured goto"
  1502. that even works across function calls.  Many feel that exceptions
  1503. can conveniently emulate all reasonable uses of the "go" or "goto"
  1504. constructs of C, Fortran, and other languages.  For example:</p>
  1505. <pre class="literal-block">
  1506. class label: pass # declare a label
  1507.  
  1508. try:
  1509.      ...
  1510.      if (condition): raise label() # goto label
  1511.      ...
  1512. except label: # where to goto
  1513.      pass
  1514. ...
  1515. </pre>
  1516. <p>This doesn't allow you to jump into the middle of a loop, but
  1517. that's usually considered an abuse of goto anyway.  Use sparingly.</p>
  1518. </div>
  1519. <div class="section" id="why-do-i-get-a-syntaxerror-for-a-continue-inside-a-try">
  1520. <h2><a class="toc-backref" href="#id54">4.24   Why do I get a SyntaxError for a 'continue' inside a 'try'?</a></h2>
  1521. <p>This is an implementation limitation, caused by the extremely
  1522. simple-minded way Python generates bytecode.  The <tt class="docutils literal"><span class="pre">try</span></tt> block pushes
  1523. something on the "block stack" which the <tt class="docutils literal"><span class="pre">continue</span></tt> would have to pop
  1524. off again.  The current code generator doesn't have the data
  1525. structures around so that <tt class="docutils literal"><span class="pre">continue</span></tt> can generate the right code.</p>
  1526. <p>Note that Jython doesn't have this restriction!</p>
  1527. </div>
  1528. <div class="section" id="why-can-t-raw-strings-r-strings-end-with-a-backslash">
  1529. <h2><a class="toc-backref" href="#id55">4.25   Why can't raw strings (r-strings) end with a backslash?</a></h2>
  1530. <p>More precisely, they can't end with an odd number of backslashes:
  1531. the unpaired backslash at the end escapes the closing quote character,
  1532. leaving an unterminated string.</p>
  1533. <p>Raw strings were designed to ease creating input for processors
  1534. (chiefly regular expression engines) that want to do their own
  1535. backslash escape processing. Such processors consider an unmatched
  1536. trailing backslash to be an error anyway, so raw strings disallow
  1537. that.  In return, they allow you to pass on the string quote character
  1538. by escaping it with a backslash.  These rules work well when r-strings
  1539. are used for their intended purpose.</p>
  1540. <p>If you're trying to build Windows pathnames, note that all Windows
  1541. system calls accept forward slashes too:</p>
  1542. <pre class="literal-block">
  1543. f = open("/mydir/file.txt") # works fine!
  1544. </pre>
  1545. <p>If you're trying to build a pathname for a DOS command, try e.g. one of</p>
  1546. <pre class="literal-block">
  1547. dir = r"\this\is\my\dos\dir" "\\"
  1548. dir = r"\this\is\my\dos\dir\ "[:-1]
  1549. dir = "\\this\\is\\my\\dos\\dir\\"
  1550. </pre>
  1551. </div>
  1552. <div class="section" id="why-doesn-t-python-have-a-with-statement-like-some-other-languages">
  1553. <h2><a class="toc-backref" href="#id56">4.26   Why doesn't Python have a "with" statement like some other languages?</a></h2>
  1554. <p>Because such a construct would be ambiguous.</p>
  1555. <p>Some languages, such as Object Pascal, Delphi, and C++, use static
  1556. types. So it is possible to know, in an unambiguous way, what member
  1557. is being assigned in a "with" clause. This is the main point - the
  1558. compiler <em>always</em> knows the scope of every variable at compile time.</p>
  1559. <p>Python uses dynamic types. It is impossible to know in advance which
  1560. attribute will be referenced at runtime. Member attributes may be
  1561. added or removed from objects on the fly. This would make it
  1562. impossible to know, from a simple reading, what attribute is being
  1563. referenced - a local one, a global one, or a member attribute.</p>
  1564. <p>For instance, take the following incomplete snippet:</p>
  1565. <pre class="literal-block">
  1566. def foo(a):
  1567.    with a:
  1568.       print x
  1569. </pre>
  1570. <p>The snippet assumes that "a" must have a member attribute called "x".
  1571. However, there is nothing in Python that guarantees that. What should
  1572. happen if "a" is, let us say, an integer? And if I have a global
  1573. variable named "x", will it end up being used inside the with block?
  1574. As you see, the dynamic nature of Python makes such choices much
  1575. harder.</p>
  1576. <p>The primary benefit of "with" and similar language features (reduction
  1577. of code volume) can, however, easily be achieved in Python by
  1578. assignment. Instead of:</p>
  1579. <pre class="literal-block">
  1580. function(args).dict[index][index].a = 21
  1581. function(args).dict[index][index].b = 42
  1582. function(args).dict[index][index].c = 63
  1583. </pre>
  1584. <p>write this:</p>
  1585. <pre class="literal-block">
  1586. ref = function(args).dict[index][index]
  1587. ref.a = 21
  1588. ref.b = 42
  1589. ref.c = 63
  1590. </pre>
  1591. <p>This also has the side-effect of increasing execution speed because
  1592. name bindings are resolved at run-time in Python, and the second
  1593. version only needs to perform the resolution once. If the referenced
  1594. object does not have a, b and c attributes, of course, the end result
  1595. is still a run-time exception.</p>
  1596. </div>
  1597. <div class="section" id="why-are-colons-required-for-the-if-while-def-class-statements">
  1598. <h2><a class="toc-backref" href="#id57">4.27   Why are colons required for the if/while/def/class statements?</a></h2>
  1599. <p>The colon is required primarily to enhance readability (one of the
  1600. results of the experimental ABC language).  Consider this:</p>
  1601. <pre class="literal-block">
  1602. if a==b
  1603.     print a
  1604. </pre>
  1605. <p>versus</p>
  1606. <pre class="literal-block">
  1607. if a==b:
  1608.     print a
  1609. </pre>
  1610. <p>Notice how the second one is slightly easier to read.  Notice further how
  1611. a colon sets off the example in the second line of this FAQ answer; it's
  1612. a standard usage in English.</p>
  1613. <p>Another minor reason is that the colon makes it easier for editors
  1614. with syntax highlighting; they can look for colons to decide when
  1615. indentation needs to be increased instead of having to do a more
  1616. elaborate parsing of the program text.</p>
  1617. </div>
  1618. </div>
  1619. </div>
  1620. </body>
  1621. </html>
  1622.