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