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

  1. <?xml version="1.0" encoding="utf-8" ?>
  2. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  3. <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
  4. <head>
  5. <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  6. <meta name="generator" content="Docutils 0.5: http://docutils.sourceforge.net/" />
  7. <title>Programming FAQ</title>
  8. <meta name="date" content="2005-12-21" />
  9. <style type="text/css">
  10.  
  11. /*
  12. :Author: David Goodger (goodger@python.org)
  13. :Id: $Id: html4css1.css 5196 2007-06-03 20:25:28Z wiemann $
  14. :Copyright: This stylesheet has been placed in the public domain.
  15.  
  16. Default cascading style sheet for the HTML output of Docutils.
  17.  
  18. See http://docutils.sf.net/docs/howto/html-stylesheets.html for how to
  19. customize this style sheet.
  20. */
  21.  
  22. /* used to remove borders from tables and images */
  23. .borderless, table.borderless td, table.borderless th {
  24.   border: 0 }
  25.  
  26. table.borderless td, table.borderless th {
  27.   /* Override padding for "table.docutils td" with "! important".
  28.      The right padding separates the table cells. */
  29.   padding: 0 0.5em 0 0 ! important }
  30.  
  31. .first {
  32.   /* Override more specific margin styles with "! important". */
  33.   margin-top: 0 ! important }
  34.  
  35. .last, .with-subtitle {
  36.   margin-bottom: 0 ! important }
  37.  
  38. .hidden {
  39.   display: none }
  40.  
  41. a.toc-backref {
  42.   text-decoration: none ;
  43.   color: black }
  44.  
  45. blockquote.epigraph {
  46.   margin: 2em 5em ; }
  47.  
  48. dl.docutils dd {
  49.   margin-bottom: 0.5em }
  50.  
  51. /* Uncomment (and remove this text!) to get bold-faced definition list terms
  52. dl.docutils dt {
  53.   font-weight: bold }
  54. */
  55.  
  56. div.abstract {
  57.   margin: 2em 5em }
  58.  
  59. div.abstract p.topic-title {
  60.   font-weight: bold ;
  61.   text-align: center }
  62.  
  63. div.admonition, div.attention, div.caution, div.danger, div.error,
  64. div.hint, div.important, div.note, div.tip, div.warning {
  65.   margin: 2em ;
  66.   border: medium outset ;
  67.   padding: 1em }
  68.  
  69. div.admonition p.admonition-title, div.hint p.admonition-title,
  70. div.important p.admonition-title, div.note p.admonition-title,
  71. div.tip p.admonition-title {
  72.   font-weight: bold ;
  73.   font-family: sans-serif }
  74.  
  75. div.attention p.admonition-title, div.caution p.admonition-title,
  76. div.danger p.admonition-title, div.error p.admonition-title,
  77. div.warning p.admonition-title {
  78.   color: red ;
  79.   font-weight: bold ;
  80.   font-family: sans-serif }
  81.  
  82. /* Uncomment (and remove this text!) to get reduced vertical space in
  83.    compound paragraphs.
  84. div.compound .compound-first, div.compound .compound-middle {
  85.   margin-bottom: 0.5em }
  86.  
  87. div.compound .compound-last, div.compound .compound-middle {
  88.   margin-top: 0.5em }
  89. */
  90.  
  91. div.dedication {
  92.   margin: 2em 5em ;
  93.   text-align: center ;
  94.   font-style: italic }
  95.  
  96. div.dedication p.topic-title {
  97.   font-weight: bold ;
  98.   font-style: normal }
  99.  
  100. div.figure {
  101.   margin-left: 2em ;
  102.   margin-right: 2em }
  103.  
  104. div.footer, div.header {
  105.   clear: both;
  106.   font-size: smaller }
  107.  
  108. div.line-block {
  109.   display: block ;
  110.   margin-top: 1em ;
  111.   margin-bottom: 1em }
  112.  
  113. div.line-block div.line-block {
  114.   margin-top: 0 ;
  115.   margin-bottom: 0 ;
  116.   margin-left: 1.5em }
  117.  
  118. div.sidebar {
  119.   margin: 0 0 0.5em 1em ;
  120.   border: medium outset ;
  121.   padding: 1em ;
  122.   background-color: #ffffee ;
  123.   width: 40% ;
  124.   float: right ;
  125.   clear: right }
  126.  
  127. div.sidebar p.rubric {
  128.   font-family: sans-serif ;
  129.   font-size: medium }
  130.  
  131. div.system-messages {
  132.   margin: 5em }
  133.  
  134. div.system-messages h1 {
  135.   color: red }
  136.  
  137. div.system-message {
  138.   border: medium outset ;
  139.   padding: 1em }
  140.  
  141. div.system-message p.system-message-title {
  142.   color: red ;
  143.   font-weight: bold }
  144.  
  145. div.topic {
  146.   margin: 2em }
  147.  
  148. h1.section-subtitle, h2.section-subtitle, h3.section-subtitle,
  149. h4.section-subtitle, h5.section-subtitle, h6.section-subtitle {
  150.   margin-top: 0.4em }
  151.  
  152. h1.title {
  153.   text-align: center }
  154.  
  155. h2.subtitle {
  156.   text-align: center }
  157.  
  158. hr.docutils {
  159.   width: 75% }
  160.  
  161. img.align-left {
  162.   clear: left }
  163.  
  164. img.align-right {
  165.   clear: right }
  166.  
  167. ol.simple, ul.simple {
  168.   margin-bottom: 1em }
  169.  
  170. ol.arabic {
  171.   list-style: decimal }
  172.  
  173. ol.loweralpha {
  174.   list-style: lower-alpha }
  175.  
  176. ol.upperalpha {
  177.   list-style: upper-alpha }
  178.  
  179. ol.lowerroman {
  180.   list-style: lower-roman }
  181.  
  182. ol.upperroman {
  183.   list-style: upper-roman }
  184.  
  185. p.attribution {
  186.   text-align: right ;
  187.   margin-left: 50% }
  188.  
  189. p.caption {
  190.   font-style: italic }
  191.  
  192. p.credits {
  193.   font-style: italic ;
  194.   font-size: smaller }
  195.  
  196. p.label {
  197.   white-space: nowrap }
  198.  
  199. p.rubric {
  200.   font-weight: bold ;
  201.   font-size: larger ;
  202.   color: maroon ;
  203.   text-align: center }
  204.  
  205. p.sidebar-title {
  206.   font-family: sans-serif ;
  207.   font-weight: bold ;
  208.   font-size: larger }
  209.  
  210. p.sidebar-subtitle {
  211.   font-family: sans-serif ;
  212.   font-weight: bold }
  213.  
  214. p.topic-title {
  215.   font-weight: bold }
  216.  
  217. pre.address {
  218.   margin-bottom: 0 ;
  219.   margin-top: 0 ;
  220.   font-family: serif ;
  221.   font-size: 100% }
  222.  
  223. pre.literal-block, pre.doctest-block {
  224.   margin-left: 2em ;
  225.   margin-right: 2em }
  226.  
  227. span.classifier {
  228.   font-family: sans-serif ;
  229.   font-style: oblique }
  230.  
  231. span.classifier-delimiter {
  232.   font-family: sans-serif ;
  233.   font-weight: bold }
  234.  
  235. span.interpreted {
  236.   font-family: sans-serif }
  237.  
  238. span.option {
  239.   white-space: nowrap }
  240.  
  241. span.pre {
  242.   white-space: pre }
  243.  
  244. span.problematic {
  245.   color: red }
  246.  
  247. span.section-subtitle {
  248.   /* font-size relative to parent (h1..h6 element) */
  249.   font-size: 80% }
  250.  
  251. table.citation {
  252.   border-left: solid 1px gray;
  253.   margin-left: 1px }
  254.  
  255. table.docinfo {
  256.   margin: 2em 4em }
  257.  
  258. table.docutils {
  259.   margin-top: 0.5em ;
  260.   margin-bottom: 0.5em }
  261.  
  262. table.footnote {
  263.   border-left: solid 1px black;
  264.   margin-left: 1px }
  265.  
  266. table.docutils td, table.docutils th,
  267. table.docinfo td, table.docinfo th {
  268.   padding-left: 0.5em ;
  269.   padding-right: 0.5em ;
  270.   vertical-align: top }
  271.  
  272. table.docutils th.field-name, table.docinfo th.docinfo-name {
  273.   font-weight: bold ;
  274.   text-align: left ;
  275.   white-space: nowrap ;
  276.   padding-left: 0 }
  277.  
  278. h1 tt.docutils, h2 tt.docutils, h3 tt.docutils,
  279. h4 tt.docutils, h5 tt.docutils, h6 tt.docutils {
  280.   font-size: 100% }
  281.  
  282. ul.auto-toc {
  283.   list-style-type: none }
  284.  
  285. </style>
  286. </head>
  287. <body>
  288. <div class="document" id="programming-faq">
  289. <h1 class="title">Programming FAQ</h1>
  290. <table class="docinfo" frame="void" rules="none">
  291. <col class="docinfo-name" />
  292. <col class="docinfo-content" />
  293. <tbody valign="top">
  294. <tr><th class="docinfo-name">Date:</th>
  295. <td>2005-12-21</td></tr>
  296. <tr><th class="docinfo-name">Version:</th>
  297. <td>8721</td></tr>
  298. <tr class="field"><th class="docinfo-name">Web site:</th><td class="field-body"><a class="reference external" href="http://www.python.org/">http://www.python.org/</a></td>
  299. </tr>
  300. </tbody>
  301. </table>
  302. <div class="contents topic" id="contents">
  303. <p class="topic-title first">Contents</p>
  304. <ul class="auto-toc simple">
  305. <li><a class="reference internal" href="#general-questions" id="id1">1   General Questions</a><ul class="auto-toc">
  306. <li><a class="reference internal" href="#is-there-a-source-code-level-debugger-with-breakpoints-single-stepping-etc" id="id2">1.1   Is there a source code level debugger with breakpoints, single-stepping, etc.?</a></li>
  307. <li><a class="reference internal" href="#is-there-a-tool-to-help-find-bugs-or-perform-static-analysis" id="id3">1.2   Is there a tool to help find bugs or perform static analysis?</a></li>
  308. <li><a class="reference internal" href="#how-can-i-create-a-stand-alone-binary-from-a-python-script" id="id4">1.3   How can I create a stand-alone binary from a Python script?</a></li>
  309. <li><a class="reference internal" href="#are-there-coding-standards-or-a-style-guide-for-python-programs" id="id5">1.4   Are there coding standards or a style guide for Python programs?</a></li>
  310. <li><a class="reference internal" href="#my-program-is-too-slow-how-do-i-speed-it-up" id="id6">1.5   My program is too slow. How do I speed it up?</a></li>
  311. </ul>
  312. </li>
  313. <li><a class="reference internal" href="#core-language" id="id7">2   Core Language</a><ul class="auto-toc">
  314. <li><a class="reference internal" href="#how-do-you-set-a-global-variable-in-a-function" id="id8">2.1   How do you set a global variable in a function?</a></li>
  315. <li><a class="reference internal" href="#what-are-the-rules-for-local-and-global-variables-in-python" id="id9">2.2   What are the rules for local and global variables in Python?</a></li>
  316. <li><a class="reference internal" href="#how-do-i-share-global-variables-across-modules" id="id10">2.3   How do I share global variables across modules?</a></li>
  317. <li><a class="reference internal" href="#what-are-the-best-practices-for-using-import-in-a-module" id="id11">2.4   What are the "best practices" for using import in a module?</a></li>
  318. <li><a class="reference internal" href="#how-can-i-pass-optional-or-keyword-parameters-from-one-function-to-another" id="id12">2.5   How can I pass optional or keyword parameters from one function to another?</a></li>
  319. <li><a class="reference internal" href="#how-do-i-write-a-function-with-output-parameters-call-by-reference" id="id13">2.6   How do I write a function with output parameters (call by reference)?</a></li>
  320. <li><a class="reference internal" href="#how-do-you-make-a-higher-order-function-in-python" id="id14">2.7   How do you make a higher order function in Python?</a></li>
  321. <li><a class="reference internal" href="#how-do-i-copy-an-object-in-python" id="id15">2.8   How do I copy an object in Python?</a></li>
  322. <li><a class="reference internal" href="#how-can-i-find-the-methods-or-attributes-of-an-object" id="id16">2.9   How can I find the methods or attributes of an object?</a></li>
  323. <li><a class="reference internal" href="#how-can-my-code-discover-the-name-of-an-object" id="id17">2.10   How can my code discover the name of an object?</a></li>
  324. <li><a class="reference internal" href="#is-there-an-equivalent-of-c-s-ternary-operator" id="id18">2.11   Is there an equivalent of C's "?:" ternary operator?</a></li>
  325. <li><a class="reference internal" href="#is-it-possible-to-write-obfuscated-one-liners-in-python" id="id19">2.12   Is it possible to write obfuscated one-liners in Python?</a></li>
  326. </ul>
  327. </li>
  328. <li><a class="reference internal" href="#numbers-and-strings" id="id20">3   Numbers and strings</a><ul class="auto-toc">
  329. <li><a class="reference internal" href="#how-do-i-specify-hexadecimal-and-octal-integers" id="id21">3.1   How do I specify hexadecimal and octal integers?</a></li>
  330. <li><a class="reference internal" href="#why-does-22-10-return-3" id="id22">3.2   Why does -22 / 10 return -3?</a></li>
  331. <li><a class="reference internal" href="#how-do-i-convert-a-string-to-a-number" id="id23">3.3   How do I convert a string to a number?</a></li>
  332. <li><a class="reference internal" href="#how-do-i-convert-a-number-to-a-string" id="id24">3.4   How do I convert a number to a string?</a></li>
  333. <li><a class="reference internal" href="#how-do-i-modify-a-string-in-place" id="id25">3.5   How do I modify a string in place?</a></li>
  334. <li><a class="reference internal" href="#how-do-i-use-strings-to-call-functions-methods" id="id26">3.6   How do I use strings to call functions/methods?</a></li>
  335. <li><a class="reference internal" href="#is-there-an-equivalent-to-perl-s-chomp-for-removing-trailing-newlines-from-strings" id="id27">3.7   Is there an equivalent to Perl's chomp() for removing trailing newlines from strings?</a></li>
  336. <li><a class="reference internal" href="#is-there-a-scanf-or-sscanf-equivalent" id="id28">3.8   Is there a scanf() or sscanf() equivalent?</a></li>
  337. <li><a class="reference internal" href="#what-does-unicodeerror-ascii-decoding-encoding-error-ordinal-not-in-range-128-mean" id="id29">3.9   What does 'UnicodeError: ASCII [decoding,encoding] error: ordinal not in range(128)' mean?</a></li>
  338. </ul>
  339. </li>
  340. <li><a class="reference internal" href="#sequences-tuples-lists" id="id30">4   Sequences (Tuples/Lists)</a><ul class="auto-toc">
  341. <li><a class="reference internal" href="#how-do-i-convert-between-tuples-and-lists" id="id31">4.1   How do I convert between tuples and lists?</a></li>
  342. <li><a class="reference internal" href="#what-s-a-negative-index" id="id32">4.2   What's a negative index?</a></li>
  343. <li><a class="reference internal" href="#how-do-i-iterate-over-a-sequence-in-reverse-order" id="id33">4.3   How do I iterate over a sequence in reverse order?</a></li>
  344. <li><a class="reference internal" href="#how-do-you-remove-duplicates-from-a-list" id="id34">4.4   How do you remove duplicates from a list?</a></li>
  345. <li><a class="reference internal" href="#how-do-you-make-an-array-in-python" id="id35">4.5   How do you make an array in Python?</a></li>
  346. <li><a class="reference internal" href="#how-do-i-create-a-multidimensional-list" id="id36">4.6   How do I create a multidimensional list?</a></li>
  347. <li><a class="reference internal" href="#how-do-i-apply-a-method-to-a-sequence-of-objects" id="id37">4.7   How do I apply a method to a sequence of objects?</a></li>
  348. </ul>
  349. </li>
  350. <li><a class="reference internal" href="#dictionaries" id="id38">5   Dictionaries</a><ul class="auto-toc">
  351. <li><a class="reference internal" href="#how-can-i-get-a-dictionary-to-display-its-keys-in-a-consistent-order" id="id39">5.1   How can I get a dictionary to display its keys in a consistent order?</a></li>
  352. <li><a class="reference internal" href="#i-want-to-do-a-complicated-sort-can-you-do-a-schwartzian-transform-in-python" id="id40">5.2   I want to do a complicated sort: can you do a Schwartzian Transform in Python?</a></li>
  353. <li><a class="reference internal" href="#how-can-i-sort-one-list-by-values-from-another-list" id="id41">5.3   How can I sort one list by values from another list?</a></li>
  354. </ul>
  355. </li>
  356. <li><a class="reference internal" href="#objects" id="id42">6   Objects</a><ul class="auto-toc">
  357. <li><a class="reference internal" href="#what-is-a-class" id="id43">6.1   What is a class?</a></li>
  358. <li><a class="reference internal" href="#what-is-a-method" id="id44">6.2   What is a method?</a></li>
  359. <li><a class="reference internal" href="#what-is-self" id="id45">6.3   What is self?</a></li>
  360. <li><a class="reference internal" href="#how-do-i-check-if-an-object-is-an-instance-of-a-given-class-or-of-a-subclass-of-it" id="id46">6.4   How do I check if an object is an instance of a given class or of a subclass of it?</a></li>
  361. <li><a class="reference internal" href="#what-is-delegation" id="id47">6.5   What is delegation?</a></li>
  362. <li><a class="reference internal" href="#how-do-i-call-a-method-defined-in-a-base-class-from-a-derived-class-that-overrides-it" id="id48">6.6   How do I call a method defined in a base class from a derived class that overrides it?</a></li>
  363. <li><a class="reference internal" href="#how-can-i-organize-my-code-to-make-it-easier-to-change-the-base-class" id="id49">6.7   How can I organize my code to make it easier to change the base class?</a></li>
  364. <li><a class="reference internal" href="#how-do-i-create-static-class-data-and-static-class-methods" id="id50">6.8   How do I create static class data and static class methods?</a></li>
  365. <li><a class="reference internal" href="#how-can-i-overload-constructors-or-methods-in-python" id="id51">6.9   How can I overload constructors (or methods) in Python?</a></li>
  366. <li><a class="reference internal" href="#i-try-to-use-spam-and-i-get-an-error-about-someclassname-spam" id="id52">6.10   I try to use __spam and I get an error about _SomeClassName__spam.</a></li>
  367. <li><a class="reference internal" href="#my-class-defines-del-but-it-is-not-called-when-i-delete-the-object" id="id53">6.11   My class defines __del__ but it is not called when I delete the object.</a></li>
  368. <li><a class="reference internal" href="#how-do-i-get-a-list-of-all-instances-of-a-given-class" id="id54">6.12   How do I get a list of all instances of a given class?</a></li>
  369. </ul>
  370. </li>
  371. <li><a class="reference internal" href="#modules" id="id55">7   Modules</a><ul class="auto-toc">
  372. <li><a class="reference internal" href="#how-do-i-create-a-pyc-file" id="id56">7.1   How do I create a .pyc file?</a></li>
  373. <li><a class="reference internal" href="#how-do-i-find-the-current-module-name" id="id57">7.2   How do I find the current module name?</a></li>
  374. <li><a class="reference internal" href="#how-can-i-have-modules-that-mutually-import-each-other" id="id58">7.3   How can I have modules that mutually import each other?</a></li>
  375. <li><a class="reference internal" href="#import-x-y-z-returns-module-x-how-do-i-get-z" id="id59">7.4   __import__('x.y.z') returns <module 'x'>; how do I get z?</a></li>
  376. <li><a class="reference internal" href="#when-i-edit-an-imported-module-and-reimport-it-the-changes-don-t-show-up-why-does-this-happen" id="id60">7.5   When I edit an imported module and reimport it, the changes don't show up.  Why does this happen?</a></li>
  377. </ul>
  378. </li>
  379. </ul>
  380. </div>
  381. <div class="section" id="general-questions">
  382. <h1><a class="toc-backref" href="#id1">1   General Questions</a></h1>
  383. <div class="section" id="is-there-a-source-code-level-debugger-with-breakpoints-single-stepping-etc">
  384. <h2><a class="toc-backref" href="#id2">1.1   Is there a source code level debugger with breakpoints, single-stepping, etc.?</a></h2>
  385. <p>Yes.</p>
  386. <p>The pdb module is a simple but adequate console-mode debugger for
  387. Python. It is part of the standard Python library, and is <a class="reference external" href="http://docs.python.org/lib/module-pdb.html">documented
  388. in the Library Reference Manual</a>. You can
  389. also write your own debugger by using the code for pdb as an example.</p>
  390. <p>The IDLE interactive development environment, which is part of the
  391. standard Python distribution (normally available as Tools/scripts/idle),
  392. includes a graphical debugger.  There is documentation for the IDLE
  393. debugger at <a class="reference external" href="http://www.python.org/idle/doc/idle2.html#Debugger">http://www.python.org/idle/doc/idle2.html#Debugger</a></p>
  394. <p>PythonWin is a Python IDE that includes a GUI debugger based on pdb.
  395. The Pythonwin debugger colors breakpoints and has quite a few cool
  396. features such as debugging non-Pythonwin programs.  A reference can be
  397. found at <a class="reference external" href="http://www.python.org/windows/pythonwin/">http://www.python.org/windows/pythonwin/</a>. Recent versions of
  398. PythonWin are available as a part of the ActivePython distribution
  399. (see <a class="reference external" href="http://www.activestate.com/Products/ActivePython/index.html">http://www.activestate.com/Products/ActivePython/index.html</a>).</p>
  400. <p><a class="reference external" href="http://boa-constructor.sourceforge.net/">Boa Constructor</a> is an IDE
  401. and GUI builder that uses wxPython.  It offers visual frame creation
  402. and manipulation, an object
  403. inspector,  many views on the source like object browsers, inheritance
  404. hierarchies,  doc  string  generated  html  documentation, an advanced
  405. debugger, integrated help, and Zope support.</p>
  406. <p><a class="reference external" href="http://www.die-offenbachs.de/detlev/eric3.html">Eric3</a> is an IDE
  407. built on PyQt and the Scintilla editing component.</p>
  408. <p>Pydb is a version of the standard Python debugger pdb, modified for
  409. use with DDD (Data Display Debugger), a popular graphical debugger
  410. front end.  Pydb can be found at
  411. <a class="reference external" href="http://packages.debian.org/unstable/devel/pydb.html">http://packages.debian.org/unstable/devel/pydb.html</a>> and DDD can be
  412. found at <a class="reference external" href="http://www.gnu.org/software/ddd">http://www.gnu.org/software/ddd</a>.</p>
  413. <p>There are a number of commmercial Python IDEs that include graphical
  414. debuggers.  They include:</p>
  415. <ul class="simple">
  416. <li>Wing IDE (<a class="reference external" href="http://wingide.com">http://wingide.com</a>)</li>
  417. <li>Komodo IDE (<a class="reference external" href="http://www.activestate.com/Products/Komodo">http://www.activestate.com/Products/Komodo</a>)</li>
  418. </ul>
  419. </div>
  420. <div class="section" id="is-there-a-tool-to-help-find-bugs-or-perform-static-analysis">
  421. <h2><a class="toc-backref" href="#id3">1.2   Is there a tool to help find bugs or perform static analysis?</a></h2>
  422. <p>Yes.</p>
  423. <p>PyChecker is a static analysis tool that finds bugs in Python source
  424. code and warns about code complexity and style.  You can get PyChecker
  425. from <a class="reference external" href="http://pychecker.sf.net">http://pychecker.sf.net</a>.</p>
  426. <p><a class="reference external" href="http://www.logilab.org/projects/pylint">Pylint</a> is another tool
  427. that checks if a module satisfies a coding standard, and also makes it
  428. possible to write plug-ins to add a custom feature.  In addition to
  429. the bug checking that PyChecker performs, Pylint offers some
  430. additional features such as checking line length, whether variable
  431. names are well-formed according to your coding standard, whether
  432. declared interfaces are fully implemented, and more.
  433. <a class="reference external" href="http://www.logilab.org/projects/pylint/documentation">http://www.logilab.org/projects/pylint/documentation</a> provides a full
  434. list of Pylint's features.</p>
  435. </div>
  436. <div class="section" id="how-can-i-create-a-stand-alone-binary-from-a-python-script">
  437. <h2><a class="toc-backref" href="#id4">1.3   How can I create a stand-alone binary from a Python script?</a></h2>
  438. <p>You don't need the ability to compile Python to C code if all you
  439. want is a stand-alone program that users can download and run without
  440. having to install the Python distribution first.  There are a number
  441. of tools that determine the set of modules required by a program and
  442. bind these modules together with a Python binary to produce a single
  443. executable.</p>
  444. <p>One is to use the freeze tool, which is included in the Python
  445. source tree as <tt class="docutils literal"><span class="pre">Tools/freeze</span></tt>. It converts Python byte
  446. code to C arrays; a C compiler you can embed all
  447. your modules into a new program, which is then linked
  448. with the standard Python modules.</p>
  449. <p>It works by scanning your source recursively for import statements (in
  450. both forms) and looking for the modules in the standard Python path as
  451. well as in the source directory (for built-in modules).  It then turns
  452. the bytecode for modules written in Python into C code (array
  453. initializers that can be turned into code objects using the marshal
  454. module) and creates a custom-made config file that only contains those
  455. built-in modules which are actually used in the program.  It then
  456. compiles the generated C code and links it with the rest of the Python
  457. interpreter to form a self-contained binary which acts exactly like
  458. your script.</p>
  459. <p>Obviously, freeze requires a C compiler.  There are several other
  460. utilities which don't. The first is Gordon McMillan's installer at</p>
  461. <blockquote>
  462. <a class="reference external" href="http://www.mcmillan-inc.com/install1.html">http://www.mcmillan-inc.com/install1.html</a></blockquote>
  463. <p>which works on Windows, Linux and at least some forms of Unix.</p>
  464. <p>Another is Thomas Heller's py2exe (Windows only) at</p>
  465. <blockquote>
  466. <a class="reference external" href="http://starship.python.net/crew/theller/py2exe">http://starship.python.net/crew/theller/py2exe</a></blockquote>
  467. <p>A third is Christian Tismer's <a class="reference external" href="http://starship.python.net/crew/pirx">SQFREEZE</a> which appends the byte code
  468. to a specially-prepared Python interpreter that can find the byte
  469. code in the executable.  It's possible that a similar approach will
  470. be added to Python 2.4, due out some time in 2004.</p>
  471. <p>Other tools include Fredrik Lundh's <a class="reference external" href="http://www.pythonware.com/products/python/squeeze">Squeeze</a> and Anthony
  472. Tuininga's <a class="reference external" href="http://starship.python.net/crew/atuining/cx_Freeze/index.html">cx_Freeze</a>.</p>
  473. </div>
  474. <div class="section" id="are-there-coding-standards-or-a-style-guide-for-python-programs">
  475. <h2><a class="toc-backref" href="#id5">1.4   Are there coding standards or a style guide for Python programs?</a></h2>
  476. <p>Yes.  The coding style required for standard library modules
  477. is documented as <a class="reference external" href="../../peps/pep-0008.html">PEP 8</a>.</p>
  478. </div>
  479. <div class="section" id="my-program-is-too-slow-how-do-i-speed-it-up">
  480. <h2><a class="toc-backref" href="#id6">1.5   My program is too slow. How do I speed it up?</a></h2>
  481. <p>That's a tough one, in general.  There are many tricks to speed up
  482. Python code; consider rewriting parts in C as a last resort.</p>
  483. <p>In some cases it's possible to automatically translate Python to C or
  484. x86 assembly language, meaning that you don't have to modify your code
  485. to gain increased speed.</p>
  486. <p><a class="reference external" href="http://www.cosc.canterbury.ac.nz/~greg/python/Pyrex/">Pyrex</a> can
  487. compile a slightly modified version of Python code into a C extension,
  488. and can be used on many different platforms.</p>
  489. <p><a class="reference external" href="http://psyco.sourceforge.net">Psyco</a> is a just-in-time compiler
  490. that translates Python code into x86 assembly language.  If you can
  491. use it, Psyco can provide dramatic speedups for critical functions.</p>
  492. <p>The rest of this answer will discuss various tricks for squeezing a
  493. bit more speed out of Python code.  <em>Never</em> apply any optimization
  494. tricks unless you know you need them, after profiling has indicated
  495. that a particular function is the heavily executed hot spot in the
  496. code.  Optimizations almost always make the code less clear, and you
  497. shouldn't pay the costs of reduced clarity (increased development
  498. time, greater likelihood of bugs) unless the resulting performance
  499. benefit is worth it.</p>
  500. <p>There is a page on the wiki devoted to <a class="reference external" href="http://wiki.python.org/moin/PythonSpeed/PerformanceTips">performance tips</a>.</p>
  501. <p>Guido van Rossum has written up an anecdote related to optimization at
  502. <a class="reference external" href="http://www.python.org/doc/essays/list2str.html">http://www.python.org/doc/essays/list2str.html</a>.</p>
  503. <p>One thing to notice is that function and (especially) method calls are
  504. rather expensive; if you have designed a purely OO interface with lots
  505. of tiny functions that don't do much more than get or set an instance
  506. variable or call another method, you might consider using a more
  507. direct way such as directly accessing instance variables.  Also see the
  508. standard module "profile" (<a class="reference external" href="http://docs.python.org/lib/module-profile.html">described in the Library Reference manual</a>) which
  509. makes it possible to find out where your program is spending most of
  510. its time (if you have some patience -- the profiling itself can slow
  511. your program down by an order of magnitude).</p>
  512. <p>Remember that many standard optimization heuristics you
  513. may know from other programming experience may well apply
  514. to Python.  For example it may be faster to send output to output
  515. devices using larger writes rather than smaller ones in order to
  516. reduce the overhead of kernel system calls.  Thus CGI scripts
  517. that write all output in "one shot" may be faster than
  518. those that write lots of small pieces of output.</p>
  519. <p>Also, be sure to use Python's core features where appropriate.
  520. For example,  slicing allows programs to chop up
  521. lists and other sequence objects in a single tick of the interpreter's
  522. mainloop using highly optimized C implementations.  Thus to
  523. get the same effect as:</p>
  524. <pre class="literal-block">
  525. L2 = []
  526. for i in range[3]:
  527.      L2.append(L1[i])
  528. </pre>
  529. <p>it is much shorter and far faster to use</p>
  530. <pre class="literal-block">
  531. L2 = list(L1[:3]) # "list" is redundant if L1 is a list.
  532. </pre>
  533. <p>Note that the functionally-oriented builtins such as
  534. <tt class="docutils literal"><span class="pre">map()</span></tt>, <tt class="docutils literal"><span class="pre">zip()</span></tt>, and friends can be a convenient
  535. accelerator for loops that perform a single task.  For example to pair the elements of two
  536. lists together:</p>
  537. <pre class="literal-block">
  538. >>> zip([1,2,3], [4,5,6])
  539. [(1, 4), (2, 5), (3, 6)]
  540. </pre>
  541. <p>or to compute a number of sines:</p>
  542. <pre class="literal-block">
  543. >>> map( math.sin, (1,2,3,4))
  544. [0.841470984808, 0.909297426826, 0.14112000806,   -0.756802495308]
  545. </pre>
  546. <p>The operation completes very quickly in such cases.</p>
  547. <p>Other examples include the <tt class="docutils literal"><span class="pre">join()</span></tt> and <tt class="docutils literal"><span class="pre">split()</span></tt>
  548. methods of string objects.  For example if s1..s7 are large (10K+) strings then
  549. <tt class="docutils literal"><span class="pre">"".join([s1,s2,s3,s4,s5,s6,s7])`</span> <span class="pre">may</span> <span class="pre">be</span> <span class="pre">far</span> <span class="pre">faster</span> <span class="pre">than</span>
  550. <span class="pre">the</span> <span class="pre">more</span> <span class="pre">obvious</span> <span class="pre">``s1+s2+s3+s4+s5+s6+s7</span></tt>, since the "summation"
  551. will compute many subexpressions, whereas <tt class="docutils literal"><span class="pre">join()</span></tt> does all the
  552. copying in one pass.  For manipulating strings, use
  553. the <tt class="docutils literal"><span class="pre">replace()</span></tt> method on string objects. Use
  554. regular expressions only when you're not dealing with constant string patterns.
  555. Consider using the string formatting operations
  556. <tt class="docutils literal"><span class="pre">string</span> <span class="pre">%</span> <span class="pre">tuple</span></tt> and <tt class="docutils literal"><span class="pre">string</span> <span class="pre">%</span> <span class="pre">dictionary</span></tt>.</p>
  557. <p>Be sure to use the <tt class="docutils literal"><span class="pre">list.sort()</span></tt> builtin method to do sorting, and see
  558. the <a class="reference external" href="http://wiki.python.org/moin/HowTo/Sorting">sorting mini-HOWTO</a> for examples of moderately advanced usage.
  559. <tt class="docutils literal"><span class="pre">list.sort()</span></tt> beats other techniques for sorting in all but the most
  560. extreme circumstances.</p>
  561. <p>Another common trick is to "push loops into functions or methods."
  562. For example suppose you have a program that runs slowly and you
  563. use the profiler to determine that a Python function <tt class="docutils literal"><span class="pre">ff()</span></tt>
  564. is being called lots of times.  If you notice that <tt class="docutils literal"><span class="pre">ff</span> <span class="pre">()</span></tt>:</p>
  565. <pre class="literal-block">
  566. def ff(x):
  567.     ...do something with x computing result...
  568.     return result
  569. </pre>
  570. <p>tends to be called in loops like:</p>
  571. <pre class="literal-block">
  572. list = map(ff, oldlist)
  573. </pre>
  574. <p>or:</p>
  575. <pre class="literal-block">
  576. for x in sequence:
  577.     value = ff(x)
  578.     ...do something with value...
  579. </pre>
  580. <p>then you can often eliminate function call overhead by rewriting
  581. <tt class="docutils literal"><span class="pre">ff()</span></tt> to:</p>
  582. <pre class="literal-block">
  583. def ffseq(seq):
  584.     resultseq = []
  585.     for x in seq:
  586.         ...do something with x computing result...
  587.         resultseq.append(result)
  588.     return resultseq
  589. </pre>
  590. <p>and rewrite the two examples to <tt class="docutils literal"><span class="pre">list</span> <span class="pre">=</span> <span class="pre">ffseq(oldlist)</span></tt> and to:</p>
  591. <pre class="literal-block">
  592. for value in ffseq(sequence):
  593.     ...do something with value...
  594. </pre>
  595. <p>Single calls to ff(x) translate to ffseq([x])[0] with little
  596. penalty.  Of course this technique is not always appropriate
  597. and there are other variants which you can figure out.</p>
  598. <p>You can gain some performance by explicitly storing the results of
  599. a function or method lookup into a local variable.  A loop like:</p>
  600. <pre class="literal-block">
  601. for key in token:
  602.     dict[key] = dict.get(key, 0) + 1
  603. </pre>
  604. <p>resolves dict.get every iteration.  If the method isn't going to
  605. change, a slightly faster implementation is:</p>
  606. <pre class="literal-block">
  607. dict_get = dict.get  # look up the method once
  608. for key in token:
  609.     dict[key] = dict_get(key, 0) + 1
  610. </pre>
  611. <p>Default arguments can be used to determine values once, at
  612. compile time instead of at run time.  This can only be done for
  613. functions or objects which will not be changed during program
  614. execution, such as replacing</p>
  615. <pre class="literal-block">
  616. def degree_sin(deg):
  617.     return math.sin(deg * math.pi / 180.0)
  618. </pre>
  619. <p>with</p>
  620. <pre class="literal-block">
  621. def degree_sin(deg, factor = math.pi/180.0, sin = math.sin):
  622.     return sin(deg * factor)
  623. </pre>
  624. <p>Because this trick uses default arguments for terms which should
  625. not be changed, it should only be used when you are not concerned
  626. with presenting a possibly confusing API to your users.</p>
  627. </div>
  628. </div>
  629. <div class="section" id="core-language">
  630. <h1><a class="toc-backref" href="#id7">2   Core Language</a></h1>
  631. <div class="section" id="how-do-you-set-a-global-variable-in-a-function">
  632. <h2><a class="toc-backref" href="#id8">2.1   How do you set a global variable in a function?</a></h2>
  633. <p>Did you do something like this?</p>
  634. <pre class="literal-block">
  635. x = 1 # make a global
  636.  
  637. def f():
  638.       print x # try to print the global
  639.       ...
  640.       for j in range(100):
  641.            if q>3:
  642.               x=4
  643. </pre>
  644. <p>Any variable assigned in a function is local to that function.
  645. unless it is specifically declared global. Since a value is bound
  646. to <tt class="docutils literal"><span class="pre">x</span></tt> as the last statement of the function body, the compiler
  647. assumes that <tt class="docutils literal"><span class="pre">x</span></tt> is local. Consequently the <tt class="docutils literal"><span class="pre">print</span> <span class="pre">x</span></tt>
  648. attempts to print an uninitialized local variable and will
  649. trigger a <tt class="docutils literal"><span class="pre">NameError</span></tt>.</p>
  650. <p>The solution is to insert an explicit global declaration at the start
  651. of the function:</p>
  652. <pre class="literal-block">
  653. def f():
  654.       global x
  655.       print x # try to print the global
  656.       ...
  657.       for j in range(100):
  658.            if q>3:
  659.               x=4
  660. </pre>
  661. <p>In this case, all references to <tt class="docutils literal"><span class="pre">x</span></tt> are interpreted as references
  662. to the <tt class="docutils literal"><span class="pre">x</span></tt> from the module namespace.</p>
  663. </div>
  664. <div class="section" id="what-are-the-rules-for-local-and-global-variables-in-python">
  665. <h2><a class="toc-backref" href="#id9">2.2   What are the rules for local and global variables in Python?</a></h2>
  666. <p>In Python, variables that are only referenced inside a function are
  667. implicitly global.  If a variable is assigned a new value anywhere
  668. within the function's body, it's assumed to be a local.  If a variable
  669. is ever assigned a new value inside the function, the variable is
  670. implicitly local, and you need to explicitly declare it as 'global'.</p>
  671. <p>Though a bit surprising at first, a moment's consideration explains
  672. this.  On one hand, requiring <tt class="docutils literal"><span class="pre">global</span></tt> for assigned variables provides
  673. a bar against unintended side-effects.  On the other hand, if <tt class="docutils literal"><span class="pre">global</span></tt>
  674. was required for all global references, you'd be using <tt class="docutils literal"><span class="pre">global</span></tt> all the
  675. time.  You'd have to declare as global every reference to a
  676. builtin function or to a component of an imported module.  This
  677. clutter would defeat the usefulness of the <tt class="docutils literal"><span class="pre">global</span></tt> declaration for
  678. identifying side-effects.</p>
  679. </div>
  680. <div class="section" id="how-do-i-share-global-variables-across-modules">
  681. <h2><a class="toc-backref" href="#id10">2.3   How do I share global variables across modules?</a></h2>
  682. <p>The canonical way to share information across modules within a single
  683. program is to create a special module (often called config or cfg).
  684. Just import the config module in all modules of your application; the
  685. module then becomes available as a global name.  Because there is only
  686. one instance of each module, any changes made to the module object get
  687. reflected everywhere.  For example:</p>
  688. <p>config.py:</p>
  689. <pre class="literal-block">
  690. x = 0   # Default value of the 'x' configuration setting
  691. </pre>
  692. <p>mod.py:</p>
  693. <pre class="literal-block">
  694. import config
  695. config.x = 1
  696. </pre>
  697. <p>main.py:</p>
  698. <pre class="literal-block">
  699. import config
  700. import mod
  701. print config.x
  702. </pre>
  703. <p>Note that using a module is also the basis for implementing the
  704. Singleton design pattern, for the same reason.</p>
  705. </div>
  706. <div class="section" id="what-are-the-best-practices-for-using-import-in-a-module">
  707. <h2><a class="toc-backref" href="#id11">2.4   What are the "best practices" for using import in a module?</a></h2>
  708. <p>In general, don't use <tt class="docutils literal"><span class="pre">from</span> <span class="pre">modulename</span> <span class="pre">import</span> <span class="pre">*</span></tt>.
  709. Doing so clutters the importer's namespace.  Some people avoid this idiom
  710. even with the few modules that were designed to be imported in this
  711. manner.  Modules designed in this manner include <tt class="docutils literal"><span class="pre">Tkinter</span></tt>,
  712. and <tt class="docutils literal"><span class="pre">threading</span></tt>.</p>
  713. <p>Import modules at the top of a file.  Doing so makes it clear what
  714. other modules your code requires and avoids questions of whether the
  715. module name is in scope.  Using one import per line makes it easy to
  716. add and delete module imports, but using multiple imports per line
  717. uses less screen space.</p>
  718. <p>It's good practice if you import modules in the following order:</p>
  719. <ol class="arabic simple">
  720. <li>standard libary modules -- e.g. <tt class="docutils literal"><span class="pre">sys</span></tt>, <tt class="docutils literal"><span class="pre">os</span></tt>, <tt class="docutils literal"><span class="pre">getopt</span></tt>, <tt class="docutils literal"><span class="pre">re</span></tt>)</li>
  721. <li>third-party library modules (anything installed in Python's
  722. site-packages directory) -- e.g. mx.DateTime, ZODB, PIL.Image, etc.</li>
  723. <li>locally-developed modules</li>
  724. </ol>
  725. <p>Never use relative package imports.  If you're writing code that's
  726. in the <tt class="docutils literal"><span class="pre">package.sub.m1</span></tt> module and want to import <tt class="docutils literal"><span class="pre">package.sub.m2</span></tt>,
  727. do not just write <tt class="docutils literal"><span class="pre">import</span> <span class="pre">m2</span></tt>, even though it's legal.
  728. Write <tt class="docutils literal"><span class="pre">from</span> <span class="pre">package.sub</span> <span class="pre">import</span> <span class="pre">m2</span></tt> instead.  Relative imports can lead to a
  729. module being initialized twice, leading to confusing bugs.</p>
  730. <p>It is sometimes necessary to move imports to a function or class to
  731. avoid problems with circular imports.  Gordon McMillan says:</p>
  732. <blockquote>
  733. Circular imports are fine where both modules use the "import <module>"
  734. form of import. They fail when the 2nd module wants to grab a name
  735. out of the first ("from module import name") and the import is at
  736. the top level. That's because names in the 1st are not yet available,
  737. because the first module is busy importing the 2nd.</blockquote>
  738. <p>In this case, if the second module is only used in one function, then the
  739. import can easily be moved into that function.  By the time the import
  740. is called, the first module will have finished initializing, and the
  741. second module can do its import.</p>
  742. <p>It may also be necessary to move imports out of the top level of code
  743. if some of the modules are platform-specific.  In that case, it may
  744. not even be possible to import all of the modules at the top of the
  745. file.  In this case, importing the correct modules in the
  746. corresponding platform-specific code is a good option.</p>
  747. <p>Only move imports into a local scope, such as inside a function
  748. definition, if it's necessary to solve a problem such as avoiding a
  749. circular import or are trying to reduce the initialization time of a
  750. module.  This technique is especially helpful if many of the imports
  751. are unnecessary depending on how the program executes.  You may also
  752. want to move imports into a function if the modules are only ever used
  753. in that function.  Note that loading a module the first time may be
  754. expensive because of the one time initialization of the module, but
  755. loading a module multiple times is virtually free, costing only a couple of
  756. dictionary lookups.  Even if the module name has gone out of scope,
  757. the module is probably available in sys.modules.</p>
  758. <p>If only instances of a specific class use a module, then it is
  759. reasonable to import the module in the class's <tt class="docutils literal"><span class="pre">__init__</span></tt> method and
  760. then assign the module to an instance variable so that the module is
  761. always available (via that instance variable) during the life of the
  762. object.  Note that to delay an import until the class is instantiated,
  763. the import must be inside a method.  Putting the import inside the
  764. class but outside of any method still causes the import to occur when
  765. the module is initialized.</p>
  766. </div>
  767. <div class="section" id="how-can-i-pass-optional-or-keyword-parameters-from-one-function-to-another">
  768. <h2><a class="toc-backref" href="#id12">2.5   How can I pass optional or keyword parameters from one function to another?</a></h2>
  769. <p>Collect the arguments using the <tt class="docutils literal"><span class="pre">*</span></tt> and <tt class="docutils literal"><span class="pre">**</span></tt> specifiers in the function's
  770. parameter list; this gives you the positional arguments as a tuple
  771. and the keyword arguments as a dictionary.   You can
  772. then pass these arguments when calling another function by using
  773. <tt class="docutils literal"><span class="pre">*</span></tt> and <tt class="docutils literal"><span class="pre">**</span></tt>:</p>
  774. <pre class="literal-block">
  775. def f(x, *tup, **kwargs):
  776.         ...
  777.         kwargs['width']='14.3c'
  778.         ...
  779.         g(x, *tup, **kwargs)
  780. </pre>
  781. <p>In the unlikely case that you care about Python
  782. versions older than 2.0, use 'apply':</p>
  783. <pre class="literal-block">
  784. def f(x, *tup, **kwargs):
  785.         ...
  786.         kwargs['width']='14.3c'
  787.         ...
  788.         apply(g, (x,)+tup, kwargs)
  789. </pre>
  790. </div>
  791. <div class="section" id="how-do-i-write-a-function-with-output-parameters-call-by-reference">
  792. <h2><a class="toc-backref" href="#id13">2.6   How do I write a function with output parameters (call by reference)?</a></h2>
  793. <p>Remember that arguments are passed by assignment in Python.  Since
  794. assignment just creates references to objects, there's no alias
  795. between an argument name in the caller and callee, and so no
  796. call-by-reference per se.  You can achieve the desired effect in a
  797. number of ways.</p>
  798. <ol class="arabic">
  799. <li><p class="first">By returning a tuple of the results:</p>
  800. <pre class="literal-block">
  801. def func2(a, b):
  802.     a = 'new-value'        # a and b are local names
  803.     b = b + 1              # assigned to new objects
  804.     return a, b            # return new values
  805.  
  806. x, y = 'old-value', 99
  807. x, y = func2(x, y)
  808. print x, y                 # output: new-value 100
  809. </pre>
  810. <p>This is almost always the clearest solution.</p>
  811. </li>
  812. <li><p class="first">By using global variables.  This isn't thread-safe, and is not
  813. recommended.</p>
  814. </li>
  815. <li><p class="first">By passing a mutable (changeable in-place) object:</p>
  816. <pre class="literal-block">
  817. def func1(a):
  818.     a[0] = 'new-value'     # 'a' references a mutable list
  819.     a[1] = a[1] + 1        # changes a shared object
  820.  
  821. args = ['old-value', 99]
  822. func1(args)
  823. print args[0], args[1]     # output: new-value 100
  824. </pre>
  825. </li>
  826. <li><p class="first">By passing in a dictionary that gets mutated:</p>
  827. <pre class="literal-block">
  828. def func3(args):
  829.     args['a'] = 'new-value'     # args is a mutable dictionary
  830.     args['b'] = args['b'] + 1   # change it in-place
  831.  
  832. args = {'a':' old-value', 'b': 99}
  833. func3(args)
  834. print args['a'], args['b']
  835. </pre>
  836. </li>
  837. <li><p class="first">Or bundle up values in a class instance:</p>
  838. <pre class="literal-block">
  839. class callByRef:
  840.     def __init__(self, **args):
  841.         for (key, value) in args.items():
  842.             setattr(self, key, value)
  843.  
  844. def func4(args):
  845.     args.a = 'new-value'        # args is a mutable callByRef
  846.     args.b = args.b + 1         # change object in-place
  847.  
  848. args = callByRef(a='old-value', b=99)
  849. func4(args)
  850. print args.a, args.b
  851. </pre>
  852. <p>There's almost never a good reason to get this complicated.</p>
  853. </li>
  854. </ol>
  855. <p>Your best choice is to return a tuple containing the multiple results.</p>
  856. </div>
  857. <div class="section" id="how-do-you-make-a-higher-order-function-in-python">
  858. <h2><a class="toc-backref" href="#id14">2.7   How do you make a higher order function in Python?</a></h2>
  859. <p>You have two choices: you can use nested scopes
  860. or you can use callable objects.  For example, suppose you wanted to
  861. define <tt class="docutils literal"><span class="pre">linear(a,b)</span></tt> which returns a function <tt class="docutils literal"><span class="pre">f(x)</span></tt> that computes the
  862. value <tt class="docutils literal"><span class="pre">a*x+b</span></tt>.  Using nested scopes:</p>
  863. <pre class="literal-block">
  864. def linear(a,b):
  865.     def result(x):
  866.         return a*x + b
  867.     return result
  868. </pre>
  869. <p>Or using a callable object:</p>
  870. <pre class="literal-block">
  871. class linear:
  872.    def __init__(self, a, b):
  873.        self.a, self.b = a,b
  874.    def __call__(self, x):
  875.        return self.a * x + self.b
  876. </pre>
  877. <p>In both cases:</p>
  878. <pre class="literal-block">
  879. taxes = linear(0.3,2)
  880. </pre>
  881. <p>gives a callable object where taxes(10e6) == 0.3 * 10e6 + 2.</p>
  882. <p>The callable object approach has the disadvantage that it is a bit
  883. slower and results in slightly longer code.  However, note that a
  884. collection of callables can share their signature via inheritance:</p>
  885. <pre class="literal-block">
  886. class exponential(linear):
  887.    # __init__ inherited
  888.    def __call__(self, x):
  889.        return self.a * (x ** self.b)
  890. </pre>
  891. <p>Object can encapsulate state for several methods:</p>
  892. <pre class="literal-block">
  893. class counter:
  894.     value = 0
  895.     def set(self, x): self.value = x
  896.     def up(self): self.value=self.value+1
  897.     def down(self): self.value=self.value-1
  898.  
  899. count = counter()
  900. inc, dec, reset = count.up, count.down, count.set
  901. </pre>
  902. <p>Here <tt class="docutils literal"><span class="pre">inc()</span></tt>, <tt class="docutils literal"><span class="pre">dec()</span></tt> and <tt class="docutils literal"><span class="pre">reset()</span></tt> act like functions which share the
  903. same counting variable.</p>
  904. </div>
  905. <div class="section" id="how-do-i-copy-an-object-in-python">
  906. <h2><a class="toc-backref" href="#id15">2.8   How do I copy an object in Python?</a></h2>
  907. <p>In general, try copy.copy() or copy.deepcopy() for the general case. Not all
  908. objects can be copied, but most can.</p>
  909. <p>Some objects can be copied more easily.
  910. Dictionaries have a <tt class="docutils literal"><span class="pre">copy()</span></tt> method:</p>
  911. <pre class="literal-block">
  912. newdict = olddict.copy()
  913. </pre>
  914. <p>Sequences can be copied by slicing:</p>
  915. <pre class="literal-block">
  916. new_l = l[:]
  917. </pre>
  918. </div>
  919. <div class="section" id="how-can-i-find-the-methods-or-attributes-of-an-object">
  920. <h2><a class="toc-backref" href="#id16">2.9   How can I find the methods or attributes of an object?</a></h2>
  921. <p>For an instance x of a user-defined class, <tt class="docutils literal"><span class="pre">dir(x)</span></tt> returns an
  922. alphabetized list of the names containing the instance attributes and
  923. methods and attributes defined by its class.</p>
  924. </div>
  925. <div class="section" id="how-can-my-code-discover-the-name-of-an-object">
  926. <h2><a class="toc-backref" href="#id17">2.10   How can my code discover the name of an object?</a></h2>
  927. <p>Generally speaking, it can't, because objects don't really have
  928. names. Essentially, assignment always binds a name to a value; The
  929. same is true of <tt class="docutils literal"><span class="pre">def</span></tt> and <tt class="docutils literal"><span class="pre">class</span></tt> statements, but in that case the
  930. value is a callable. Consider the following code:</p>
  931. <pre class="literal-block">
  932. class A:
  933.     pass
  934.  
  935. B = A
  936.  
  937. a = B()
  938. b = a
  939. print b
  940. <__main__.A instance at 016D07CC>
  941. print a
  942. <__main__.A instance at 016D07CC>
  943. </pre>
  944. <p>Arguably the class has a name: even though it is bound to two names
  945. and invoked through the name B the created instance is still reported
  946. as an instance of class A. However, it is impossible to say whether
  947. the instance's name is a or b, since both names are bound to the same
  948. value.</p>
  949. <p>Generally speaking it should not be necessary for your code to "know
  950. the names" of particular values. Unless you are deliberately writing
  951. introspective programs, this is usually an indication that a change of
  952. approach might be beneficial.</p>
  953. <p>In comp.lang.python, Fredrik Lundh once gave an excellent analogy in
  954. answer to this question:</p>
  955. <blockquote>
  956. <p>The same way as you get the name of that cat you found on your
  957. porch: the cat (object) itself cannot tell you its name, and it
  958. doesn't really care -- so the only way to find out what it's called
  959. is to ask all your neighbours (namespaces) if it's their cat
  960. (object)...</p>
  961. <p>....and don't be surprised if you'll find that it's known by many
  962. names, or no name at all!</p>
  963. </blockquote>
  964. </div>
  965. <div class="section" id="is-there-an-equivalent-of-c-s-ternary-operator">
  966. <h2><a class="toc-backref" href="#id18">2.11   Is there an equivalent of C's "?:" ternary operator?</a></h2>
  967. <p>No.  In many cases you can mimic a?b:c with "a and b or
  968. c", but there's a flaw: if b is zero (or empty, or None -- anything
  969. that tests false) then c will be selected instead.  In many cases you
  970. can prove by looking at the code that this can't happen (e.g. because
  971. b is a constant or has a type that can never be false), but in general
  972. this can be a problem.</p>
  973. <p>Tim Peters (who wishes it was Steve Majewski) suggested the following
  974. solution: (a and [b] or [c])[0].  Because [b] is a singleton list it
  975. is never false, so the wrong path is never taken; then applying [0] to
  976. the whole thing gets the b or c that you really wanted.  Ugly, but it
  977. gets you there in the rare cases where it is really inconvenient to
  978. rewrite your code using 'if'.</p>
  979. <p>The best course is usually to write a simple <tt class="docutils literal"><span class="pre">if...else</span></tt> statement.
  980. Another solution is to implement the "?:" operator as a function:</p>
  981. <pre class="literal-block">
  982. def q(cond,on_true,on_false):
  983.     if cond:
  984.         if not isfunction(on_true): return on_true
  985.         else: return apply(on_true)
  986.     else:
  987.         if not isfunction(on_false): return on_false
  988.         else: return apply(on_false)
  989. </pre>
  990. <p>In most cases you'll pass b and c directly: <tt class="docutils literal"><span class="pre">q(a,b,c)</span></tt>.  To avoid
  991. evaluating b or c when they shouldn't be, encapsulate them within a
  992. lambda function, e.g.: <tt class="docutils literal"><span class="pre">q(a,lambda:</span> <span class="pre">b,</span> <span class="pre">lambda:</span> <span class="pre">c)</span></tt>.</p>
  993. <p>It has been asked <em>why</em> Python has no if-then-else expression.
  994. There are several answers: many languages do
  995. just fine without one; it can easily lead to less readable code;
  996. no sufficiently "Pythonic" syntax has been discovered; a search
  997. of the standard library found remarkably few places where using an
  998. if-then-else expression would make the code more understandable.</p>
  999. <p>In 2002, <a class="reference external" href="../../peps/pep-0308.html">PEP 308</a> was
  1000. written proposing several possible syntaxes and the community was
  1001. asked to vote on the issue.  The vote was inconclusive.  Most people
  1002. liked one of the syntaxes, but also hated other syntaxes; many votes
  1003. implied that people preferred no ternary operator
  1004. rather than having a syntax they hated.</p>
  1005. </div>
  1006. <div class="section" id="is-it-possible-to-write-obfuscated-one-liners-in-python">
  1007. <h2><a class="toc-backref" href="#id19">2.12   Is it possible to write obfuscated one-liners in Python?</a></h2>
  1008. <p>Yes.  Usually this is done by nesting <cite>lambda</cite> within <cite>lambda</cite>.
  1009. See the following three examples, due to Ulf Bartelt:</p>
  1010. <pre class="literal-block">
  1011. # Primes < 1000
  1012. print filter(None,map(lambda y:y*reduce(lambda x,y:x*y!=0,
  1013. map(lambda x,y=y:y%x,range(2,int(pow(y,0.5)+1))),1),range(2,1000)))
  1014.  
  1015. # First 10 Fibonacci numbers
  1016. print map(lambda x,f=lambda x,f:(x<=1) or (f(x-1,f)+f(x-2,f)): f(x,f),
  1017. range(10))
  1018.  
  1019. # Mandelbrot set
  1020. print (lambda Ru,Ro,Iu,Io,IM,Sx,Sy:reduce(lambda x,y:x+y,map(lambda y,
  1021. Iu=Iu,Io=Io,Ru=Ru,Ro=Ro,Sy=Sy,L=lambda yc,Iu=Iu,Io=Io,Ru=Ru,Ro=Ro,i=IM,
  1022. Sx=Sx,Sy=Sy:reduce(lambda x,y:x+y,map(lambda x,xc=Ru,yc=yc,Ru=Ru,Ro=Ro,
  1023. i=i,Sx=Sx,F=lambda xc,yc,x,y,k,f=lambda xc,yc,x,y,k,f:(k<=0)or (x*x+y*y
  1024. >=4.0) or 1+f(xc,yc,x*x-y*y+xc,2.0*x*y+yc,k-1,f):f(xc,yc,x,y,k,f):chr(
  1025. 64+F(Ru+x*(Ro-Ru)/Sx,yc,0,0,i)),range(Sx))):L(Iu+y*(Io-Iu)/Sy),range(Sy
  1026. ))))(-2.1, 0.7, -1.2, 1.2, 30, 80, 24)
  1027. #    \___ ___  \___ ___  |   |   |__ lines on screen
  1028. #        V          V      |   |______ columns on screen
  1029. #        |          |      |__________ maximum of "iterations"
  1030. #        |          |_________________ range on y axis
  1031. #        |____________________________ range on x axis
  1032. </pre>
  1033. <p>Don't try this at home, kids!</p>
  1034. </div>
  1035. </div>
  1036. <div class="section" id="numbers-and-strings">
  1037. <h1><a class="toc-backref" href="#id20">3   Numbers and strings</a></h1>
  1038. <div class="section" id="how-do-i-specify-hexadecimal-and-octal-integers">
  1039. <h2><a class="toc-backref" href="#id21">3.1   How do I specify hexadecimal and octal integers?</a></h2>
  1040. <p>To specify an octal digit, precede the octal value with a zero.  For
  1041. example, to set the variable "a" to the octal value "10" (8 in
  1042. decimal), type:</p>
  1043. <pre class="literal-block">
  1044. >>> a = 010
  1045. >>> a
  1046. 8
  1047. </pre>
  1048. <p>Hexadecimal is just as easy.  Simply precede the hexadecimal number with a
  1049. zero, and then a lower or uppercase "x".  Hexadecimal digits can be specified
  1050. in lower or uppercase.  For example, in the Python interpreter:</p>
  1051. <pre class="literal-block">
  1052. >>> a = 0xa5
  1053. >>> a
  1054. 165
  1055. >>> b = 0XB2
  1056. >>> b
  1057. 178
  1058. </pre>
  1059. </div>
  1060. <div class="section" id="why-does-22-10-return-3">
  1061. <h2><a class="toc-backref" href="#id22">3.2   Why does -22 / 10 return -3?</a></h2>
  1062. <p>It's primarily driven by the desire that <tt class="docutils literal"><span class="pre">i%j</span></tt> have the same sign as
  1063. <tt class="docutils literal"><span class="pre">j</span></tt>.  If you want that, and also want:</p>
  1064. <pre class="literal-block">
  1065. i == (i/j)*j + (i%j)
  1066. </pre>
  1067. <p>then integer division has to return the floor.  C also requres that identity
  1068. to hold, and then compilers that truncate <tt class="docutils literal"><span class="pre">i/j</span></tt> need to make <tt class="docutils literal"><span class="pre">i%j</span></tt> have
  1069. the same sign as <tt class="docutils literal"><span class="pre">i</span></tt>.</p>
  1070. <p>There are few real use cases for <tt class="docutils literal"><span class="pre">i%j</span></tt> when <tt class="docutils literal"><span class="pre">j</span></tt> is negative.  When <tt class="docutils literal"><span class="pre">j</span></tt>
  1071. is positive, there are many, and in virtually all of them it's more useful
  1072. for <tt class="docutils literal"><span class="pre">i%j</span></tt> to be <tt class="docutils literal"><span class="pre">>=</span> <span class="pre">0</span></tt>.  If the clock says 10 now, what did it say 200
  1073. hours ago?  <tt class="docutils literal"><span class="pre">-190</span> <span class="pre">%</span> <span class="pre">12</span> <span class="pre">==</span> <span class="pre">2</span></tt> is useful; <tt class="docutils literal"><span class="pre">-190</span> <span class="pre">%</span> <span class="pre">12</span> <span class="pre">==</span> <span class="pre">-10</span></tt> is a bug
  1074. waiting to bite.</p>
  1075. </div>
  1076. <div class="section" id="how-do-i-convert-a-string-to-a-number">
  1077. <h2><a class="toc-backref" href="#id23">3.3   How do I convert a string to a number?</a></h2>
  1078. <p>For integers, use the built-in <tt class="docutils literal"><span class="pre">int()</span></tt> type constructor,
  1079. e.g. int('144') == 144.  Similarly, <tt class="docutils literal"><span class="pre">float()</span></tt> converts to
  1080. floating-point, e.g. <tt class="docutils literal"><span class="pre">float('144')</span> <span class="pre">==</span> <span class="pre">144.0</span></tt>.</p>
  1081. <p>By default, these interpret the number as decimal, so that
  1082. <tt class="docutils literal"><span class="pre">int('0144')</span> <span class="pre">==</span> <span class="pre">144</span></tt> and <tt class="docutils literal"><span class="pre">int('0x144')</span></tt> raises
  1083. <tt class="docutils literal"><span class="pre">ValueError</span></tt>. <tt class="docutils literal"><span class="pre">int(string,</span> <span class="pre">base)</span></tt> takes the base to convert from
  1084. as a second optional argument, so <tt class="docutils literal"><span class="pre">int('0x144',</span> <span class="pre">16)</span> <span class="pre">==</span> <span class="pre">324</span></tt>.  If the
  1085. base is specified as 0, the number is interpreted using Python's
  1086. rules: a leading '0' indicates octal, and '0x' indicates a hex number.</p>
  1087. <p>Do not use the built-in function <tt class="docutils literal"><span class="pre">eval()</span></tt> if all you need is to
  1088. convert strings to numbers.  <tt class="docutils literal"><span class="pre">eval()</span></tt> will be significantly slower
  1089. and it presents a security risk: someone could pass you a Python
  1090. expression that might have unwanted side effects.  For example,
  1091. someone could pass <tt class="docutils literal"><span class="pre">__import__('os').system("rm</span> <span class="pre">-rf</span> <span class="pre">$HOME")</span></tt> which
  1092. would erase your home directory.</p>
  1093. <p><tt class="docutils literal"><span class="pre">eval()</span></tt> also has the effect of interpreting numbers as Python
  1094. expressions, so that e.g. eval('09') gives a syntax error because Python
  1095. regards numbers starting with '0' as octal (base 8).</p>
  1096. </div>
  1097. <div class="section" id="how-do-i-convert-a-number-to-a-string">
  1098. <h2><a class="toc-backref" href="#id24">3.4   How do I convert a number to a string?</a></h2>
  1099. <p>To convert, e.g., the number 144 to the string '144', use the built-in
  1100. function <tt class="docutils literal"><span class="pre">str()</span></tt>.  If you want a hexadecimal or octal
  1101. representation, use the built-in functions <tt class="docutils literal"><span class="pre">hex()</span></tt> or <tt class="docutils literal"><span class="pre">oct()</span></tt>.
  1102. For fancy formatting, use <a class="reference external" href="../../doc/lib/typesseq-strings.html">the % operator</a> on strings, e.g. <tt class="docutils literal"><span class="pre">"%04d"</span> <span class="pre">%</span> <span class="pre">144</span></tt>
  1103. yields '0144' and <tt class="docutils literal"><span class="pre">"%.3f"</span> <span class="pre">%</span> <span class="pre">(1/3.0)</span></tt> yields '0.333'.  See the library
  1104. reference manual for details.</p>
  1105. </div>
  1106. <div class="section" id="how-do-i-modify-a-string-in-place">
  1107. <h2><a class="toc-backref" href="#id25">3.5   How do I modify a string in place?</a></h2>
  1108. <p>You can't, because strings are immutable.  If you need an object with
  1109. this ability, try converting the string to a list or use the array
  1110. module:</p>
  1111. <pre class="literal-block">
  1112. >>> s = "Hello, world"
  1113. >>> a = list(s)
  1114. >>> print a
  1115. ['H', 'e', 'l', 'l', 'o', ',', ' ', 'w', 'o', 'r', 'l', 'd']
  1116. >>> a[7:] = list("there!")
  1117. >>> ''.join(a)
  1118. 'Hello, there!'
  1119.  
  1120. >>> import array
  1121. >>> a = array.array('c', s)
  1122. >>> print a
  1123. array('c', 'Hello, world')
  1124. >>> a[0] = 'y' ; print a
  1125. array('c', 'yello world')
  1126. >>> a.tostring()
  1127. 'yello, world'
  1128. </pre>
  1129. </div>
  1130. <div class="section" id="how-do-i-use-strings-to-call-functions-methods">
  1131. <h2><a class="toc-backref" href="#id26">3.6   How do I use strings to call functions/methods?</a></h2>
  1132. <p>There are various techniques.</p>
  1133. <ul>
  1134. <li><p class="first">The best is to use a dictionary that maps strings to functions.  The
  1135. primary advantage of this technique is that the strings do not need
  1136. to match the names of the functions.  This is also the primary
  1137. technique used to emulate a case construct:</p>
  1138. <pre class="literal-block">
  1139. def a():
  1140.     pass
  1141.  
  1142. def b():
  1143.     pass
  1144.  
  1145. dispatch = {'go': a, 'stop': b}  # Note lack of parens for funcs
  1146.  
  1147. dispatch[get_input()]()  # Note trailing parens to call function
  1148. </pre>
  1149. </li>
  1150. <li><p class="first">Use the built-in function <tt class="docutils literal"><span class="pre">getattr()</span></tt>:</p>
  1151. <pre class="literal-block">
  1152. import foo
  1153. getattr(foo, 'bar')()
  1154. </pre>
  1155. <p>Note that getattr() works on any object, including classes, class
  1156. instances, modules, and so on.</p>
  1157. <p>This is used in several places in the standard library, like
  1158. this:</p>
  1159. <pre class="literal-block">
  1160. class Foo:
  1161.     def do_foo(self):
  1162.         ...
  1163.  
  1164.     def do_bar(self):
  1165.         ...
  1166.  
  1167.  f = getattr(foo_instance, 'do_' + opname)
  1168.  f()
  1169. </pre>
  1170. </li>
  1171. <li><p class="first">Use <tt class="docutils literal"><span class="pre">locals()</span></tt> or <tt class="docutils literal"><span class="pre">eval()</span></tt> to resolve the function name:</p>
  1172. <pre class="literal-block">
  1173. def myFunc():
  1174.     print "hello"
  1175.  
  1176. fname = "myFunc"
  1177.  
  1178. f = locals()[fname]
  1179. f()
  1180.  
  1181. f = eval(fname)
  1182. f()
  1183. </pre>
  1184. <p>Note: Using <tt class="docutils literal"><span class="pre">eval()</span></tt> is slow and dangerous. If you don't have absolute control
  1185. over the contents of the string, someone could pass a string that
  1186. resulted in an arbitrary function being executed.</p>
  1187. </li>
  1188. </ul>
  1189. </div>
  1190. <div class="section" id="is-there-an-equivalent-to-perl-s-chomp-for-removing-trailing-newlines-from-strings">
  1191. <h2><a class="toc-backref" href="#id27">3.7   Is there an equivalent to Perl's chomp() for removing trailing newlines from strings?</a></h2>
  1192. <p>Starting with Python 2.2, you can use <tt class="docutils literal"><span class="pre">S.rstrip("\r\n")</span></tt> to remove
  1193. all occurances of any line terminator from the end of the string <tt class="docutils literal"><span class="pre">S</span></tt>
  1194. without removing other trailing whitespace.  If the string <tt class="docutils literal"><span class="pre">S</span></tt>
  1195. represents more than one line, with several empty lines at the end,
  1196. the line terminators for all the blank lines will be removed:</p>
  1197. <pre class="literal-block">
  1198. >>> lines = ("line 1 \r\n"
  1199. ...          "\r\n"
  1200. ...          "\r\n")
  1201. >>> lines.rstrip("\n\r")
  1202. "line 1 "
  1203. </pre>
  1204. <p>Since this is typically only desired when reading text one line at a
  1205. time, using <tt class="docutils literal"><span class="pre">S.rstrip()</span></tt> this way works well.</p>
  1206. <p>For older versions of Python, There are two partial substitutes:</p>
  1207. <ul class="simple">
  1208. <li>If you want to remove all trailing whitespace, use the <tt class="docutils literal"><span class="pre">rstrip()</span></tt>
  1209. method of string objects.  This removes all trailing whitespace, not
  1210. just a single newline.</li>
  1211. <li>Otherwise, if there is only one line in the string <tt class="docutils literal"><span class="pre">S</span></tt>, use
  1212. <tt class="docutils literal"><span class="pre">S.splitlines()[0]</span></tt>.</li>
  1213. </ul>
  1214. </div>
  1215. <div class="section" id="is-there-a-scanf-or-sscanf-equivalent">
  1216. <h2><a class="toc-backref" href="#id28">3.8   Is there a scanf() or sscanf() equivalent?</a></h2>
  1217. <p>Not as such.</p>
  1218. <p>For simple input parsing, the easiest approach is usually to split the
  1219. line into whitespace-delimited words using the <tt class="docutils literal"><span class="pre">split()</span></tt> method of
  1220. string objects and then convert decimal strings to numeric values using
  1221. <tt class="docutils literal"><span class="pre">int()</span></tt> or <tt class="docutils literal"><span class="pre">float()</span></tt>.  <tt class="docutils literal"><span class="pre">split()</span></tt> supports an optional "sep"
  1222. parameter which is useful if the line uses something other than
  1223. whitespace as a separator.</p>
  1224. <p>For more complicated input parsing, regular expressions
  1225. more powerful than C's <tt class="docutils literal"><span class="pre">sscanf()</span></tt> and better suited for the task.</p>
  1226. </div>
  1227. <div class="section" id="what-does-unicodeerror-ascii-decoding-encoding-error-ordinal-not-in-range-128-mean">
  1228. <h2><a class="toc-backref" href="#id29">3.9   What does 'UnicodeError: ASCII [decoding,encoding] error: ordinal not in range(128)' mean?</a></h2>
  1229. <p>This error indicates that your Python installation can handle
  1230. only 7-bit ASCII strings.  There are a couple ways to fix or
  1231. work around the problem.</p>
  1232. <p>If your programs must handle data in arbitary character set encodings,
  1233. the environment the application runs in will generally identify the
  1234. encoding of the data it is handing you.  You need to convert the input
  1235. to Unicode data using that encoding.  For example, a program that
  1236. handles email or web input will typically find character set encoding
  1237. information in Content-Type headers.  This can then be used to
  1238. properly convert input data to Unicode. Assuming the string referred
  1239. to by <tt class="docutils literal"><span class="pre">value</span></tt> is encoded as UTF-8:</p>
  1240. <pre class="literal-block">
  1241. value = unicode(value, "utf-8")
  1242. </pre>
  1243. <p>will return a Unicode object.  If the data is not correctly encoded as
  1244. UTF-8, the above call will raise a <tt class="docutils literal"><span class="pre">UnicodeError</span></tt> exception.</p>
  1245. <p>If you only want strings coverted to Unicode which have non-ASCII
  1246. data, you can try converting them first assuming an ASCII encoding,
  1247. and then generate Unicode objects if that fails:</p>
  1248. <pre class="literal-block">
  1249. try:
  1250.     x = unicode(value, "ascii")
  1251. except UnicodeError:
  1252.     value = unicode(value, "utf-8")
  1253. else:
  1254.     # value was valid ASCII data
  1255.     pass
  1256. </pre>
  1257. <p>It's possible to set a default encoding in a file called <tt class="docutils literal"><span class="pre">sitecustomize.py</span></tt>
  1258. that's part of the Python library.  However, this isn't recommended because changing the Python-wide default encoding may cause third-party extension modules to fail.</p>
  1259. <p>Note that on Windows, there is an encoding known as "mbcs", which uses
  1260. an encoding specific to your current locale.  In many cases, and
  1261. particularly when working with COM, this may be an appropriate default
  1262. encoding to use.</p>
  1263. </div>
  1264. </div>
  1265. <div class="section" id="sequences-tuples-lists">
  1266. <h1><a class="toc-backref" href="#id30">4   Sequences (Tuples/Lists)</a></h1>
  1267. <div class="section" id="how-do-i-convert-between-tuples-and-lists">
  1268. <h2><a class="toc-backref" href="#id31">4.1   How do I convert between tuples and lists?</a></h2>
  1269. <p>The function <tt class="docutils literal"><span class="pre">tuple(seq)</span></tt> converts any sequence (actually, any
  1270. iterable) into a tuple with the same items in the same order.</p>
  1271. <p>For example, <tt class="docutils literal"><span class="pre">tuple([1,</span> <span class="pre">2,</span> <span class="pre">3])</span></tt> yields <tt class="docutils literal"><span class="pre">(1,</span> <span class="pre">2,</span> <span class="pre">3)</span></tt> and <tt class="docutils literal"><span class="pre">tuple('abc')</span></tt>
  1272. yields <tt class="docutils literal"><span class="pre">('a',</span> <span class="pre">'b',</span> <span class="pre">'c')</span></tt>.  If the argument is
  1273. a tuple, it does not make a copy but returns the same object, so
  1274. it is cheap to call <tt class="docutils literal"><span class="pre">tuple()</span></tt> when you aren't sure that an object
  1275. is already a tuple.</p>
  1276. <p>The function <tt class="docutils literal"><span class="pre">list(seq)</span></tt> converts any sequence or iterable into a list with
  1277. the same items in the same order.
  1278. For example, <tt class="docutils literal"><span class="pre">list((1,</span> <span class="pre">2,</span> <span class="pre">3))</span></tt> yields <tt class="docutils literal"><span class="pre">[1,</span> <span class="pre">2,</span> <span class="pre">3]</span></tt> and <tt class="docutils literal"><span class="pre">list('abc')</span></tt>
  1279. yields <tt class="docutils literal"><span class="pre">['a',</span> <span class="pre">'b',</span> <span class="pre">'c']</span></tt>.  If the argument is a list,
  1280. it makes a copy just like <tt class="docutils literal"><span class="pre">seq[:]</span></tt> would.</p>
  1281. </div>
  1282. <div class="section" id="what-s-a-negative-index">
  1283. <h2><a class="toc-backref" href="#id32">4.2   What's a negative index?</a></h2>
  1284. <p>Python sequences are indexed with positive numbers and
  1285. negative numbers.  For positive numbers 0 is the first index
  1286. 1 is the second index and so forth.  For negative indices -1
  1287. is the last index and -2 is the pentultimate (next to last) index
  1288. and so forth.  Think of <tt class="docutils literal"><span class="pre">seq[-n]</span></tt> as the same as <tt class="docutils literal"><span class="pre">seq[len(seq)-n]</span></tt>.</p>
  1289. <p>Using negative indices can be very convenient.  For example <tt class="docutils literal"><span class="pre">S[:-1]</span></tt>
  1290. is all of the string except for its last character, which is useful
  1291. for removing the trailing newline from a string.</p>
  1292. </div>
  1293. <div class="section" id="how-do-i-iterate-over-a-sequence-in-reverse-order">
  1294. <h2><a class="toc-backref" href="#id33">4.3   How do I iterate over a sequence in reverse order?</a></h2>
  1295. <p>If it is a list, the fastest solution is</p>
  1296. <pre class="literal-block">
  1297. list.reverse()
  1298. try:
  1299.     for x in list:
  1300.         "do something with x"
  1301. finally:
  1302.     list.reverse()
  1303. </pre>
  1304. <p>This has the disadvantage that while you are in the loop, the list
  1305. is temporarily reversed.  If you don't like this, you can make a copy.
  1306. This appears expensive but is actually faster than other solutions:</p>
  1307. <pre class="literal-block">
  1308. rev = list[:]
  1309. rev.reverse()
  1310. for x in rev:
  1311.         <do something with x>
  1312. </pre>
  1313. <p>If it's not a list, a more general but slower solution is:</p>
  1314. <pre class="literal-block">
  1315. for i in range(len(sequence)-1, -1, -1):
  1316.         x = sequence[i]
  1317.         <do something with x>
  1318. </pre>
  1319. <p>A more elegant solution, is to define a class which acts as a sequence
  1320. and yields the elements in reverse order (solution due to Steve
  1321. Majewski):</p>
  1322. <pre class="literal-block">
  1323. class Rev:
  1324.         def __init__(self, seq):
  1325.                 self.forw = seq
  1326.         def __len__(self):
  1327.                 return len(self.forw)
  1328.         def __getitem__(self, i):
  1329.                 return self.forw[-(i + 1)]
  1330. </pre>
  1331. <p>You can now simply write:</p>
  1332. <pre class="literal-block">
  1333. for x in Rev(list):
  1334.         <do something with x>
  1335. </pre>
  1336. <p>Unfortunately, this solution is slowest of all, due to the method
  1337. call overhead.</p>
  1338. <p>With Python 2.3, you can use an extended slice syntax:</p>
  1339. <pre class="literal-block">
  1340. for x in sequence[::-1]:
  1341.        <do something with x>
  1342. </pre>
  1343. </div>
  1344. <div class="section" id="how-do-you-remove-duplicates-from-a-list">
  1345. <h2><a class="toc-backref" href="#id34">4.4   How do you remove duplicates from a list?</a></h2>
  1346. <p>See the Python Cookbook for a long discussion of many ways to do this:</p>
  1347. <blockquote>
  1348. <a class="reference external" href="http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52560">http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52560</a></blockquote>
  1349. <p>If you don't mind reordering the list, sort it and then scan from the
  1350. end of the list, deleting duplicates as you go:</p>
  1351. <pre class="literal-block">
  1352. if List:
  1353.    List.sort()
  1354.    last = List[-1]
  1355.    for i in range(len(List)-2, -1, -1):
  1356.        if last==List[i]: del List[i]
  1357.        else: last=List[i]
  1358. </pre>
  1359. <p>If all elements of the list may be used as
  1360. dictionary keys (i.e. they are all hashable)
  1361. this is often faster</p>
  1362. <pre class="literal-block">
  1363. d = {}
  1364. for x in List: d[x]=x
  1365. List = d.values()
  1366. </pre>
  1367. </div>
  1368. <div class="section" id="how-do-you-make-an-array-in-python">
  1369. <h2><a class="toc-backref" href="#id35">4.5   How do you make an array in Python?</a></h2>
  1370. <p>Use a list:</p>
  1371. <pre class="literal-block">
  1372. ["this", 1, "is", "an", "array"]
  1373. </pre>
  1374. <p>Lists are equivalent to C or Pascal arrays in their time complexity;
  1375. the primary difference is that a Python list can contain objects of
  1376. many different types.</p>
  1377. <p>The <tt class="docutils literal"><span class="pre">array</span></tt> module also provides methods for creating arrays of
  1378. fixed types with compact representations, but they are slower to index
  1379. than lists.  Also note that the Numeric extensions and others define
  1380. array-like structures with various characteristics as well.</p>
  1381. <p>To get Lisp-style linked lists, you can emulate cons cells using tuples:</p>
  1382. <pre class="literal-block">
  1383. lisp_list = ("like",  ("this",  ("example", None) ) )
  1384. </pre>
  1385. <p>If mutability is desired, you could use lists instead of tuples.  Here
  1386. the analogue of lisp car is <tt class="docutils literal"><span class="pre">lisp_list[0]</span></tt> and the analogue of cdr
  1387. is <tt class="docutils literal"><span class="pre">lisp_list[1]</span></tt>.  Only do this if you're sure you really need to,
  1388. because it's usually a lot slower than using Python lists.</p>
  1389. </div>
  1390. <div class="section" id="how-do-i-create-a-multidimensional-list">
  1391. <h2><a class="toc-backref" href="#id36">4.6   How do I create a multidimensional list?</a></h2>
  1392. <p>You probably tried to make a multidimensional array like this:</p>
  1393. <pre class="literal-block">
  1394. A = [[None] * 2] * 3
  1395. </pre>
  1396. <p>This looks correct if you print it:</p>
  1397. <pre class="literal-block">
  1398. >>> A
  1399. [[None, None], [None, None], [None, None]]
  1400. </pre>
  1401. <p>But when you assign a value, it shows up in multiple places:</p>
  1402. <blockquote>
  1403. <pre class="doctest-block">
  1404. >>> A[0][0] = 5
  1405. >>> A
  1406. [[5, None], [5, None], [5, None]]
  1407. </pre>
  1408. </blockquote>
  1409. <p>The reason is that replicating a list with <tt class="docutils literal"><span class="pre">*</span></tt> doesn't create copies, it only creates references to the existing objects.  The <tt class="docutils literal"><span class="pre">*3</span></tt>
  1410. creates a list containing 3 references to the same list of length
  1411. two.  Changes to one row will show in all rows, which is almost certainly
  1412. not what you want.</p>
  1413. <p>The suggested approach is to create a list of the desired length first
  1414. and then fill in each element with a newly created list:</p>
  1415. <pre class="literal-block">
  1416. A = [None]*3
  1417. for i in range(3):
  1418.      A[i] = [None] * 2
  1419. </pre>
  1420. <p>This generates a list containing 3 different lists of length two.
  1421. You can also use a list comprehension:</p>
  1422. <pre class="literal-block">
  1423. w,h = 2,3
  1424. A = [ [None]*w for i in range(h) ]
  1425. </pre>
  1426. <p>Or, you can use an extension that provides a matrix datatype; <a class="reference external" href="http://www.pfdubois.com/numpy/">Numeric
  1427. Python</a> is the best known.</p>
  1428. </div>
  1429. <div class="section" id="how-do-i-apply-a-method-to-a-sequence-of-objects">
  1430. <h2><a class="toc-backref" href="#id37">4.7   How do I apply a method to a sequence of objects?</a></h2>
  1431. <p>Use a list comprehension:</p>
  1432. <pre class="literal-block">
  1433. result = [obj.method() for obj in List]
  1434. </pre>
  1435. <p>More generically, you can try the following function:</p>
  1436. <pre class="literal-block">
  1437. def method_map(objects, method, arguments):
  1438.      """method_map([a,b], "meth", (1,2)) gives [a.meth(1,2), b.meth(1,2)]"""
  1439.      nobjects = len(objects)
  1440.      methods = map(getattr, objects, [method]*nobjects)
  1441.      return map(apply, methods, [arguments]*nobjects)
  1442. </pre>
  1443. </div>
  1444. </div>
  1445. <div class="section" id="dictionaries">
  1446. <h1><a class="toc-backref" href="#id38">5   Dictionaries</a></h1>
  1447. <div class="section" id="how-can-i-get-a-dictionary-to-display-its-keys-in-a-consistent-order">
  1448. <h2><a class="toc-backref" href="#id39">5.1   How can I get a dictionary to display its keys in a consistent order?</a></h2>
  1449. <p>You can't.  Dictionaries store their keys in an unpredictable order,
  1450. so the display order of a dictionary's elements will be similarly
  1451. unpredictable.</p>
  1452. <p>This can be frustrating if you want to save a printable version to a
  1453. file, make some changes and then compare it with some other printed
  1454. dictionary.  In this case, use the <tt class="docutils literal"><span class="pre">pprint</span></tt> module to pretty-print
  1455. the dictionary; the items will be presented in order sorted by the key.</p>
  1456. <p>A more complicated solution is to subclass <tt class="docutils literal"><span class="pre">UserDict.UserDict</span></tt>
  1457. to create a <tt class="docutils literal"><span class="pre">SortedDict</span></tt> class that prints itself in a predictable order.
  1458. Here's one simpleminded implementation of such a class:</p>
  1459. <pre class="literal-block">
  1460. import UserDict, string
  1461.  
  1462. class SortedDict(UserDict.UserDict):
  1463.   def __repr__(self):
  1464.     result = []
  1465.     append = result.append
  1466.     keys = self.data.keys()
  1467.     keys.sort()
  1468.     for k in keys:
  1469.       append("%s: %s" % (`k`, `self.data[k]`))
  1470.     return "{%s}" % string.join(result, ", ")
  1471.  
  1472.   ___str__ = __repr__
  1473. </pre>
  1474. <p>This will work for many common situations you might encounter, though
  1475. it's far from a perfect solution. The largest flaw is that if some
  1476. values in the dictionary are also dictionaries, their values won't be
  1477. presented in any particular order.</p>
  1478. </div>
  1479. <div class="section" id="i-want-to-do-a-complicated-sort-can-you-do-a-schwartzian-transform-in-python">
  1480. <h2><a class="toc-backref" href="#id40">5.2   I want to do a complicated sort: can you do a Schwartzian Transform in Python?</a></h2>
  1481. <p>Yes, it's quite simple with list comprehensions.</p>
  1482. <p>The technique, attributed to Randal Schwartz of the Perl community,
  1483. sorts the elements of a list by a metric which maps each element to
  1484. its "sort value".  To sort a list of strings by their uppercase
  1485. values:</p>
  1486. <pre class="literal-block">
  1487. tmp1 = [ (x.upper(), x) for x in L ] # Schwartzian transform
  1488. tmp1.sort()
  1489. Usorted = [ x[1] for x in tmp1 ]
  1490. </pre>
  1491. <p>To sort by the integer value of a subfield extending from positions 10-15
  1492. in each string:</p>
  1493. <pre class="literal-block">
  1494. tmp2 = [ (int(s[10:15]), s) for s in L ] # Schwartzian transform
  1495. tmp2.sort()
  1496. Isorted = [ x[1] for x in tmp2 ]
  1497. </pre>
  1498. <p>Note that Isorted may also be computed by</p>
  1499. <pre class="literal-block">
  1500. def intfield(s):
  1501.     return int(s[10:15])
  1502.  
  1503. def Icmp(s1, s2):
  1504.     return cmp(intfield(s1), intfield(s2))
  1505.  
  1506. Isorted = L[:]
  1507. Isorted.sort(Icmp)
  1508. </pre>
  1509. <p>but since this method calls <tt class="docutils literal"><span class="pre">intfield()</span></tt> many times for each element
  1510. of L, it is slower than the Schwartzian Transform.</p>
  1511. </div>
  1512. <div class="section" id="how-can-i-sort-one-list-by-values-from-another-list">
  1513. <h2><a class="toc-backref" href="#id41">5.3   How can I sort one list by values from another list?</a></h2>
  1514. <p>Merge them into a single list of tuples, sort the resulting list,
  1515. and then pick out the element you want.</p>
  1516. <pre class="literal-block">
  1517. >>> list1 = ["what", "I'm", "sorting", "by"]
  1518. >>> list2 = ["something", "else", "to", "sort"]
  1519. >>> pairs = zip(list1, list2)
  1520. >>> pairs
  1521. [('what', 'something'), ("I'm", 'else'), ('sorting', 'to'), ('by', 'sort')]
  1522. >>> pairs.sort()
  1523. >>> result = [ x[1] for x in pairs ]
  1524. >>> result
  1525. ['else', 'sort', 'to', 'something']
  1526. </pre>
  1527. <p>An alternative for the last step is:</p>
  1528. <pre class="literal-block">
  1529. result = []
  1530. for p in pairs: result.append(p[1])
  1531. </pre>
  1532. <p>If you find this more legible, you might prefer to use this instead of
  1533. the final list comprehension.  However, it is almost twice as slow for
  1534. long lists.  Why?  First, the <tt class="docutils literal"><span class="pre">append()</span></tt> operation has to reallocate
  1535. memory, and while it uses some tricks to avoid doing that each time,
  1536. it still has to do it occasionally, and that costs quite a bit.
  1537. Second, the expression "result.append" requires an extra attribute
  1538. lookup, and third, there's a speed reduction from having to make
  1539. all those function calls.</p>
  1540. </div>
  1541. </div>
  1542. <div class="section" id="objects">
  1543. <h1><a class="toc-backref" href="#id42">6   Objects</a></h1>
  1544. <div class="section" id="what-is-a-class">
  1545. <h2><a class="toc-backref" href="#id43">6.1   What is a class?</a></h2>
  1546. <p>A class is the particular object type created by executing
  1547. a class statement.  Class objects are used as templates to create
  1548. instance objects, which embody both the data
  1549. (attributes) and code (methods) specific to a datatype.</p>
  1550. <p>A class can be based on one or more other classes, called its base
  1551. class(es). It then inherits the attributes and methods of its base
  1552. classes. This allows an object model to be successively refined by
  1553. inheritance.  You might have a generic <tt class="docutils literal"><span class="pre">Mailbox</span></tt> class that provides
  1554. basic accessor methods for a mailbox, and subclasses such as
  1555. <tt class="docutils literal"><span class="pre">MboxMailbox</span></tt>, <tt class="docutils literal"><span class="pre">MaildirMailbox</span></tt>, <tt class="docutils literal"><span class="pre">OutlookMailbox</span></tt> that handle
  1556. various specific mailbox formats.</p>
  1557. </div>
  1558. <div class="section" id="what-is-a-method">
  1559. <h2><a class="toc-backref" href="#id44">6.2   What is a method?</a></h2>
  1560. <p>A method is a function on some object <tt class="docutils literal"><span class="pre">x</span></tt> that you normally call as
  1561. <tt class="docutils literal"><span class="pre">x.name(arguments...)</span></tt>.  Methods are defined as functions inside the
  1562. class definition:</p>
  1563. <pre class="literal-block">
  1564. class C:
  1565.     def meth (self, arg):
  1566.         return arg*2 + self.attribute
  1567. </pre>
  1568. </div>
  1569. <div class="section" id="what-is-self">
  1570. <h2><a class="toc-backref" href="#id45">6.3   What is self?</a></h2>
  1571. <p>Self is merely a conventional name for the first argument of a method.
  1572. A method defined as <tt class="docutils literal"><span class="pre">meth(self,</span> <span class="pre">a,</span> <span class="pre">b,</span> <span class="pre">c)</span></tt> should be called as
  1573. <tt class="docutils literal"><span class="pre">x.meth(a,</span> <span class="pre">b,</span> <span class="pre">c)</span></tt> for some instance <tt class="docutils literal"><span class="pre">x</span></tt> of the class in which the
  1574. definition occurs; the called method will think it is called as
  1575. <tt class="docutils literal"><span class="pre">meth(x,</span> <span class="pre">a,</span> <span class="pre">b,</span> <span class="pre">c)</span></tt>.</p>
  1576. <p>See also
  1577. <a class="reference external" href="general.html#why-must-self-be-used-explicitly-in-method-definitions-and-calls">Why must 'self' be used explicitly in method definitions and calls?</a></p>
  1578. </div>
  1579. <div class="section" id="how-do-i-check-if-an-object-is-an-instance-of-a-given-class-or-of-a-subclass-of-it">
  1580. <h2><a class="toc-backref" href="#id46">6.4   How do I check if an object is an instance of a given class or of a subclass of it?</a></h2>
  1581. <p>Use the built-in function <tt class="docutils literal"><span class="pre">isinstance(obj,</span> <span class="pre">cls)</span></tt>.  You can check if
  1582. an object is an instance of any of a number of classes by providing a tuple instead of a single class, e.g. <tt class="docutils literal"><span class="pre">isinstance(obj,</span> <span class="pre">(class1,</span> <span class="pre">class2,</span> <span class="pre">...))</span></tt>,
  1583. and can also check whether an object is one of Python's built-in types, e.g.
  1584. <tt class="docutils literal"><span class="pre">isinstance(obj,</span> <span class="pre">str)</span></tt> or <tt class="docutils literal"><span class="pre">isinstance(obj,</span> <span class="pre">(int,</span> <span class="pre">long,</span> <span class="pre">float,</span> <span class="pre">complex))</span></tt>.</p>
  1585. <p>Note that most programs do not use <tt class="docutils literal"><span class="pre">isinstance()</span></tt> on user-defined
  1586. classes very often.  If you are developing the classes yourself, a
  1587. more proper object-oriented style is to define methods on the classes
  1588. that encapsulate a particular behaviour, instead of checking the
  1589. object's class and doing a different thing based on what class it is.
  1590. For example, if you have a function that does something:</p>
  1591. <pre class="literal-block">
  1592. def search (obj):
  1593.     if isinstance(obj, Mailbox):
  1594.         # ... code to search a mailbox
  1595.     elif isinstance(obj, Document):
  1596.         # ... code to search a document
  1597.     elif ...
  1598. </pre>
  1599. <p>A better approach is to define a <tt class="docutils literal"><span class="pre">search()</span></tt> method on all the
  1600. classes and just call it:</p>
  1601. <pre class="literal-block">
  1602. class Mailbox:
  1603.     def search(self):
  1604.         # ... code to search a mailbox
  1605.  
  1606. class Document:
  1607.     def search(self):
  1608.         # ... code to search a document
  1609.  
  1610. obj.search()
  1611. </pre>
  1612. </div>
  1613. <div class="section" id="what-is-delegation">
  1614. <h2><a class="toc-backref" href="#id47">6.5   What is delegation?</a></h2>
  1615. <p>Delegation is an object oriented technique (also called a design
  1616. pattern).  Let's say you have an object <tt class="docutils literal"><span class="pre">x</span></tt> and want to change the
  1617. behaviour of just one of its methods.  You can create a new class that
  1618. provides a new implementation of the method you're interested in changing
  1619. and delegates all other methods to the corresponding method of <tt class="docutils literal"><span class="pre">x</span></tt>.</p>
  1620. <p>Python programmers can easily implement delegation.  For example, the
  1621. following class implements a class that behaves like a file but
  1622. converts all written data to uppercase:</p>
  1623. <pre class="literal-block">
  1624. class UpperOut:
  1625.       def __init__(self, outfile):
  1626.             self.__outfile = outfile
  1627.       def write(self, s):
  1628.             self.__outfile.write(s.upper())
  1629.       def __getattr__(self, name):
  1630.             return getattr(self.__outfile, name)
  1631. </pre>
  1632. <p>Here the <tt class="docutils literal"><span class="pre">UpperOut</span></tt> class redefines the <tt class="docutils literal"><span class="pre">write()</span></tt> method to
  1633. convert the argument string to uppercase before calling the underlying
  1634. <tt class="docutils literal"><span class="pre">self.__outfile.write()</span></tt> method.  All other methods are delegated to
  1635. the underlying <tt class="docutils literal"><span class="pre">self.__outfile</span></tt> object.  The delegation is
  1636. accomplished via the <tt class="docutils literal"><span class="pre">__getattr__</span></tt> method; consult <a class="reference external" href="../../doc/ref/attribute-access.html">the language
  1637. reference</a> for
  1638. more information about controlling attribute access.</p>
  1639. <p>Note that for more general cases delegation can get trickier. When
  1640. attributes must be set as well as retrieved, the class must define a
  1641. <tt class="docutils literal"><span class="pre">__settattr__</span></tt> method too, and it must do so carefully.  The basic
  1642. implementation of __setattr__ is roughly equivalent to the following:</p>
  1643. <pre class="literal-block">
  1644. class X:
  1645.      ...
  1646.      def __setattr__(self, name, value):
  1647.           self.__dict__[name] = value
  1648.      ...
  1649. </pre>
  1650. <p>Most __setattr__ implementations must modify
  1651. self.__dict__ to store local state for self without
  1652. causing an infinite recursion.</p>
  1653. </div>
  1654. <div class="section" id="how-do-i-call-a-method-defined-in-a-base-class-from-a-derived-class-that-overrides-it">
  1655. <h2><a class="toc-backref" href="#id48">6.6   How do I call a method defined in a base class from a derived class that overrides it?</a></h2>
  1656. <p>If you're using new-style classes, use the built-in <tt class="docutils literal"><span class="pre">super()</span></tt> function:</p>
  1657. <pre class="literal-block">
  1658. class Derived(Base):
  1659.     def meth (self):
  1660.         super(Derived, self).meth()
  1661. </pre>
  1662. <p>If you're using classic classes: For a class definition such as
  1663. <tt class="docutils literal"><span class="pre">class</span> <span class="pre">Derived(Base):</span> <span class="pre">...</span></tt> you can call method <tt class="docutils literal"><span class="pre">meth()</span></tt> defined in
  1664. <tt class="docutils literal"><span class="pre">Base</span></tt> (or one of <tt class="docutils literal"><span class="pre">Base</span></tt>'s base classes) as <tt class="docutils literal"><span class="pre">Base.meth(self,</span>
  1665. <span class="pre">arguments...)</span></tt>.  Here, <tt class="docutils literal"><span class="pre">Base.meth</span></tt> is an unbound method, so you
  1666. need to provide the <tt class="docutils literal"><span class="pre">self</span></tt> argument.</p>
  1667. </div>
  1668. <div class="section" id="how-can-i-organize-my-code-to-make-it-easier-to-change-the-base-class">
  1669. <h2><a class="toc-backref" href="#id49">6.7   How can I organize my code to make it easier to change the base class?</a></h2>
  1670. <p>You could define an alias for the base class, assign the real base
  1671. class to it before your class definition, and use the alias throughout
  1672. your class.  Then all you have to change is the value assigned to the
  1673. alias.  Incidentally, this trick is also handy if you want to decide
  1674. dynamically (e.g. depending on availability of resources) which base
  1675. class to use.  Example:</p>
  1676. <pre class="literal-block">
  1677. BaseAlias = <real base class>
  1678. class Derived(BaseAlias):
  1679.         def meth(self):
  1680.                 BaseAlias.meth(self)
  1681.                 ...
  1682. </pre>
  1683. </div>
  1684. <div class="section" id="how-do-i-create-static-class-data-and-static-class-methods">
  1685. <h2><a class="toc-backref" href="#id50">6.8   How do I create static class data and static class methods?</a></h2>
  1686. <p>Static data (in the sense of C++ or Java) is easy; static methods
  1687. (again in the sense of C++ or Java) are not supported directly.</p>
  1688. <p>For static data, simply define a class attribute.  To assign a new
  1689. value to the attribute, you have to explicitly use the class name in
  1690. the assignment:</p>
  1691. <pre class="literal-block">
  1692. class C:
  1693.     count = 0   # number of times C.__init__ called
  1694.  
  1695.     def __init__(self):
  1696.         C.count = C.count + 1
  1697.  
  1698.     def getcount(self):
  1699.         return C.count  # or return self.count
  1700. </pre>
  1701. <p><tt class="docutils literal"><span class="pre">c.count</span></tt> also refers to <tt class="docutils literal"><span class="pre">C.count</span></tt> for any <tt class="docutils literal"><span class="pre">c</span></tt> such that
  1702. <tt class="docutils literal"><span class="pre">isinstance(c,</span> <span class="pre">C)</span></tt> holds, unless overridden by <tt class="docutils literal"><span class="pre">c</span></tt> itself or by some
  1703. class on the base-class search path from <tt class="docutils literal"><span class="pre">c.__class__</span></tt> back to <tt class="docutils literal"><span class="pre">C</span></tt>.</p>
  1704. <p>Caution:  within a method of C, an assignment like <tt class="docutils literal"><span class="pre">self.count</span> <span class="pre">=</span> <span class="pre">42</span></tt>
  1705. creates a new and unrelated instance vrbl named "count" in <tt class="docutils literal"><span class="pre">self</span></tt>'s own dict.
  1706. Rebinding of a class-static data name must always specify the class
  1707. whether inside a method or not:</p>
  1708. <pre class="literal-block">
  1709. C.count = 314
  1710. </pre>
  1711. <p>Static methods are possible when you're using new-style classes:</p>
  1712. <pre class="literal-block">
  1713. class C:
  1714.     def static(arg1, arg2, arg3):
  1715.         # No 'self' parameter!
  1716.         ...
  1717.     static = staticmethod(static)
  1718. </pre>
  1719. <p>However, a far more straightforward way to get the effect of a static
  1720. method is via a simple module-level function:</p>
  1721. <pre class="literal-block">
  1722. def getcount():
  1723.     return C.count
  1724. </pre>
  1725. <p>If your code is structured so as to define one class (or tightly
  1726. related class hierarchy) per module, this supplies the desired
  1727. encapsulation.</p>
  1728. </div>
  1729. <div class="section" id="how-can-i-overload-constructors-or-methods-in-python">
  1730. <h2><a class="toc-backref" href="#id51">6.9   How can I overload constructors (or methods) in Python?</a></h2>
  1731. <p>This answer actually applies to all methods, but the question
  1732. usually comes up first in the context of constructors.</p>
  1733. <p>In C++ you'd write</p>
  1734. <pre class="literal-block">
  1735. class C {
  1736.     C() { cout << "No arguments\n"; }
  1737.     C(int i) { cout << "Argument is " << i << "\n"; }
  1738. }
  1739. </pre>
  1740. <p>in Python you have to write a single constructor that catches all
  1741. cases using default arguments.  For example:</p>
  1742. <pre class="literal-block">
  1743. class C:
  1744.     def __init__(self, i=None):
  1745.         if i is None:
  1746.             print "No arguments"
  1747.         else:
  1748.             print "Argument is", i
  1749. </pre>
  1750. <p>This is not entirely equivalent, but close enough in practice.</p>
  1751. <p>You could also try a variable-length argument list, e.g.</p>
  1752. <pre class="literal-block">
  1753. def __init__(self, *args):
  1754.     ....
  1755. </pre>
  1756. <p>The same approach works for all method definitions.</p>
  1757. </div>
  1758. <div class="section" id="i-try-to-use-spam-and-i-get-an-error-about-someclassname-spam">
  1759. <h2><a class="toc-backref" href="#id52">6.10   I try to use __spam and I get an error about _SomeClassName__spam.</a></h2>
  1760. <p>Variables with double leading underscore are "mangled" to provide a
  1761. simple but effective way to define class private variables.  Any
  1762. identifier of the form <tt class="docutils literal"><span class="pre">__spam</span></tt> (at least two leading
  1763. underscores, at most one trailing underscore) is textually
  1764. replaced with <tt class="docutils literal"><span class="pre">_classname__spam</span></tt>, where <tt class="docutils literal"><span class="pre">classname</span></tt> is the
  1765. current class name with any leading underscores stripped.</p>
  1766. <p>This doesn't guarantee privacy: an outside user can still deliberately
  1767. access the "_classname__spam" attribute, and private values are visible
  1768. in the object's <tt class="docutils literal"><span class="pre">__dict__</span></tt>.  Many Python programmers never bother to use
  1769. private variable names at all.</p>
  1770. </div>
  1771. <div class="section" id="my-class-defines-del-but-it-is-not-called-when-i-delete-the-object">
  1772. <h2><a class="toc-backref" href="#id53">6.11   My class defines __del__ but it is not called when I delete the object.</a></h2>
  1773. <p>There are several possible reasons for this.</p>
  1774. <p>The del statement does not necessarily call __del__ -- it simply
  1775. decrements the object's reference count, and if this reaches zero
  1776. __del__ is called.</p>
  1777. <p>If your data structures contain circular links (e.g. a tree where each
  1778. child has a parent reference and each parent has a list of children)
  1779. the reference counts will never go back to zero.  Once in a while
  1780. Python runs an algorithm to detect such cycles, but the garbage
  1781. collector might run some time after the last reference to your data
  1782. structure vanishes, so your __del__ method may be called at an
  1783. inconvenient and random time. This is inconvenient if you're trying to
  1784. reproduce a problem. Worse, the order in which object's __del__
  1785. methods are executed is arbitrary.  You can run <tt class="docutils literal"><span class="pre">gc.collect()</span></tt> to
  1786. force a collection, but there <em>are</em> pathological cases where objects will
  1787. never be collected.</p>
  1788. <p>Despite the cycle collector, it's still a good idea to define an
  1789. explicit <tt class="docutils literal"><span class="pre">close()</span></tt> method on objects to be called whenever you're
  1790. done with them.  The <tt class="docutils literal"><span class="pre">close()</span></tt> method can then remove attributes
  1791. that refer to subobjecs.  Don't call <tt class="docutils literal"><span class="pre">__del__</span></tt> directly --
  1792. <tt class="docutils literal"><span class="pre">__del__</span></tt> should call <tt class="docutils literal"><span class="pre">close()</span></tt> and <tt class="docutils literal"><span class="pre">close()</span></tt> should make sure
  1793. that it can be called more than once for the same object.</p>
  1794. <p>Another way to avoid cyclical references is to use the "weakref"
  1795. module, which allows you to point to objects without incrementing
  1796. their reference count. Tree data structures, for instance, should use
  1797. weak references for their parent and sibling references (if they need
  1798. them!).</p>
  1799. <p>If the object has ever been a local variable in a function that caught
  1800. an expression in an except clause, chances are that a reference to the
  1801. object still exists in that function's stack frame as contained in the
  1802. stack trace.  Normally, calling <tt class="docutils literal"><span class="pre">sys.exc_clear()</span></tt> will take care of
  1803. this by clearing the last recorded exception.</p>
  1804. <p>Finally, if your __del__ method raises an exception, a warning message
  1805. is printed to sys.stderr.</p>
  1806. </div>
  1807. <div class="section" id="how-do-i-get-a-list-of-all-instances-of-a-given-class">
  1808. <h2><a class="toc-backref" href="#id54">6.12   How do I get a list of all instances of a given class?</a></h2>
  1809. <p>Python does not keep track of all instances of a class (or of a
  1810. built-in type).  You can program the class's constructor to keep track
  1811. of all instances by keeping a list of weak references to each
  1812. instance.</p>
  1813. </div>
  1814. </div>
  1815. <div class="section" id="modules">
  1816. <h1><a class="toc-backref" href="#id55">7   Modules</a></h1>
  1817. <div class="section" id="how-do-i-create-a-pyc-file">
  1818. <h2><a class="toc-backref" href="#id56">7.1   How do I create a .pyc file?</a></h2>
  1819. <p>When a module is imported for the first time (or when the source is
  1820. more recent than the current compiled file) a <tt class="docutils literal"><span class="pre">.pyc</span></tt> file containing
  1821. the compiled code should be created in the same directory as the
  1822. <tt class="docutils literal"><span class="pre">.py</span></tt> file.</p>
  1823. <p>One reason that a <tt class="docutils literal"><span class="pre">.pyc</span></tt> file may not be created is permissions
  1824. problems with the directory. This can happen, for example, if you
  1825. develop as one user but run as another, such as if you are testing
  1826. with a web server.  Creation of a .pyc file is automatic if you're
  1827. importing a module and Python has the ability (permissions, free
  1828. space, etc...) to write the compiled module back to the directory.</p>
  1829. <p>Running Python on a top level script is not considered an import and
  1830. no <tt class="docutils literal"><span class="pre">.pyc</span></tt> will be created.  For example, if you have a top-level
  1831. module <tt class="docutils literal"><span class="pre">abc.py</span></tt> that imports another module <tt class="docutils literal"><span class="pre">xyz.py</span></tt>, when you run
  1832. abc, <tt class="docutils literal"><span class="pre">xyz.pyc</span></tt> will be created since xyz is imported, but no
  1833. <tt class="docutils literal"><span class="pre">abc.pyc</span></tt> file will be created since <tt class="docutils literal"><span class="pre">abc.py</span></tt> isn't being
  1834. imported.</p>
  1835. <p>If you need to create abc.pyc -- that is, to create a .pyc file for a
  1836. module that is not imported -- you can, using the py_compile and
  1837. compileall modules.</p>
  1838. <p>The <tt class="docutils literal"><span class="pre">py_compile</span></tt> module can manually compile any module.  One way is
  1839. to use the <tt class="docutils literal"><span class="pre">compile()</span></tt> function in that module interactively:</p>
  1840. <pre class="literal-block">
  1841. >>> import py_compile
  1842. >>> py_compile.compile('abc.py')
  1843. </pre>
  1844. <p>This will write the <tt class="docutils literal"><span class="pre">.pyc</span></tt> to the same location as <tt class="docutils literal"><span class="pre">abc.py</span></tt> (or
  1845. you can override that with the optional parameter <tt class="docutils literal"><span class="pre">cfile</span></tt>).</p>
  1846. <p>You can also automatically compile all files in a directory or
  1847. directories using the <tt class="docutils literal"><span class="pre">compileall</span></tt> module.
  1848. You can do it from the shell prompt by running <tt class="docutils literal"><span class="pre">compileall.py</span></tt>
  1849. and providing the path of a directory containing Python files to compile:</p>
  1850. <pre class="literal-block">
  1851. python compileall.py .
  1852. </pre>
  1853. </div>
  1854. <div class="section" id="how-do-i-find-the-current-module-name">
  1855. <h2><a class="toc-backref" href="#id57">7.2   How do I find the current module name?</a></h2>
  1856. <p>A module can find out its own module name by looking at the predefined
  1857. global variable <tt class="docutils literal"><span class="pre">__name__</span></tt>.  If this has the value '__main__', the
  1858. program is running as a script.  Many modules that are usually used by
  1859. importing them also provide a command-line interface or a self-test,
  1860. and only execute this code after checking <tt class="docutils literal"><span class="pre">__name__</span></tt>:</p>
  1861. <pre class="literal-block">
  1862. def main():
  1863.     print 'Running test...'
  1864.     ...
  1865.  
  1866. if __name__ == '__main__':
  1867.     main()
  1868. </pre>
  1869. </div>
  1870. <div class="section" id="how-can-i-have-modules-that-mutually-import-each-other">
  1871. <h2><a class="toc-backref" href="#id58">7.3   How can I have modules that mutually import each other?</a></h2>
  1872. <p>Suppose you have the following modules:</p>
  1873. <p>foo.py:</p>
  1874. <pre class="literal-block">
  1875. from bar import bar_var
  1876. foo_var=1
  1877. </pre>
  1878. <p>bar.py:</p>
  1879. <pre class="literal-block">
  1880. from foo import foo_var
  1881. bar_var=2
  1882. </pre>
  1883. <p>The problem is that the interpreter will perform the following steps:</p>
  1884. <ul class="simple">
  1885. <li>main imports foo</li>
  1886. <li>Empty globals for foo are created</li>
  1887. <li>foo is compiled and starts executing</li>
  1888. <li>foo imports bar</li>
  1889. <li>Empty globals for bar are created</li>
  1890. <li>bar is compiled and starts executing</li>
  1891. <li>bar imports foo (which is a no-op since there already is a module named foo)</li>
  1892. <li>bar.foo_var = foo.foo_var</li>
  1893. </ul>
  1894. <p>The last step fails, because Python isn't done with interpreting <tt class="docutils literal"><span class="pre">foo</span></tt>
  1895. yet and the global symbol dictionary for <tt class="docutils literal"><span class="pre">foo</span></tt> is still empty.</p>
  1896. <p>The same thing happens when you use <tt class="docutils literal"><span class="pre">import</span> <span class="pre">foo</span></tt>, and then try to
  1897. access <tt class="docutils literal"><span class="pre">foo.foo_var</span></tt> in global code.</p>
  1898. <p>There are (at least) three possible workarounds for this problem.</p>
  1899. <p>Guido van Rossum recommends avoiding all uses of <tt class="docutils literal"><span class="pre">from</span> <span class="pre"><module></span>
  1900. <span class="pre">import</span> <span class="pre">...</span></tt>, and placing all code inside functions.  Initializations
  1901. of global variables and class variables should use constants or
  1902. built-in functions only.  This means everything from an imported
  1903. module is referenced as <tt class="docutils literal"><span class="pre"><module>.<name></span></tt>.</p>
  1904. <p>Jim Roskind suggests performing steps in the following order in each
  1905. module:</p>
  1906. <ul class="simple">
  1907. <li>exports (globals, functions, and classes that don't need imported base classes)</li>
  1908. <li><tt class="docutils literal"><span class="pre">import</span></tt> statements</li>
  1909. <li>active code (including globals that are initialized from imported values).</li>
  1910. </ul>
  1911. <p>van Rossum doesn't like this approach much because the imports
  1912. appear in a strange place, but it does work.</p>
  1913. <p>Matthias Urlichs recommends restructuring your code so that the
  1914. recursive import is not necessary in the first place.</p>
  1915. <p>These solutions are not mutually exclusive.</p>
  1916. </div>
  1917. <div class="section" id="import-x-y-z-returns-module-x-how-do-i-get-z">
  1918. <h2><a class="toc-backref" href="#id59">7.4   __import__('x.y.z') returns <module 'x'>; how do I get z?</a></h2>
  1919. <p>Try:</p>
  1920. <pre class="literal-block">
  1921. __import__('x.y.z').y.z
  1922. </pre>
  1923. <p>For more realistic situations, you may have to do something like</p>
  1924. <pre class="literal-block">
  1925. m = __import__(s)
  1926. for i in s.split(".")[1:]:
  1927.     m = getattr(m, i)
  1928. </pre>
  1929. </div>
  1930. <div class="section" id="when-i-edit-an-imported-module-and-reimport-it-the-changes-don-t-show-up-why-does-this-happen">
  1931. <h2><a class="toc-backref" href="#id60">7.5   When I edit an imported module and reimport it, the changes don't show up.  Why does this happen?</a></h2>
  1932. <p>For reasons of efficiency as well as consistency, Python only reads
  1933. the module file on the first time a module is imported.  If it didn't,
  1934. in a program consisting of many modules where each one imports the
  1935. same basic module, the basic module would be parsed and re-parsed many
  1936. times.  To force rereading of a changed module, do this:</p>
  1937. <pre class="literal-block">
  1938. import modname
  1939. reload(modname)
  1940. </pre>
  1941. <p>Warning: this technique is not 100% fool-proof.  In particular,
  1942. modules containing statements like</p>
  1943. <pre class="literal-block">
  1944. from modname import some_objects
  1945. </pre>
  1946. <p>will continue to work with the old version of the imported objects.
  1947. If the module contains class definitions, existing class instances
  1948. will <em>not</em> be updated to use the new class definition.  This can
  1949. result in the following paradoxical behaviour:</p>
  1950. <pre class="literal-block">
  1951. >>> import cls
  1952. >>> c = cls.C()                # Create an instance of C
  1953. >>> reload(cls)
  1954. <module 'cls' from 'cls.pyc'>
  1955. >>> isinstance(c, cls.C)       # isinstance is false?!?
  1956. False
  1957. </pre>
  1958. <p>The nature of the problem is made clear if you print out the class objects:</p>
  1959. <blockquote>
  1960. <pre class="doctest-block">
  1961. >>> c.__class__
  1962. <class cls.C at 0x7352a0>
  1963. >>> cls.C
  1964. <class cls.C at 0x4198d0>
  1965. </pre>
  1966. </blockquote>
  1967. </div>
  1968. </div>
  1969. </div>
  1970. </body>
  1971. </html>
  1972.