CHips L MINI SHELL

CHips L pro

Current Path : /proc/2/root/usr/share/doc/python-docs-2.6.6/html/faq/
Upload File :
Current File : //proc/2/root/usr/share/doc/python-docs-2.6.6/html/faq/programming.html

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    
    <title>Programming FAQ &mdash; Python v2.6.6 documentation</title>
    <link rel="stylesheet" href="../_static/default.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript">
      var DOCUMENTATION_OPTIONS = {
        URL_ROOT:    '../',
        VERSION:     '2.6.6',
        COLLAPSE_MODINDEX: false,
        FILE_SUFFIX: '.html',
        HAS_SOURCE:  true
      };
    </script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python v2.6.6 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="top" title="Python v2.6.6 documentation" href="../index.html" />
    <link rel="up" title="Python Frequently Asked Questions" href="index.html" />
    <link rel="next" title="Design and History FAQ" href="design.html" />
    <link rel="prev" title="General Python FAQ" href="general.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
 

  </head>
  <body>
    <div class="related">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../modindex.html" title="Global Module Index"
             accesskey="M">modules</a> |</li>
        <li class="right" >
          <a href="design.html" title="Design and History FAQ"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="general.html" title="General Python FAQ"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="../index.html">Python v2.6.6 documentation</a> &raquo;</li>

          <li><a href="index.html" accesskey="U">Python Frequently Asked Questions</a> &raquo;</li> 
      </ul>
    </div>  

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body">
            
  <div class="section" id="programming-faq">
<h1><a class="toc-backref" href="#id1">Programming FAQ</a><a class="headerlink" href="#programming-faq" title="Permalink to this headline">¶</a></h1>
<div class="contents topic" id="contents">
<p class="topic-title first">Contents</p>
<ul class="simple">
<li><a class="reference internal" href="#programming-faq" id="id1">Programming FAQ</a><ul>
<li><a class="reference internal" href="#general-questions" id="id2">General Questions</a><ul>
<li><a class="reference internal" href="#is-there-a-source-code-level-debugger-with-breakpoints-single-stepping-etc" id="id3">Is there a source code level debugger with breakpoints, single-stepping, etc.?</a></li>
<li><a class="reference internal" href="#is-there-a-tool-to-help-find-bugs-or-perform-static-analysis" id="id4">Is there a tool to help find bugs or perform static analysis?</a></li>
<li><a class="reference internal" href="#how-can-i-create-a-stand-alone-binary-from-a-python-script" id="id5">How can I create a stand-alone binary from a Python script?</a></li>
<li><a class="reference internal" href="#are-there-coding-standards-or-a-style-guide-for-python-programs" id="id6">Are there coding standards or a style guide for Python programs?</a></li>
<li><a class="reference internal" href="#my-program-is-too-slow-how-do-i-speed-it-up" id="id7">My program is too slow. How do I speed it up?</a></li>
</ul>
</li>
<li><a class="reference internal" href="#core-language" id="id8">Core Language</a><ul>
<li><a class="reference internal" href="#why-am-i-getting-an-unboundlocalerror-when-the-variable-has-a-value" id="id9">Why am I getting an UnboundLocalError when the variable has a value?</a></li>
<li><a class="reference internal" href="#what-are-the-rules-for-local-and-global-variables-in-python" id="id10">What are the rules for local and global variables in Python?</a></li>
<li><a class="reference internal" href="#how-do-i-share-global-variables-across-modules" id="id11">How do I share global variables across modules?</a></li>
<li><a class="reference internal" href="#what-are-the-best-practices-for-using-import-in-a-module" id="id12">What are the &#8220;best practices&#8221; for using import in a module?</a></li>
<li><a class="reference internal" href="#how-can-i-pass-optional-or-keyword-parameters-from-one-function-to-another" id="id13">How can I pass optional or keyword parameters from one function to another?</a></li>
<li><a class="reference internal" href="#how-do-i-write-a-function-with-output-parameters-call-by-reference" id="id14">How do I write a function with output parameters (call by reference)?</a></li>
<li><a class="reference internal" href="#how-do-you-make-a-higher-order-function-in-python" id="id15">How do you make a higher order function in Python?</a></li>
<li><a class="reference internal" href="#how-do-i-copy-an-object-in-python" id="id16">How do I copy an object in Python?</a></li>
<li><a class="reference internal" href="#how-can-i-find-the-methods-or-attributes-of-an-object" id="id17">How can I find the methods or attributes of an object?</a></li>
<li><a class="reference internal" href="#how-can-my-code-discover-the-name-of-an-object" id="id18">How can my code discover the name of an object?</a></li>
<li><a class="reference internal" href="#what-s-up-with-the-comma-operator-s-precedence" id="id19">What&#8217;s up with the comma operator&#8217;s precedence?</a></li>
<li><a class="reference internal" href="#is-there-an-equivalent-of-c-s-ternary-operator" id="id20">Is there an equivalent of C&#8217;s &#8220;?:&#8221; ternary operator?</a></li>
<li><a class="reference internal" href="#is-it-possible-to-write-obfuscated-one-liners-in-python" id="id21">Is it possible to write obfuscated one-liners in Python?</a></li>
</ul>
</li>
<li><a class="reference internal" href="#numbers-and-strings" id="id22">Numbers and strings</a><ul>
<li><a class="reference internal" href="#how-do-i-specify-hexadecimal-and-octal-integers" id="id23">How do I specify hexadecimal and octal integers?</a></li>
<li><a class="reference internal" href="#why-does-22-10-return-3" id="id24">Why does -22 // 10 return -3?</a></li>
<li><a class="reference internal" href="#how-do-i-convert-a-string-to-a-number" id="id25">How do I convert a string to a number?</a></li>
<li><a class="reference internal" href="#how-do-i-convert-a-number-to-a-string" id="id26">How do I convert a number to a string?</a></li>
<li><a class="reference internal" href="#how-do-i-modify-a-string-in-place" id="id27">How do I modify a string in place?</a></li>
<li><a class="reference internal" href="#how-do-i-use-strings-to-call-functions-methods" id="id28">How do I use strings to call functions/methods?</a></li>
<li><a class="reference internal" href="#is-there-an-equivalent-to-perl-s-chomp-for-removing-trailing-newlines-from-strings" id="id29">Is there an equivalent to Perl&#8217;s chomp() for removing trailing newlines from strings?</a></li>
<li><a class="reference internal" href="#is-there-a-scanf-or-sscanf-equivalent" id="id30">Is there a scanf() or sscanf() equivalent?</a></li>
<li><a class="reference internal" href="#what-does-unicodeerror-ascii-decoding-encoding-error-ordinal-not-in-range-128-mean" id="id31">What does &#8216;UnicodeError: ASCII [decoding,encoding] error: ordinal not in range(128)&#8217; mean?</a></li>
</ul>
</li>
<li><a class="reference internal" href="#sequences-tuples-lists" id="id32">Sequences (Tuples/Lists)</a><ul>
<li><a class="reference internal" href="#how-do-i-convert-between-tuples-and-lists" id="id33">How do I convert between tuples and lists?</a></li>
<li><a class="reference internal" href="#what-s-a-negative-index" id="id34">What&#8217;s a negative index?</a></li>
<li><a class="reference internal" href="#how-do-i-iterate-over-a-sequence-in-reverse-order" id="id35">How do I iterate over a sequence in reverse order?</a></li>
<li><a class="reference internal" href="#how-do-you-remove-duplicates-from-a-list" id="id36">How do you remove duplicates from a list?</a></li>
<li><a class="reference internal" href="#how-do-you-make-an-array-in-python" id="id37">How do you make an array in Python?</a></li>
<li><a class="reference internal" href="#how-do-i-create-a-multidimensional-list" id="id38">How do I create a multidimensional list?</a></li>
<li><a class="reference internal" href="#how-do-i-apply-a-method-to-a-sequence-of-objects" id="id39">How do I apply a method to a sequence of objects?</a></li>
</ul>
</li>
<li><a class="reference internal" href="#dictionaries" id="id40">Dictionaries</a><ul>
<li><a class="reference internal" href="#how-can-i-get-a-dictionary-to-display-its-keys-in-a-consistent-order" id="id41">How can I get a dictionary to display its keys in a consistent order?</a></li>
<li><a class="reference internal" href="#i-want-to-do-a-complicated-sort-can-you-do-a-schwartzian-transform-in-python" id="id42">I want to do a complicated sort: can you do a Schwartzian Transform in Python?</a></li>
<li><a class="reference internal" href="#how-can-i-sort-one-list-by-values-from-another-list" id="id43">How can I sort one list by values from another list?</a></li>
</ul>
</li>
<li><a class="reference internal" href="#objects" id="id44">Objects</a><ul>
<li><a class="reference internal" href="#what-is-a-class" id="id45">What is a class?</a></li>
<li><a class="reference internal" href="#what-is-a-method" id="id46">What is a method?</a></li>
<li><a class="reference internal" href="#what-is-self" id="id47">What is self?</a></li>
<li><a class="reference internal" href="#how-do-i-check-if-an-object-is-an-instance-of-a-given-class-or-of-a-subclass-of-it" id="id48">How do I check if an object is an instance of a given class or of a subclass of it?</a></li>
<li><a class="reference internal" href="#what-is-delegation" id="id49">What is delegation?</a></li>
<li><a class="reference internal" href="#how-do-i-call-a-method-defined-in-a-base-class-from-a-derived-class-that-overrides-it" id="id50">How do I call a method defined in a base class from a derived class that overrides it?</a></li>
<li><a class="reference internal" href="#how-can-i-organize-my-code-to-make-it-easier-to-change-the-base-class" id="id51">How can I organize my code to make it easier to change the base class?</a></li>
<li><a class="reference internal" href="#how-do-i-create-static-class-data-and-static-class-methods" id="id52">How do I create static class data and static class methods?</a></li>
<li><a class="reference internal" href="#how-can-i-overload-constructors-or-methods-in-python" id="id53">How can I overload constructors (or methods) in Python?</a></li>
<li><a class="reference internal" href="#i-try-to-use-spam-and-i-get-an-error-about-someclassname-spam" id="id54">I try to use __spam and I get an error about _SomeClassName__spam.</a></li>
<li><a class="reference internal" href="#my-class-defines-del-but-it-is-not-called-when-i-delete-the-object" id="id55">My class defines __del__ but it is not called when I delete the object.</a></li>
<li><a class="reference internal" href="#how-do-i-get-a-list-of-all-instances-of-a-given-class" id="id56">How do I get a list of all instances of a given class?</a></li>
</ul>
</li>
<li><a class="reference internal" href="#modules" id="id57">Modules</a><ul>
<li><a class="reference internal" href="#how-do-i-create-a-pyc-file" id="id58">How do I create a .pyc file?</a></li>
<li><a class="reference internal" href="#how-do-i-find-the-current-module-name" id="id59">How do I find the current module name?</a></li>
<li><a class="reference internal" href="#how-can-i-have-modules-that-mutually-import-each-other" id="id60">How can I have modules that mutually import each other?</a></li>
<li><a class="reference internal" href="#import-x-y-z-returns-module-x-how-do-i-get-z" id="id61">__import__(&#8216;x.y.z&#8217;) returns &lt;module &#8216;x&#8217;&gt;; how do I get z?</a></li>
<li><a class="reference internal" href="#when-i-edit-an-imported-module-and-reimport-it-the-changes-don-t-show-up-why-does-this-happen" id="id62">When I edit an imported module and reimport it, the changes don&#8217;t show up.  Why does this happen?</a></li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
<div class="section" id="general-questions">
<h2><a class="toc-backref" href="#id2">General Questions</a><a class="headerlink" href="#general-questions" title="Permalink to this headline">¶</a></h2>
<div class="section" id="is-there-a-source-code-level-debugger-with-breakpoints-single-stepping-etc">
<h3><a class="toc-backref" href="#id3">Is there a source code level debugger with breakpoints, single-stepping, etc.?</a><a class="headerlink" href="#is-there-a-source-code-level-debugger-with-breakpoints-single-stepping-etc" title="Permalink to this headline">¶</a></h3>
<p>Yes.</p>
<p>The pdb module is a simple but adequate console-mode debugger for Python. It is
part of the standard Python library, and is <a title="The Python debugger for interactive interpreters." class="reference external" href="../library/pdb.html#module-pdb"><tt class="xref docutils literal"><span class="pre">documented</span> <span class="pre">in</span> <span class="pre">the</span> <span class="pre">Library</span>
<span class="pre">Reference</span> <span class="pre">Manual</span></tt></a>. You can also write your own debugger by using the code
for pdb as an example.</p>
<p>The IDLE interactive development environment, which is part of the standard
Python distribution (normally available as Tools/scripts/idle), includes a
graphical debugger.  There is documentation for the IDLE debugger at
<a class="reference external" href="http://www.python.org/idle/doc/idle2.html#Debugger">http://www.python.org/idle/doc/idle2.html#Debugger</a>.</p>
<p>PythonWin is a Python IDE that includes a GUI debugger based on pdb.  The
Pythonwin debugger colors breakpoints and has quite a few cool features such as
debugging non-Pythonwin programs.  Pythonwin is available as part of the <a class="reference external" href="http://sourceforge.net/projects/pywin32/">Python
for Windows Extensions</a> project and
as a part of the ActivePython distribution (see
<a class="reference external" href="http://www.activestate.com/Products/ActivePython/index.html">http://www.activestate.com/Products/ActivePython/index.html</a>).</p>
<p><a class="reference external" href="http://boa-constructor.sourceforge.net/">Boa Constructor</a> is an IDE and GUI
builder that uses wxWidgets.  It offers visual frame creation and manipulation,
an object inspector, many views on the source like object browsers, inheritance
hierarchies, doc string generated html documentation, an advanced debugger,
integrated help, and Zope support.</p>
<p><a class="reference external" href="http://www.die-offenbachs.de/eric/index.html">Eric</a> is an IDE built on PyQt
and the Scintilla editing component.</p>
<p>Pydb is a version of the standard Python debugger pdb, modified for use with DDD
(Data Display Debugger), a popular graphical debugger front end.  Pydb can be
found at <a class="reference external" href="http://bashdb.sourceforge.net/pydb/">http://bashdb.sourceforge.net/pydb/</a> and DDD can be found at
<a class="reference external" href="http://www.gnu.org/software/ddd">http://www.gnu.org/software/ddd</a>.</p>
<p>There are a number of commercial Python IDEs that include graphical debuggers.
They include:</p>
<ul class="simple">
<li>Wing IDE (<a class="reference external" href="http://wingware.com/">http://wingware.com/</a>)</li>
<li>Komodo IDE (<a class="reference external" href="http://www.activestate.com/Products/Komodo">http://www.activestate.com/Products/Komodo</a>)</li>
</ul>
</div>
<div class="section" id="is-there-a-tool-to-help-find-bugs-or-perform-static-analysis">
<h3><a class="toc-backref" href="#id4">Is there a tool to help find bugs or perform static analysis?</a><a class="headerlink" href="#is-there-a-tool-to-help-find-bugs-or-perform-static-analysis" title="Permalink to this headline">¶</a></h3>
<p>Yes.</p>
<p>PyChecker is a static analysis tool that finds bugs in Python source code and
warns about code complexity and style.  You can get PyChecker from
<a class="reference external" href="http://pychecker.sf.net">http://pychecker.sf.net</a>.</p>
<p><a class="reference external" href="http://www.logilab.org/projects/pylint">Pylint</a> is another tool that checks
if a module satisfies a coding standard, and also makes it possible to write
plug-ins to add a custom feature.  In addition to the bug checking that
PyChecker performs, Pylint offers some additional features such as checking line
length, whether variable names are well-formed according to your coding
standard, whether declared interfaces are fully implemented, and more.
<a class="reference external" href="http://www.logilab.org/card/pylint_manual">http://www.logilab.org/card/pylint_manual</a> provides a full list of Pylint&#8217;s
features.</p>
</div>
<div class="section" id="how-can-i-create-a-stand-alone-binary-from-a-python-script">
<h3><a class="toc-backref" href="#id5">How can I create a stand-alone binary from a Python script?</a><a class="headerlink" href="#how-can-i-create-a-stand-alone-binary-from-a-python-script" title="Permalink to this headline">¶</a></h3>
<p>You don&#8217;t need the ability to compile Python to C code if all you want is a
stand-alone program that users can download and run without having to install
the Python distribution first.  There are a number of tools that determine the
set of modules required by a program and bind these modules together with a
Python binary to produce a single executable.</p>
<p>One is to use the freeze tool, which is included in the Python source tree as
<tt class="docutils literal"><span class="pre">Tools/freeze</span></tt>. It converts Python byte code to C arrays; a C compiler you can
embed all your modules into a new program, which is then linked with the
standard Python modules.</p>
<p>It works by scanning your source recursively for import statements (in both
forms) and looking for the modules in the standard Python path as well as in the
source directory (for built-in modules).  It then turns the bytecode for modules
written in Python into C code (array initializers that can be turned into code
objects using the marshal module) and creates a custom-made config file that
only contains those built-in modules which are actually used in the program.  It
then compiles the generated C code and links it with the rest of the Python
interpreter to form a self-contained binary which acts exactly like your script.</p>
<p>Obviously, freeze requires a C compiler.  There are several other utilities
which don&#8217;t. One is Thomas Heller&#8217;s py2exe (Windows only) at</p>
<blockquote>
<a class="reference external" href="http://www.py2exe.org/">http://www.py2exe.org/</a></blockquote>
<p>Another is Christian Tismer&#8217;s <a class="reference external" href="http://starship.python.net/crew/pirx">SQFREEZE</a>
which appends the byte code to a specially-prepared Python interpreter that can
find the byte code in the executable.</p>
<p>Other tools include Fredrik Lundh&#8217;s <a class="reference external" href="http://www.pythonware.com/products/python/squeeze">Squeeze</a> and Anthony Tuininga&#8217;s
<a class="reference external" href="http://starship.python.net/crew/atuining/cx_Freeze/index.html">cx_Freeze</a>.</p>
</div>
<div class="section" id="are-there-coding-standards-or-a-style-guide-for-python-programs">
<h3><a class="toc-backref" href="#id6">Are there coding standards or a style guide for Python programs?</a><a class="headerlink" href="#are-there-coding-standards-or-a-style-guide-for-python-programs" title="Permalink to this headline">¶</a></h3>
<p>Yes.  The coding style required for standard library modules is documented as
<span class="target" id="index-179"></span><a class="reference external" href="http://www.python.org/dev/peps/pep-0008"><strong>PEP 8</strong></a>.</p>
</div>
<div class="section" id="my-program-is-too-slow-how-do-i-speed-it-up">
<h3><a class="toc-backref" href="#id7">My program is too slow. How do I speed it up?</a><a class="headerlink" href="#my-program-is-too-slow-how-do-i-speed-it-up" title="Permalink to this headline">¶</a></h3>
<p>That&#8217;s a tough one, in general.  There are many tricks to speed up Python code;
consider rewriting parts in C as a last resort.</p>
<p>In some cases it&#8217;s possible to automatically translate Python to C or x86
assembly language, meaning that you don&#8217;t have to modify your code to gain
increased speed.</p>
<p><a class="reference external" href="http://www.cosc.canterbury.ac.nz/~greg/python/Pyrex/">Pyrex</a> can compile a
slightly modified version of Python code into a C extension, and can be used on
many different platforms.</p>
<p><a class="reference external" href="http://psyco.sourceforge.net">Psyco</a> is a just-in-time compiler that
translates Python code into x86 assembly language.  If you can use it, Psyco can
provide dramatic speedups for critical functions.</p>
<p>The rest of this answer will discuss various tricks for squeezing a bit more
speed out of Python code.  <em>Never</em> apply any optimization tricks unless you know
you need them, after profiling has indicated that a particular function is the
heavily executed hot spot in the code.  Optimizations almost always make the
code less clear, and you shouldn&#8217;t pay the costs of reduced clarity (increased
development time, greater likelihood of bugs) unless the resulting performance
benefit is worth it.</p>
<p>There is a page on the wiki devoted to <a class="reference external" href="http://wiki.python.org/moin/PythonSpeed/PerformanceTips">performance tips</a>.</p>
<p>Guido van Rossum has written up an anecdote related to optimization at
<a class="reference external" href="http://www.python.org/doc/essays/list2str.html">http://www.python.org/doc/essays/list2str.html</a>.</p>
<p>One thing to notice is that function and (especially) method calls are rather
expensive; if you have designed a purely OO interface with lots of tiny
functions that don&#8217;t do much more than get or set an instance variable or call
another method, you might consider using a more direct way such as directly
accessing instance variables.  Also see the standard module <a title="Python source profiler." class="reference external" href="../library/profile.html#module-profile"><tt class="xref docutils literal"><span class="pre">profile</span></tt></a> which
makes it possible to find out where your program is spending most of its time
(if you have some patience &#8211; the profiling itself can slow your program down by
an order of magnitude).</p>
<p>Remember that many standard optimization heuristics you may know from other
programming experience may well apply to Python.  For example it may be faster
to send output to output devices using larger writes rather than smaller ones in
order to reduce the overhead of kernel system calls.  Thus CGI scripts that
write all output in &#8220;one shot&#8221; may be faster than those that write lots of small
pieces of output.</p>
<p>Also, be sure to use Python&#8217;s core features where appropriate.  For example,
slicing allows programs to chop up lists and other sequence objects in a single
tick of the interpreter&#8217;s mainloop using highly optimized C implementations.
Thus to get the same effect as:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">L2</span> <span class="o">=</span> <span class="p">[]</span>
<span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">[</span><span class="mi">3</span><span class="p">]:</span>
    <span class="n">L2</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">L1</span><span class="p">[</span><span class="n">i</span><span class="p">])</span>
</pre></div>
</div>
<p>it is much shorter and far faster to use</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">L2</span> <span class="o">=</span> <span class="nb">list</span><span class="p">(</span><span class="n">L1</span><span class="p">[:</span><span class="mi">3</span><span class="p">])</span>  <span class="c"># &quot;list&quot; is redundant if L1 is a list.</span>
</pre></div>
</div>
<p>Note that the functionally-oriented built-in functions such as <a title="map" class="reference external" href="../library/functions.html#map"><tt class="xref docutils literal"><span class="pre">map()</span></tt></a>,
<a title="zip" class="reference external" href="../library/functions.html#zip"><tt class="xref docutils literal"><span class="pre">zip()</span></tt></a>, and friends can be a convenient accelerator for loops that
perform a single task.  For example to pair the elements of two lists
together:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="nb">zip</span><span class="p">([</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">],</span> <span class="p">[</span><span class="mi">4</span><span class="p">,</span> <span class="mi">5</span><span class="p">,</span> <span class="mi">6</span><span class="p">])</span>
<span class="go">[(1, 4), (2, 5), (3, 6)]</span>
</pre></div>
</div>
<p>or to compute a number of sines:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="nb">map</span><span class="p">(</span><span class="n">math</span><span class="o">.</span><span class="n">sin</span><span class="p">,</span> <span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">,</span> <span class="mi">4</span><span class="p">))</span>
<span class="go">[0.841470984808, 0.909297426826, 0.14112000806, -0.756802495308]</span>
</pre></div>
</div>
<p>The operation completes very quickly in such cases.</p>
<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> <a class="reference external" href="../library/stdtypes.html#string-methods"><em>methods
of string objects</em></a>.
For example if s1..s7 are large (10K+) strings then
<tt class="docutils literal"><span class="pre">&quot;&quot;.join([s1,s2,s3,s4,s5,s6,s7])</span></tt> may be far faster than the more obvious
<tt class="docutils literal"><span class="pre">s1+s2+s3+s4+s5+s6+s7</span></tt>, since the &#8220;summation&#8221; will compute many
subexpressions, whereas <tt class="docutils literal"><span class="pre">join()</span></tt> does all the copying in one pass.  For
manipulating strings, use the <tt class="docutils literal"><span class="pre">replace()</span></tt> and the <tt class="docutils literal"><span class="pre">format()</span></tt> <a class="reference external" href="../library/stdtypes.html#string-methods"><em>methods
on string objects</em></a>.  Use regular expressions only when you&#8217;re
not dealing with constant string patterns.  You may still use <a class="reference external" href="../library/stdtypes.html#string-formatting"><em>the old %
operations</em></a> <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>
<p>Be sure to use the <tt class="xref docutils literal"><span class="pre">list.sort()</span></tt> built-in method to do sorting, and see the
<a class="reference external" href="http://wiki.python.org/moin/HowTo/Sorting">sorting mini-HOWTO</a> for examples
of moderately advanced usage.  <tt class="xref docutils literal"><span class="pre">list.sort()</span></tt> beats other techniques for
sorting in all but the most extreme circumstances.</p>
<p>Another common trick is to &#8220;push loops into functions or methods.&#8221;  For example
suppose you have a program that runs slowly and you use the profiler to
determine that a Python function <tt class="docutils literal"><span class="pre">ff()</span></tt> is being called lots of times.  If you
notice that <tt class="docutils literal"><span class="pre">ff()</span></tt>:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">def</span> <span class="nf">ff</span><span class="p">(</span><span class="n">x</span><span class="p">):</span>
    <span class="o">...</span> <span class="c"># do something with x computing result...</span>
    <span class="k">return</span> <span class="n">result</span>
</pre></div>
</div>
<p>tends to be called in loops like:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="nb">list</span> <span class="o">=</span> <span class="nb">map</span><span class="p">(</span><span class="n">ff</span><span class="p">,</span> <span class="n">oldlist</span><span class="p">)</span>
</pre></div>
</div>
<p>or:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">for</span> <span class="n">x</span> <span class="ow">in</span> <span class="n">sequence</span><span class="p">:</span>
    <span class="n">value</span> <span class="o">=</span> <span class="n">ff</span><span class="p">(</span><span class="n">x</span><span class="p">)</span>
    <span class="o">...</span> <span class="c"># do something with value...</span>
</pre></div>
</div>
<p>then you can often eliminate function call overhead by rewriting <tt class="docutils literal"><span class="pre">ff()</span></tt> to:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">def</span> <span class="nf">ffseq</span><span class="p">(</span><span class="n">seq</span><span class="p">):</span>
    <span class="n">resultseq</span> <span class="o">=</span> <span class="p">[]</span>
    <span class="k">for</span> <span class="n">x</span> <span class="ow">in</span> <span class="n">seq</span><span class="p">:</span>
        <span class="o">...</span> <span class="c"># do something with x computing result...</span>
        <span class="n">resultseq</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">result</span><span class="p">)</span>
    <span class="k">return</span> <span class="n">resultseq</span>
</pre></div>
</div>
<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>
<div class="highlight-python"><div class="highlight"><pre><span class="k">for</span> <span class="n">value</span> <span class="ow">in</span> <span class="n">ffseq</span><span class="p">(</span><span class="n">sequence</span><span class="p">):</span>
    <span class="o">...</span> <span class="c"># do something with value...</span>
</pre></div>
</div>
<p>Single calls to <tt class="docutils literal"><span class="pre">ff(x)</span></tt> translate to <tt class="docutils literal"><span class="pre">ffseq([x])[0]</span></tt> with little penalty.
Of course this technique is not always appropriate and there are other variants
which you can figure out.</p>
<p>You can gain some performance by explicitly storing the results of a function or
method lookup into a local variable.  A loop like:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">for</span> <span class="n">key</span> <span class="ow">in</span> <span class="n">token</span><span class="p">:</span>
    <span class="nb">dict</span><span class="p">[</span><span class="n">key</span><span class="p">]</span> <span class="o">=</span> <span class="nb">dict</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="n">key</span><span class="p">,</span> <span class="mi">0</span><span class="p">)</span> <span class="o">+</span> <span class="mi">1</span>
</pre></div>
</div>
<p>resolves <tt class="docutils literal"><span class="pre">dict.get</span></tt> every iteration.  If the method isn&#8217;t going to change, a
slightly faster implementation is:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">dict_get</span> <span class="o">=</span> <span class="nb">dict</span><span class="o">.</span><span class="n">get</span>  <span class="c"># look up the method once</span>
<span class="k">for</span> <span class="n">key</span> <span class="ow">in</span> <span class="n">token</span><span class="p">:</span>
    <span class="nb">dict</span><span class="p">[</span><span class="n">key</span><span class="p">]</span> <span class="o">=</span> <span class="n">dict_get</span><span class="p">(</span><span class="n">key</span><span class="p">,</span> <span class="mi">0</span><span class="p">)</span> <span class="o">+</span> <span class="mi">1</span>
</pre></div>
</div>
<p>Default arguments can be used to determine values once, at compile time instead
of at run time.  This can only be done for functions or objects which will not
be changed during program execution, such as replacing</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">def</span> <span class="nf">degree_sin</span><span class="p">(</span><span class="n">deg</span><span class="p">):</span>
    <span class="k">return</span> <span class="n">math</span><span class="o">.</span><span class="n">sin</span><span class="p">(</span><span class="n">deg</span> <span class="o">*</span> <span class="n">math</span><span class="o">.</span><span class="n">pi</span> <span class="o">/</span> <span class="mf">180.0</span><span class="p">)</span>
</pre></div>
</div>
<p>with</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">def</span> <span class="nf">degree_sin</span><span class="p">(</span><span class="n">deg</span><span class="p">,</span> <span class="n">factor</span><span class="o">=</span><span class="n">math</span><span class="o">.</span><span class="n">pi</span><span class="o">/</span><span class="mf">180.0</span><span class="p">,</span> <span class="n">sin</span><span class="o">=</span><span class="n">math</span><span class="o">.</span><span class="n">sin</span><span class="p">):</span>
    <span class="k">return</span> <span class="n">sin</span><span class="p">(</span><span class="n">deg</span> <span class="o">*</span> <span class="n">factor</span><span class="p">)</span>
</pre></div>
</div>
<p>Because this trick uses default arguments for terms which should not be changed,
it should only be used when you are not concerned with presenting a possibly
confusing API to your users.</p>
</div>
</div>
<div class="section" id="core-language">
<h2><a class="toc-backref" href="#id8">Core Language</a><a class="headerlink" href="#core-language" title="Permalink to this headline">¶</a></h2>
<div class="section" id="why-am-i-getting-an-unboundlocalerror-when-the-variable-has-a-value">
<h3><a class="toc-backref" href="#id9">Why am I getting an UnboundLocalError when the variable has a value?</a><a class="headerlink" href="#why-am-i-getting-an-unboundlocalerror-when-the-variable-has-a-value" title="Permalink to this headline">¶</a></h3>
<p>It can be a surprise to get the UnboundLocalError in previously working
code when it is modified by adding an assignment statement somewhere in
the body of a function.</p>
<p>This code:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">x</span> <span class="o">=</span> <span class="mi">10</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">def</span> <span class="nf">bar</span><span class="p">():</span>
<span class="gp">... </span>    <span class="k">print</span> <span class="n">x</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">bar</span><span class="p">()</span>
<span class="go">10</span>
</pre></div>
</div>
<p>works, but this code:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">x</span> <span class="o">=</span> <span class="mi">10</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">def</span> <span class="nf">foo</span><span class="p">():</span>
<span class="gp">... </span>    <span class="k">print</span> <span class="n">x</span>
<span class="gp">... </span>    <span class="n">x</span> <span class="o">+=</span> <span class="mi">1</span>
</pre></div>
</div>
<p>results in an UnboundLocalError:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">foo</span><span class="p">()</span>
<span class="gt">Traceback (most recent call last):</span>
  <span class="c">...</span>
<span class="nc">UnboundLocalError</span>: <span class="n-Identifier">local variable &#39;x&#39; referenced before assignment</span>
</pre></div>
</div>
<p>This is because when you make an assignment to a variable in a scope, that
variable becomes local to that scope and shadows any similarly named variable
in the outer scope.  Since the last statement in foo assigns a new value to
<tt class="docutils literal"><span class="pre">x</span></tt>, the compiler recognizes it as a local variable.  Consequently when the
earlier <tt class="docutils literal"><span class="pre">print</span> <span class="pre">x</span></tt> attempts to print the uninitialized local variable and
an error results.</p>
<p>In the example above you can access the outer scope variable by declaring it
global:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">x</span> <span class="o">=</span> <span class="mi">10</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">def</span> <span class="nf">foobar</span><span class="p">():</span>
<span class="gp">... </span>    <span class="k">global</span> <span class="n">x</span>
<span class="gp">... </span>    <span class="k">print</span> <span class="n">x</span>
<span class="gp">... </span>    <span class="n">x</span> <span class="o">+=</span> <span class="mi">1</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">foobar</span><span class="p">()</span>
<span class="go">10</span>
</pre></div>
</div>
<p>This explicit declaration is required in order to remind you that (unlike the
superficially analogous situation with class and instance variables) you are
actually modifying the value of the variable in the outer scope:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="k">print</span> <span class="n">x</span>
<span class="go">11</span>
</pre></div>
</div>
</div>
<div class="section" id="what-are-the-rules-for-local-and-global-variables-in-python">
<h3><a class="toc-backref" href="#id10">What are the rules for local and global variables in Python?</a><a class="headerlink" href="#what-are-the-rules-for-local-and-global-variables-in-python" title="Permalink to this headline">¶</a></h3>
<p>In Python, variables that are only referenced inside a function are implicitly
global.  If a variable is assigned a new value anywhere within the function&#8217;s
body, it&#8217;s assumed to be a local.  If a variable is ever assigned a new value
inside the function, the variable is implicitly local, and you need to
explicitly declare it as &#8216;global&#8217;.</p>
<p>Though a bit surprising at first, a moment&#8217;s consideration explains this.  On
one hand, requiring <a class="reference external" href="../reference/simple_stmts.html#global"><tt class="xref docutils literal"><span class="pre">global</span></tt></a> for assigned variables provides a bar
against unintended side-effects.  On the other hand, if <tt class="docutils literal"><span class="pre">global</span></tt> was required
for all global references, you&#8217;d be using <tt class="docutils literal"><span class="pre">global</span></tt> all the time.  You&#8217;d have
to declare as global every reference to a built-in function or to a component of
an imported module.  This clutter would defeat the usefulness of the <tt class="docutils literal"><span class="pre">global</span></tt>
declaration for identifying side-effects.</p>
</div>
<div class="section" id="how-do-i-share-global-variables-across-modules">
<h3><a class="toc-backref" href="#id11">How do I share global variables across modules?</a><a class="headerlink" href="#how-do-i-share-global-variables-across-modules" title="Permalink to this headline">¶</a></h3>
<p>The canonical way to share information across modules within a single program is
to create a special module (often called config or cfg).  Just import the config
module in all modules of your application; the module then becomes available as
a global name.  Because there is only one instance of each module, any changes
made to the module object get reflected everywhere.  For example:</p>
<p>config.py:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">x</span> <span class="o">=</span> <span class="mi">0</span>   <span class="c"># Default value of the &#39;x&#39; configuration setting</span>
</pre></div>
</div>
<p>mod.py:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="kn">import</span> <span class="nn">config</span>
<span class="n">config</span><span class="o">.</span><span class="n">x</span> <span class="o">=</span> <span class="mi">1</span>
</pre></div>
</div>
<p>main.py:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="kn">import</span> <span class="nn">config</span>
<span class="kn">import</span> <span class="nn">mod</span>
<span class="k">print</span> <span class="n">config</span><span class="o">.</span><span class="n">x</span>
</pre></div>
</div>
<p>Note that using a module is also the basis for implementing the Singleton design
pattern, for the same reason.</p>
</div>
<div class="section" id="what-are-the-best-practices-for-using-import-in-a-module">
<h3><a class="toc-backref" href="#id12">What are the &#8220;best practices&#8221; for using import in a module?</a><a class="headerlink" href="#what-are-the-best-practices-for-using-import-in-a-module" title="Permalink to this headline">¶</a></h3>
<p>In general, don&#8217;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>.  Doing so clutters the
importer&#8217;s namespace.  Some people avoid this idiom even with the few modules
that were designed to be imported in this manner.  Modules designed in this
manner include <a title="Interface to Tcl/Tk for graphical user interfaces" class="reference external" href="../library/tkinter.html#module-Tkinter"><tt class="xref docutils literal"><span class="pre">Tkinter</span></tt></a>, and <a title="Higher-level threading interface." class="reference external" href="../library/threading.html#module-threading"><tt class="xref docutils literal"><span class="pre">threading</span></tt></a>.</p>
<p>Import modules at the top of a file.  Doing so makes it clear what other modules
your code requires and avoids questions of whether the module name is in scope.
Using one import per line makes it easy to add and delete module imports, but
using multiple imports per line uses less screen space.</p>
<p>It&#8217;s good practice if you import modules in the following order:</p>
<ol class="arabic simple">
<li>standard library modules &#8211; 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>
<li>third-party library modules (anything installed in Python&#8217;s site-packages
directory) &#8211; e.g. mx.DateTime, ZODB, PIL.Image, etc.</li>
<li>locally-developed modules</li>
</ol>
<p>Never use relative package imports.  If you&#8217;re writing code that&#8217;s 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>, do not just
write <tt class="docutils literal"><span class="pre">import</span> <span class="pre">m2</span></tt>, even though it&#8217;s legal.  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 module being initialized twice,
leading to confusing bugs.  See <span class="target" id="index-180"></span><a class="reference external" href="http://www.python.org/dev/peps/pep-0328"><strong>PEP 328</strong></a> for details.</p>
<p>It is sometimes necessary to move imports to a function or class to avoid
problems with circular imports.  Gordon McMillan says:</p>
<blockquote>
Circular imports are fine where both modules use the &#8220;import &lt;module&gt;&#8221; form
of import.  They fail when the 2nd module wants to grab a name out of the
first (&#8220;from module import name&#8221;) and the import is at the top level.  That&#8217;s
because names in the 1st are not yet available, because the first module is
busy importing the 2nd.</blockquote>
<p>In this case, if the second module is only used in one function, then the import
can easily be moved into that function.  By the time the import is called, the
first module will have finished initializing, and the second module can do its
import.</p>
<p>It may also be necessary to move imports out of the top level of code if some of
the modules are platform-specific.  In that case, it may not even be possible to
import all of the modules at the top of the file.  In this case, importing the
correct modules in the corresponding platform-specific code is a good option.</p>
<p>Only move imports into a local scope, such as inside a function definition, if
it&#8217;s necessary to solve a problem such as avoiding a circular import or are
trying to reduce the initialization time of a module.  This technique is
especially helpful if many of the imports are unnecessary depending on how the
program executes.  You may also want to move imports into a function if the
modules are only ever used in that function.  Note that loading a module the
first time may be expensive because of the one time initialization of the
module, but loading a module multiple times is virtually free, costing only a
couple of dictionary lookups.  Even if the module name has gone out of scope,
the module is probably available in <a title="sys.modules" class="reference external" href="../library/sys.html#sys.modules"><tt class="xref docutils literal"><span class="pre">sys.modules</span></tt></a>.</p>
<p>If only instances of a specific class use a module, then it is reasonable to
import the module in the class&#8217;s <tt class="docutils literal"><span class="pre">__init__</span></tt> method and then assign the module
to an instance variable so that the module is always available (via that
instance variable) during the life of the object.  Note that to delay an import
until the class is instantiated, the import must be inside a method.  Putting
the import inside the class but outside of any method still causes the import to
occur when the module is initialized.</p>
</div>
<div class="section" id="how-can-i-pass-optional-or-keyword-parameters-from-one-function-to-another">
<h3><a class="toc-backref" href="#id13">How can I pass optional or keyword parameters from one function to another?</a><a class="headerlink" href="#how-can-i-pass-optional-or-keyword-parameters-from-one-function-to-another" title="Permalink to this headline">¶</a></h3>
<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&#8217;s
parameter list; this gives you the positional arguments as a tuple and the
keyword arguments as a dictionary.  You can then pass these arguments when
calling another function by using <tt class="docutils literal"><span class="pre">*</span></tt> and <tt class="docutils literal"><span class="pre">**</span></tt>:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">def</span> <span class="nf">f</span><span class="p">(</span><span class="n">x</span><span class="p">,</span> <span class="o">*</span><span class="n">args</span><span class="p">,</span> <span class="o">**</span><span class="n">kwargs</span><span class="p">):</span>
    <span class="o">...</span>
    <span class="n">kwargs</span><span class="p">[</span><span class="s">&#39;width&#39;</span><span class="p">]</span> <span class="o">=</span> <span class="s">&#39;14.3c&#39;</span>
    <span class="o">...</span>
    <span class="n">g</span><span class="p">(</span><span class="n">x</span><span class="p">,</span> <span class="o">*</span><span class="n">args</span><span class="p">,</span> <span class="o">**</span><span class="n">kwargs</span><span class="p">)</span>
</pre></div>
</div>
<p>In the unlikely case that you care about Python versions older than 2.0, use
<a title="apply" class="reference external" href="../library/functions.html#apply"><tt class="xref docutils literal"><span class="pre">apply()</span></tt></a>:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">def</span> <span class="nf">f</span><span class="p">(</span><span class="n">x</span><span class="p">,</span> <span class="o">*</span><span class="n">args</span><span class="p">,</span> <span class="o">**</span><span class="n">kwargs</span><span class="p">):</span>
    <span class="o">...</span>
    <span class="n">kwargs</span><span class="p">[</span><span class="s">&#39;width&#39;</span><span class="p">]</span> <span class="o">=</span> <span class="s">&#39;14.3c&#39;</span>
    <span class="o">...</span>
    <span class="nb">apply</span><span class="p">(</span><span class="n">g</span><span class="p">,</span> <span class="p">(</span><span class="n">x</span><span class="p">,)</span><span class="o">+</span><span class="n">args</span><span class="p">,</span> <span class="n">kwargs</span><span class="p">)</span>
</pre></div>
</div>
</div>
<div class="section" id="how-do-i-write-a-function-with-output-parameters-call-by-reference">
<h3><a class="toc-backref" href="#id14">How do I write a function with output parameters (call by reference)?</a><a class="headerlink" href="#how-do-i-write-a-function-with-output-parameters-call-by-reference" title="Permalink to this headline">¶</a></h3>
<p>Remember that arguments are passed by assignment in Python.  Since assignment
just creates references to objects, there&#8217;s no alias between an argument name in
the caller and callee, and so no call-by-reference per se.  You can achieve the
desired effect in a number of ways.</p>
<ol class="arabic">
<li><p class="first">By returning a tuple of the results:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">def</span> <span class="nf">func2</span><span class="p">(</span><span class="n">a</span><span class="p">,</span> <span class="n">b</span><span class="p">):</span>
    <span class="n">a</span> <span class="o">=</span> <span class="s">&#39;new-value&#39;</span>        <span class="c"># a and b are local names</span>
    <span class="n">b</span> <span class="o">=</span> <span class="n">b</span> <span class="o">+</span> <span class="mi">1</span>              <span class="c"># assigned to new objects</span>
    <span class="k">return</span> <span class="n">a</span><span class="p">,</span> <span class="n">b</span>            <span class="c"># return new values</span>

<span class="n">x</span><span class="p">,</span> <span class="n">y</span> <span class="o">=</span> <span class="s">&#39;old-value&#39;</span><span class="p">,</span> <span class="mi">99</span>
<span class="n">x</span><span class="p">,</span> <span class="n">y</span> <span class="o">=</span> <span class="n">func2</span><span class="p">(</span><span class="n">x</span><span class="p">,</span> <span class="n">y</span><span class="p">)</span>
<span class="k">print</span> <span class="n">x</span><span class="p">,</span> <span class="n">y</span>                 <span class="c"># output: new-value 100</span>
</pre></div>
</div>
<p>This is almost always the clearest solution.</p>
</li>
<li><p class="first">By using global variables.  This isn&#8217;t thread-safe, and is not recommended.</p>
</li>
<li><p class="first">By passing a mutable (changeable in-place) object:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">def</span> <span class="nf">func1</span><span class="p">(</span><span class="n">a</span><span class="p">):</span>
    <span class="n">a</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span> <span class="o">=</span> <span class="s">&#39;new-value&#39;</span>     <span class="c"># &#39;a&#39; references a mutable list</span>
    <span class="n">a</span><span class="p">[</span><span class="mi">1</span><span class="p">]</span> <span class="o">=</span> <span class="n">a</span><span class="p">[</span><span class="mi">1</span><span class="p">]</span> <span class="o">+</span> <span class="mi">1</span>        <span class="c"># changes a shared object</span>

<span class="n">args</span> <span class="o">=</span> <span class="p">[</span><span class="s">&#39;old-value&#39;</span><span class="p">,</span> <span class="mi">99</span><span class="p">]</span>
<span class="n">func1</span><span class="p">(</span><span class="n">args</span><span class="p">)</span>
<span class="k">print</span> <span class="n">args</span><span class="p">[</span><span class="mi">0</span><span class="p">],</span> <span class="n">args</span><span class="p">[</span><span class="mi">1</span><span class="p">]</span>     <span class="c"># output: new-value 100</span>
</pre></div>
</div>
</li>
<li><p class="first">By passing in a dictionary that gets mutated:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">def</span> <span class="nf">func3</span><span class="p">(</span><span class="n">args</span><span class="p">):</span>
    <span class="n">args</span><span class="p">[</span><span class="s">&#39;a&#39;</span><span class="p">]</span> <span class="o">=</span> <span class="s">&#39;new-value&#39;</span>     <span class="c"># args is a mutable dictionary</span>
    <span class="n">args</span><span class="p">[</span><span class="s">&#39;b&#39;</span><span class="p">]</span> <span class="o">=</span> <span class="n">args</span><span class="p">[</span><span class="s">&#39;b&#39;</span><span class="p">]</span> <span class="o">+</span> <span class="mi">1</span>   <span class="c"># change it in-place</span>

<span class="n">args</span> <span class="o">=</span> <span class="p">{</span><span class="s">&#39;a&#39;</span><span class="p">:</span><span class="s">&#39; old-value&#39;</span><span class="p">,</span> <span class="s">&#39;b&#39;</span><span class="p">:</span> <span class="mi">99</span><span class="p">}</span>
<span class="n">func3</span><span class="p">(</span><span class="n">args</span><span class="p">)</span>
<span class="k">print</span> <span class="n">args</span><span class="p">[</span><span class="s">&#39;a&#39;</span><span class="p">],</span> <span class="n">args</span><span class="p">[</span><span class="s">&#39;b&#39;</span><span class="p">]</span>
</pre></div>
</div>
</li>
<li><p class="first">Or bundle up values in a class instance:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">class</span> <span class="nc">callByRef</span><span class="p">:</span>
    <span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="o">**</span><span class="n">args</span><span class="p">):</span>
        <span class="k">for</span> <span class="p">(</span><span class="n">key</span><span class="p">,</span> <span class="n">value</span><span class="p">)</span> <span class="ow">in</span> <span class="n">args</span><span class="o">.</span><span class="n">items</span><span class="p">():</span>
            <span class="nb">setattr</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">key</span><span class="p">,</span> <span class="n">value</span><span class="p">)</span>

<span class="k">def</span> <span class="nf">func4</span><span class="p">(</span><span class="n">args</span><span class="p">):</span>
    <span class="n">args</span><span class="o">.</span><span class="n">a</span> <span class="o">=</span> <span class="s">&#39;new-value&#39;</span>        <span class="c"># args is a mutable callByRef</span>
    <span class="n">args</span><span class="o">.</span><span class="n">b</span> <span class="o">=</span> <span class="n">args</span><span class="o">.</span><span class="n">b</span> <span class="o">+</span> <span class="mi">1</span>         <span class="c"># change object in-place</span>

<span class="n">args</span> <span class="o">=</span> <span class="n">callByRef</span><span class="p">(</span><span class="n">a</span><span class="o">=</span><span class="s">&#39;old-value&#39;</span><span class="p">,</span> <span class="n">b</span><span class="o">=</span><span class="mi">99</span><span class="p">)</span>
<span class="n">func4</span><span class="p">(</span><span class="n">args</span><span class="p">)</span>
<span class="k">print</span> <span class="n">args</span><span class="o">.</span><span class="n">a</span><span class="p">,</span> <span class="n">args</span><span class="o">.</span><span class="n">b</span>
</pre></div>
</div>
<p>There&#8217;s almost never a good reason to get this complicated.</p>
</li>
</ol>
<p>Your best choice is to return a tuple containing the multiple results.</p>
</div>
<div class="section" id="how-do-you-make-a-higher-order-function-in-python">
<h3><a class="toc-backref" href="#id15">How do you make a higher order function in Python?</a><a class="headerlink" href="#how-do-you-make-a-higher-order-function-in-python" title="Permalink to this headline">¶</a></h3>
<p>You have two choices: you can use nested scopes or you can use callable objects.
For example, suppose you wanted to define <tt class="docutils literal"><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 value <tt class="docutils literal"><span class="pre">a*x+b</span></tt>.  Using nested scopes:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">def</span> <span class="nf">linear</span><span class="p">(</span><span class="n">a</span><span class="p">,</span> <span class="n">b</span><span class="p">):</span>
    <span class="k">def</span> <span class="nf">result</span><span class="p">(</span><span class="n">x</span><span class="p">):</span>
        <span class="k">return</span> <span class="n">a</span> <span class="o">*</span> <span class="n">x</span> <span class="o">+</span> <span class="n">b</span>
    <span class="k">return</span> <span class="n">result</span>
</pre></div>
</div>
<p>Or using a callable object:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">class</span> <span class="nc">linear</span><span class="p">:</span>

    <span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">a</span><span class="p">,</span> <span class="n">b</span><span class="p">):</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">a</span><span class="p">,</span> <span class="bp">self</span><span class="o">.</span><span class="n">b</span> <span class="o">=</span> <span class="n">a</span><span class="p">,</span> <span class="n">b</span>

    <span class="k">def</span> <span class="nf">__call__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">x</span><span class="p">):</span>
        <span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">a</span> <span class="o">*</span> <span class="n">x</span> <span class="o">+</span> <span class="bp">self</span><span class="o">.</span><span class="n">b</span>
</pre></div>
</div>
<p>In both cases,</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">taxes</span> <span class="o">=</span> <span class="n">linear</span><span class="p">(</span><span class="mf">0.3</span><span class="p">,</span> <span class="mi">2</span><span class="p">)</span>
</pre></div>
</div>
<p>gives a callable object where <tt class="docutils literal"><span class="pre">taxes(10e6)</span> <span class="pre">==</span> <span class="pre">0.3</span> <span class="pre">*</span> <span class="pre">10e6</span> <span class="pre">+</span> <span class="pre">2</span></tt>.</p>
<p>The callable object approach has the disadvantage that it is a bit slower and
results in slightly longer code.  However, note that a collection of callables
can share their signature via inheritance:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">class</span> <span class="nc">exponential</span><span class="p">(</span><span class="n">linear</span><span class="p">):</span>
    <span class="c"># __init__ inherited</span>
    <span class="k">def</span> <span class="nf">__call__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">x</span><span class="p">):</span>
        <span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">a</span> <span class="o">*</span> <span class="p">(</span><span class="n">x</span> <span class="o">**</span> <span class="bp">self</span><span class="o">.</span><span class="n">b</span><span class="p">)</span>
</pre></div>
</div>
<p>Object can encapsulate state for several methods:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">class</span> <span class="nc">counter</span><span class="p">:</span>

    <span class="n">value</span> <span class="o">=</span> <span class="mi">0</span>

    <span class="k">def</span> <span class="nf">set</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">x</span><span class="p">):</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">value</span> <span class="o">=</span> <span class="n">x</span>

    <span class="k">def</span> <span class="nf">up</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">value</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">value</span> <span class="o">+</span> <span class="mi">1</span>

    <span class="k">def</span> <span class="nf">down</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">value</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">value</span> <span class="o">-</span> <span class="mi">1</span>

<span class="n">count</span> <span class="o">=</span> <span class="n">counter</span><span class="p">()</span>
<span class="n">inc</span><span class="p">,</span> <span class="n">dec</span><span class="p">,</span> <span class="n">reset</span> <span class="o">=</span> <span class="n">count</span><span class="o">.</span><span class="n">up</span><span class="p">,</span> <span class="n">count</span><span class="o">.</span><span class="n">down</span><span class="p">,</span> <span class="n">count</span><span class="o">.</span><span class="n">set</span>
</pre></div>
</div>
<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
same counting variable.</p>
</div>
<div class="section" id="how-do-i-copy-an-object-in-python">
<h3><a class="toc-backref" href="#id16">How do I copy an object in Python?</a><a class="headerlink" href="#how-do-i-copy-an-object-in-python" title="Permalink to this headline">¶</a></h3>
<p>In general, try <a title="copy.copy" class="reference external" href="../library/copy.html#copy.copy"><tt class="xref docutils literal"><span class="pre">copy.copy()</span></tt></a> or <a title="copy.deepcopy" class="reference external" href="../library/copy.html#copy.deepcopy"><tt class="xref docutils literal"><span class="pre">copy.deepcopy()</span></tt></a> for the general case.
Not all objects can be copied, but most can.</p>
<p>Some objects can be copied more easily.  Dictionaries have a <a title="dict.copy" class="reference external" href="../library/stdtypes.html#dict.copy"><tt class="xref docutils literal"><span class="pre">copy()</span></tt></a>
method:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">newdict</span> <span class="o">=</span> <span class="n">olddict</span><span class="o">.</span><span class="n">copy</span><span class="p">()</span>
</pre></div>
</div>
<p>Sequences can be copied by slicing:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">new_l</span> <span class="o">=</span> <span class="n">l</span><span class="p">[:]</span>
</pre></div>
</div>
</div>
<div class="section" id="how-can-i-find-the-methods-or-attributes-of-an-object">
<h3><a class="toc-backref" href="#id17">How can I find the methods or attributes of an object?</a><a class="headerlink" href="#how-can-i-find-the-methods-or-attributes-of-an-object" title="Permalink to this headline">¶</a></h3>
<p>For an instance x of a user-defined class, <tt class="docutils literal"><span class="pre">dir(x)</span></tt> returns an alphabetized
list of the names containing the instance attributes and methods and attributes
defined by its class.</p>
</div>
<div class="section" id="how-can-my-code-discover-the-name-of-an-object">
<h3><a class="toc-backref" href="#id18">How can my code discover the name of an object?</a><a class="headerlink" href="#how-can-my-code-discover-the-name-of-an-object" title="Permalink to this headline">¶</a></h3>
<p>Generally speaking, it can&#8217;t, because objects don&#8217;t really have names.
Essentially, assignment always binds a name to a value; The 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 value is a
callable. Consider the following code:</p>
<div class="highlight-python"><pre>class A:
    pass

B = A

a = B()
b = a
print b
&lt;__main__.A instance at 0x16D07CC&gt;
print a
&lt;__main__.A instance at 0x16D07CC&gt;</pre>
</div>
<p>Arguably the class has a name: even though it is bound to two names and invoked
through the name B the created instance is still reported as an instance of
class A.  However, it is impossible to say whether the instance&#8217;s name is a or
b, since both names are bound to the same value.</p>
<p>Generally speaking it should not be necessary for your code to &#8220;know the names&#8221;
of particular values. Unless you are deliberately writing introspective
programs, this is usually an indication that a change of approach might be
beneficial.</p>
<p>In comp.lang.python, Fredrik Lundh once gave an excellent analogy in answer to
this question:</p>
<blockquote>
<p>The same way as you get the name of that cat you found on your porch: the cat
(object) itself cannot tell you its name, and it doesn&#8217;t really care &#8211; so
the only way to find out what it&#8217;s called is to ask all your neighbours
(namespaces) if it&#8217;s their cat (object)...</p>
<p>....and don&#8217;t be surprised if you&#8217;ll find that it&#8217;s known by many names, or
no name at all!</p>
</blockquote>
</div>
<div class="section" id="what-s-up-with-the-comma-operator-s-precedence">
<h3><a class="toc-backref" href="#id19">What&#8217;s up with the comma operator&#8217;s precedence?</a><a class="headerlink" href="#what-s-up-with-the-comma-operator-s-precedence" title="Permalink to this headline">¶</a></h3>
<p>Comma is not an operator in Python.  Consider this session:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="s">&quot;a&quot;</span> <span class="ow">in</span> <span class="s">&quot;b&quot;</span><span class="p">,</span> <span class="s">&quot;a&quot;</span>
<span class="go">(False, &#39;a&#39;)</span>
</pre></div>
</div>
<p>Since the comma is not an operator, but a separator between expressions the
above is evaluated as if you had entered:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="p">(</span><span class="s">&quot;a&quot;</span> <span class="ow">in</span> <span class="s">&quot;b&quot;</span><span class="p">),</span> <span class="s">&quot;a&quot;</span>
</pre></div>
</div>
<p>not:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="s">&quot;a&quot;</span> <span class="ow">in</span> <span class="p">(</span><span class="s">&quot;b&quot;</span><span class="p">,</span> <span class="s">&quot;a&quot;</span><span class="p">)</span>
</pre></div>
</div>
<p>The same is true of the various assignment operators (<tt class="docutils literal"><span class="pre">=</span></tt>, <tt class="docutils literal"><span class="pre">+=</span></tt> etc).  They
are not truly operators but syntactic delimiters in assignment statements.</p>
</div>
<div class="section" id="is-there-an-equivalent-of-c-s-ternary-operator">
<h3><a class="toc-backref" href="#id20">Is there an equivalent of C&#8217;s &#8220;?:&#8221; ternary operator?</a><a class="headerlink" href="#is-there-an-equivalent-of-c-s-ternary-operator" title="Permalink to this headline">¶</a></h3>
<p>Yes, this feature was added in Python 2.5. The syntax would be as follows:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="p">[</span><span class="n">on_true</span><span class="p">]</span> <span class="k">if</span> <span class="p">[</span><span class="n">expression</span><span class="p">]</span> <span class="k">else</span> <span class="p">[</span><span class="n">on_false</span><span class="p">]</span>

<span class="n">x</span><span class="p">,</span> <span class="n">y</span> <span class="o">=</span> <span class="mi">50</span><span class="p">,</span> <span class="mi">25</span>

<span class="n">small</span> <span class="o">=</span> <span class="n">x</span> <span class="k">if</span> <span class="n">x</span> <span class="o">&lt;</span> <span class="n">y</span> <span class="k">else</span> <span class="n">y</span>
</pre></div>
</div>
<p>For versions previous to 2.5 the answer would be &#8216;No&#8217;.</p>
<p>In many cases you can mimic <tt class="docutils literal"><span class="pre">a</span> <span class="pre">?</span> <span class="pre">b</span> <span class="pre">:</span> <span class="pre">c</span></tt> with <tt class="docutils literal"><span class="pre">a</span> <span class="pre">and</span> <span class="pre">b</span> <span class="pre">or</span> <span class="pre">c</span></tt>, but there&#8217;s a
flaw: if <em>b</em> is zero (or empty, or <tt class="xref docutils literal"><span class="pre">None</span></tt> &#8211; anything that tests false) then
<em>c</em> will be selected instead.  In many cases you can prove by looking at the
code that this can&#8217;t happen (e.g. because <em>b</em> is a constant or has a type that
can never be false), but in general this can be a problem.</p>
<p>Tim Peters (who wishes it was Steve Majewski) suggested the following solution:
<tt class="docutils literal"><span class="pre">(a</span> <span class="pre">and</span> <span class="pre">[b]</span> <span class="pre">or</span> <span class="pre">[c])[0]</span></tt>.  Because <tt class="docutils literal"><span class="pre">[b]</span></tt> is a singleton list it is never
false, so the wrong path is never taken; then applying <tt class="docutils literal"><span class="pre">[0]</span></tt> to the whole
thing gets the <em>b</em> or <em>c</em> that you really wanted.  Ugly, but it gets you there
in the rare cases where it is really inconvenient to rewrite your code using
&#8216;if&#8217;.</p>
<p>The best course is usually to write a simple <tt class="docutils literal"><span class="pre">if...else</span></tt> statement.  Another
solution is to implement the <tt class="docutils literal"><span class="pre">?:</span></tt> operator as a function:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">def</span> <span class="nf">q</span><span class="p">(</span><span class="n">cond</span><span class="p">,</span> <span class="n">on_true</span><span class="p">,</span> <span class="n">on_false</span><span class="p">):</span>
    <span class="k">if</span> <span class="n">cond</span><span class="p">:</span>
        <span class="k">if</span> <span class="ow">not</span> <span class="n">isfunction</span><span class="p">(</span><span class="n">on_true</span><span class="p">):</span>
            <span class="k">return</span> <span class="n">on_true</span>
        <span class="k">else</span><span class="p">:</span>
            <span class="k">return</span> <span class="n">on_true</span><span class="p">()</span>
    <span class="k">else</span><span class="p">:</span>
        <span class="k">if</span> <span class="ow">not</span> <span class="n">isfunction</span><span class="p">(</span><span class="n">on_false</span><span class="p">):</span>
            <span class="k">return</span> <span class="n">on_false</span>
        <span class="k">else</span><span class="p">:</span>
            <span class="k">return</span> <span class="n">on_false</span><span class="p">()</span>
</pre></div>
</div>
<p>In most cases you&#8217;ll pass b and c directly: <tt class="docutils literal"><span class="pre">q(a,</span> <span class="pre">b,</span> <span class="pre">c)</span></tt>.  To avoid evaluating
b or c when they shouldn&#8217;t be, encapsulate them within a lambda function, e.g.:
<tt class="docutils literal"><span class="pre">q(a,</span> <span class="pre">lambda:</span> <span class="pre">b,</span> <span class="pre">lambda:</span> <span class="pre">c)</span></tt>.</p>
<p>It has been asked <em>why</em> Python has no if-then-else expression.  There are
several answers: many languages do just fine without one; it can easily lead to
less readable code; no sufficiently &#8220;Pythonic&#8221; syntax has been discovered; a
search of the standard library found remarkably few places where using an
if-then-else expression would make the code more understandable.</p>
<p>In 2002, <span class="target" id="index-181"></span><a class="reference external" href="http://www.python.org/dev/peps/pep-0308"><strong>PEP 308</strong></a> was written proposing several possible syntaxes and the
community was asked to vote on the issue.  The vote was inconclusive.  Most
people liked one of the syntaxes, but also hated other syntaxes; many votes
implied that people preferred no ternary operator rather than having a syntax
they hated.</p>
</div>
<div class="section" id="is-it-possible-to-write-obfuscated-one-liners-in-python">
<h3><a class="toc-backref" href="#id21">Is it possible to write obfuscated one-liners in Python?</a><a class="headerlink" href="#is-it-possible-to-write-obfuscated-one-liners-in-python" title="Permalink to this headline">¶</a></h3>
<p>Yes.  Usually this is done by nesting <a class="reference external" href="../reference/expressions.html#lambda"><tt class="xref docutils literal"><span class="pre">lambda</span></tt></a> within
<a class="reference external" href="../reference/expressions.html#lambda"><tt class="xref docutils literal"><span class="pre">lambda</span></tt></a>.  See the following three examples, due to Ulf Bartelt:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="c"># Primes &lt; 1000</span>
<span class="k">print</span> <span class="nb">filter</span><span class="p">(</span><span class="bp">None</span><span class="p">,</span><span class="nb">map</span><span class="p">(</span><span class="k">lambda</span> <span class="n">y</span><span class="p">:</span><span class="n">y</span><span class="o">*</span><span class="nb">reduce</span><span class="p">(</span><span class="k">lambda</span> <span class="n">x</span><span class="p">,</span><span class="n">y</span><span class="p">:</span><span class="n">x</span><span class="o">*</span><span class="n">y</span><span class="o">!=</span><span class="mi">0</span><span class="p">,</span>
<span class="nb">map</span><span class="p">(</span><span class="k">lambda</span> <span class="n">x</span><span class="p">,</span><span class="n">y</span><span class="o">=</span><span class="n">y</span><span class="p">:</span><span class="n">y</span><span class="o">%</span><span class="n">x</span><span class="p">,</span><span class="nb">range</span><span class="p">(</span><span class="mi">2</span><span class="p">,</span><span class="nb">int</span><span class="p">(</span><span class="nb">pow</span><span class="p">(</span><span class="n">y</span><span class="p">,</span><span class="mf">0.5</span><span class="p">)</span><span class="o">+</span><span class="mi">1</span><span class="p">))),</span><span class="mi">1</span><span class="p">),</span><span class="nb">range</span><span class="p">(</span><span class="mi">2</span><span class="p">,</span><span class="mi">1000</span><span class="p">)))</span>

<span class="c"># First 10 Fibonacci numbers</span>
<span class="k">print</span> <span class="nb">map</span><span class="p">(</span><span class="k">lambda</span> <span class="n">x</span><span class="p">,</span><span class="n">f</span><span class="o">=</span><span class="k">lambda</span> <span class="n">x</span><span class="p">,</span><span class="n">f</span><span class="p">:(</span><span class="n">f</span><span class="p">(</span><span class="n">x</span><span class="o">-</span><span class="mi">1</span><span class="p">,</span><span class="n">f</span><span class="p">)</span><span class="o">+</span><span class="n">f</span><span class="p">(</span><span class="n">x</span><span class="o">-</span><span class="mi">2</span><span class="p">,</span><span class="n">f</span><span class="p">))</span> <span class="k">if</span> <span class="n">x</span><span class="o">&gt;</span><span class="mi">1</span> <span class="k">else</span> <span class="mi">1</span><span class="p">:</span> <span class="n">f</span><span class="p">(</span><span class="n">x</span><span class="p">,</span><span class="n">f</span><span class="p">),</span>
<span class="nb">range</span><span class="p">(</span><span class="mi">10</span><span class="p">))</span>

<span class="c"># Mandelbrot set</span>
<span class="k">print</span> <span class="p">(</span><span class="k">lambda</span> <span class="n">Ru</span><span class="p">,</span><span class="n">Ro</span><span class="p">,</span><span class="n">Iu</span><span class="p">,</span><span class="n">Io</span><span class="p">,</span><span class="n">IM</span><span class="p">,</span><span class="n">Sx</span><span class="p">,</span><span class="n">Sy</span><span class="p">:</span><span class="nb">reduce</span><span class="p">(</span><span class="k">lambda</span> <span class="n">x</span><span class="p">,</span><span class="n">y</span><span class="p">:</span><span class="n">x</span><span class="o">+</span><span class="n">y</span><span class="p">,</span><span class="nb">map</span><span class="p">(</span><span class="k">lambda</span> <span class="n">y</span><span class="p">,</span>
<span class="n">Iu</span><span class="o">=</span><span class="n">Iu</span><span class="p">,</span><span class="n">Io</span><span class="o">=</span><span class="n">Io</span><span class="p">,</span><span class="n">Ru</span><span class="o">=</span><span class="n">Ru</span><span class="p">,</span><span class="n">Ro</span><span class="o">=</span><span class="n">Ro</span><span class="p">,</span><span class="n">Sy</span><span class="o">=</span><span class="n">Sy</span><span class="p">,</span><span class="n">L</span><span class="o">=</span><span class="k">lambda</span> <span class="n">yc</span><span class="p">,</span><span class="n">Iu</span><span class="o">=</span><span class="n">Iu</span><span class="p">,</span><span class="n">Io</span><span class="o">=</span><span class="n">Io</span><span class="p">,</span><span class="n">Ru</span><span class="o">=</span><span class="n">Ru</span><span class="p">,</span><span class="n">Ro</span><span class="o">=</span><span class="n">Ro</span><span class="p">,</span><span class="n">i</span><span class="o">=</span><span class="n">IM</span><span class="p">,</span>
<span class="n">Sx</span><span class="o">=</span><span class="n">Sx</span><span class="p">,</span><span class="n">Sy</span><span class="o">=</span><span class="n">Sy</span><span class="p">:</span><span class="nb">reduce</span><span class="p">(</span><span class="k">lambda</span> <span class="n">x</span><span class="p">,</span><span class="n">y</span><span class="p">:</span><span class="n">x</span><span class="o">+</span><span class="n">y</span><span class="p">,</span><span class="nb">map</span><span class="p">(</span><span class="k">lambda</span> <span class="n">x</span><span class="p">,</span><span class="n">xc</span><span class="o">=</span><span class="n">Ru</span><span class="p">,</span><span class="n">yc</span><span class="o">=</span><span class="n">yc</span><span class="p">,</span><span class="n">Ru</span><span class="o">=</span><span class="n">Ru</span><span class="p">,</span><span class="n">Ro</span><span class="o">=</span><span class="n">Ro</span><span class="p">,</span>
<span class="n">i</span><span class="o">=</span><span class="n">i</span><span class="p">,</span><span class="n">Sx</span><span class="o">=</span><span class="n">Sx</span><span class="p">,</span><span class="n">F</span><span class="o">=</span><span class="k">lambda</span> <span class="n">xc</span><span class="p">,</span><span class="n">yc</span><span class="p">,</span><span class="n">x</span><span class="p">,</span><span class="n">y</span><span class="p">,</span><span class="n">k</span><span class="p">,</span><span class="n">f</span><span class="o">=</span><span class="k">lambda</span> <span class="n">xc</span><span class="p">,</span><span class="n">yc</span><span class="p">,</span><span class="n">x</span><span class="p">,</span><span class="n">y</span><span class="p">,</span><span class="n">k</span><span class="p">,</span><span class="n">f</span><span class="p">:(</span><span class="n">k</span><span class="o">&lt;=</span><span class="mi">0</span><span class="p">)</span><span class="ow">or</span> <span class="p">(</span><span class="n">x</span><span class="o">*</span><span class="n">x</span><span class="o">+</span><span class="n">y</span><span class="o">*</span><span class="n">y</span>
<span class="o">&gt;=</span><span class="mf">4.0</span><span class="p">)</span> <span class="ow">or</span> <span class="mi">1</span><span class="o">+</span><span class="n">f</span><span class="p">(</span><span class="n">xc</span><span class="p">,</span><span class="n">yc</span><span class="p">,</span><span class="n">x</span><span class="o">*</span><span class="n">x</span><span class="o">-</span><span class="n">y</span><span class="o">*</span><span class="n">y</span><span class="o">+</span><span class="n">xc</span><span class="p">,</span><span class="mf">2.0</span><span class="o">*</span><span class="n">x</span><span class="o">*</span><span class="n">y</span><span class="o">+</span><span class="n">yc</span><span class="p">,</span><span class="n">k</span><span class="o">-</span><span class="mi">1</span><span class="p">,</span><span class="n">f</span><span class="p">):</span><span class="n">f</span><span class="p">(</span><span class="n">xc</span><span class="p">,</span><span class="n">yc</span><span class="p">,</span><span class="n">x</span><span class="p">,</span><span class="n">y</span><span class="p">,</span><span class="n">k</span><span class="p">,</span><span class="n">f</span><span class="p">):</span><span class="nb">chr</span><span class="p">(</span>
<span class="mi">64</span><span class="o">+</span><span class="n">F</span><span class="p">(</span><span class="n">Ru</span><span class="o">+</span><span class="n">x</span><span class="o">*</span><span class="p">(</span><span class="n">Ro</span><span class="o">-</span><span class="n">Ru</span><span class="p">)</span><span class="o">/</span><span class="n">Sx</span><span class="p">,</span><span class="n">yc</span><span class="p">,</span><span class="mi">0</span><span class="p">,</span><span class="mi">0</span><span class="p">,</span><span class="n">i</span><span class="p">)),</span><span class="nb">range</span><span class="p">(</span><span class="n">Sx</span><span class="p">))):</span><span class="n">L</span><span class="p">(</span><span class="n">Iu</span><span class="o">+</span><span class="n">y</span><span class="o">*</span><span class="p">(</span><span class="n">Io</span><span class="o">-</span><span class="n">Iu</span><span class="p">)</span><span class="o">/</span><span class="n">Sy</span><span class="p">),</span><span class="nb">range</span><span class="p">(</span><span class="n">Sy</span>
<span class="p">))))(</span><span class="o">-</span><span class="mf">2.1</span><span class="p">,</span> <span class="mf">0.7</span><span class="p">,</span> <span class="o">-</span><span class="mf">1.2</span><span class="p">,</span> <span class="mf">1.2</span><span class="p">,</span> <span class="mi">30</span><span class="p">,</span> <span class="mi">80</span><span class="p">,</span> <span class="mi">24</span><span class="p">)</span>
<span class="c">#    \___ ___/  \___ ___/  |   |   |__ lines on screen</span>
<span class="c">#        V          V      |   |______ columns on screen</span>
<span class="c">#        |          |      |__________ maximum of &quot;iterations&quot;</span>
<span class="c">#        |          |_________________ range on y axis</span>
<span class="c">#        |____________________________ range on x axis</span>
</pre></div>
</div>
<p>Don&#8217;t try this at home, kids!</p>
</div>
</div>
<div class="section" id="numbers-and-strings">
<h2><a class="toc-backref" href="#id22">Numbers and strings</a><a class="headerlink" href="#numbers-and-strings" title="Permalink to this headline">¶</a></h2>
<div class="section" id="how-do-i-specify-hexadecimal-and-octal-integers">
<h3><a class="toc-backref" href="#id23">How do I specify hexadecimal and octal integers?</a><a class="headerlink" href="#how-do-i-specify-hexadecimal-and-octal-integers" title="Permalink to this headline">¶</a></h3>
<p>To specify an octal digit, precede the octal value with a zero, and then a lower
or uppercase &#8220;o&#8221;.  For example, to set the variable &#8220;a&#8221; to the octal value &#8220;10&#8221;
(8 in decimal), type:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">a</span> <span class="o">=</span> <span class="mi">0</span><span class="n">o10</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">a</span>
<span class="go">8</span>
</pre></div>
</div>
<p>Hexadecimal is just as easy.  Simply precede the hexadecimal number with a zero,
and then a lower or uppercase &#8220;x&#8221;.  Hexadecimal digits can be specified in lower
or uppercase.  For example, in the Python interpreter:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">a</span> <span class="o">=</span> <span class="mh">0xa5</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">a</span>
<span class="go">165</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">b</span> <span class="o">=</span> <span class="mh">0XB2</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">b</span>
<span class="go">178</span>
</pre></div>
</div>
</div>
<div class="section" id="why-does-22-10-return-3">
<h3><a class="toc-backref" href="#id24">Why does -22 // 10 return -3?</a><a class="headerlink" href="#why-does-22-10-return-3" title="Permalink to this headline">¶</a></h3>
<p>It&#8217;s primarily driven by the desire that <tt class="docutils literal"><span class="pre">i</span> <span class="pre">%</span> <span class="pre">j</span></tt> have the same sign as <tt class="docutils literal"><span class="pre">j</span></tt>.
If you want that, and also want:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">i</span> <span class="o">==</span> <span class="p">(</span><span class="n">i</span> <span class="o">//</span> <span class="n">j</span><span class="p">)</span> <span class="o">*</span> <span class="n">j</span> <span class="o">+</span> <span class="p">(</span><span class="n">i</span> <span class="o">%</span> <span class="n">j</span><span class="p">)</span>
</pre></div>
</div>
<p>then integer division has to return the floor.  C also requires that identity to
hold, and then compilers that truncate <tt class="docutils literal"><span class="pre">i</span> <span class="pre">//</span> <span class="pre">j</span></tt> need to make <tt class="docutils literal"><span class="pre">i</span> <span class="pre">%</span> <span class="pre">j</span></tt> have
the same sign as <tt class="docutils literal"><span class="pre">i</span></tt>.</p>
<p>There are few real use cases for <tt class="docutils literal"><span class="pre">i</span> <span class="pre">%</span> <span class="pre">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>
is positive, there are many, and in virtually all of them it&#8217;s more useful for
<tt class="docutils literal"><span class="pre">i</span> <span class="pre">%</span> <span class="pre">j</span></tt> to be <tt class="docutils literal"><span class="pre">&gt;=</span> <span class="pre">0</span></tt>.  If the clock says 10 now, what did it say 200 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 waiting to
bite.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">On Python 2, <tt class="docutils literal"><span class="pre">a</span> <span class="pre">/</span> <span class="pre">b</span></tt> returns the same as <tt class="docutils literal"><span class="pre">a</span> <span class="pre">//</span> <span class="pre">b</span></tt> if
<tt class="docutils literal"><span class="pre">__future__.division</span></tt> is not in effect.  This is also known as &#8220;classic&#8221;
division.</p>
</div>
</div>
<div class="section" id="how-do-i-convert-a-string-to-a-number">
<h3><a class="toc-backref" href="#id25">How do I convert a string to a number?</a><a class="headerlink" href="#how-do-i-convert-a-string-to-a-number" title="Permalink to this headline">¶</a></h3>
<p>For integers, use the built-in <a title="int" class="reference external" href="../library/functions.html#int"><tt class="xref docutils literal"><span class="pre">int()</span></tt></a> type constructor, e.g. <tt class="docutils literal"><span class="pre">int('144')</span>
<span class="pre">==</span> <span class="pre">144</span></tt>.  Similarly, <a title="float" class="reference external" href="../library/functions.html#float"><tt class="xref docutils literal"><span class="pre">float()</span></tt></a> converts to 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>
<p>By default, these interpret the number as decimal, so that <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 <a title="exceptions.ValueError" class="reference external" href="../library/exceptions.html#exceptions.ValueError"><tt class="xref docutils literal"><span class="pre">ValueError</span></tt></a>. <tt class="docutils literal"><span class="pre">int(string,</span> <span class="pre">base)</span></tt> takes
the base to convert from 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 base is specified as 0, the number is interpreted using Python&#8217;s
rules: a leading &#8216;0&#8217; indicates octal, and &#8216;0x&#8217; indicates a hex number.</p>
<p>Do not use the built-in function <a title="eval" class="reference external" href="../library/functions.html#eval"><tt class="xref docutils literal"><span class="pre">eval()</span></tt></a> if all you need is to convert
strings to numbers.  <a title="eval" class="reference external" href="../library/functions.html#eval"><tt class="xref docutils literal"><span class="pre">eval()</span></tt></a> will be significantly slower and it presents a
security risk: someone could pass you a Python expression that might have
unwanted side effects.  For example, someone could pass
<tt class="docutils literal"><span class="pre">__import__('os').system(&quot;rm</span> <span class="pre">-rf</span> <span class="pre">$HOME&quot;)</span></tt> which would erase your home
directory.</p>
<p><a title="eval" class="reference external" href="../library/functions.html#eval"><tt class="xref docutils literal"><span class="pre">eval()</span></tt></a> also has the effect of interpreting numbers as Python expressions,
so that e.g. <tt class="docutils literal"><span class="pre">eval('09')</span></tt> gives a syntax error because Python regards numbers
starting with &#8216;0&#8217; as octal (base 8).</p>
</div>
<div class="section" id="how-do-i-convert-a-number-to-a-string">
<h3><a class="toc-backref" href="#id26">How do I convert a number to a string?</a><a class="headerlink" href="#how-do-i-convert-a-number-to-a-string" title="Permalink to this headline">¶</a></h3>
<p>To convert, e.g., the number 144 to the string &#8216;144&#8217;, use the built-in type
constructor <a title="str" class="reference external" href="../library/functions.html#str"><tt class="xref docutils literal"><span class="pre">str()</span></tt></a>.  If you want a hexadecimal or octal representation, use
the built-in functions <a title="hex" class="reference external" href="../library/functions.html#hex"><tt class="xref docutils literal"><span class="pre">hex()</span></tt></a> or <a title="oct" class="reference external" href="../library/functions.html#oct"><tt class="xref docutils literal"><span class="pre">oct()</span></tt></a>.  For fancy formatting, see
the <a class="reference external" href="../library/string.html#formatstrings"><em>Format String Syntax</em></a> section, e.g. <tt class="docutils literal"><span class="pre">&quot;{:04d}&quot;.format(144)</span></tt> yields
<tt class="docutils literal"><span class="pre">'0144'</span></tt> and <tt class="docutils literal"><span class="pre">&quot;{:.3f}&quot;.format(1/3)</span></tt> yields <tt class="docutils literal"><span class="pre">'0.333'</span></tt>.  You may also use
<a class="reference external" href="../library/stdtypes.html#string-formatting"><em>the % operator</em></a> on strings.  See the library reference
manual for details.</p>
</div>
<div class="section" id="how-do-i-modify-a-string-in-place">
<h3><a class="toc-backref" href="#id27">How do I modify a string in place?</a><a class="headerlink" href="#how-do-i-modify-a-string-in-place" title="Permalink to this headline">¶</a></h3>
<p>You can&#8217;t, because strings are immutable.  If you need an object with this
ability, try converting the string to a list or use the array module:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">s</span> <span class="o">=</span> <span class="s">&quot;Hello, world&quot;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">a</span> <span class="o">=</span> <span class="nb">list</span><span class="p">(</span><span class="n">s</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">print</span> <span class="n">a</span>
<span class="go">[&#39;H&#39;, &#39;e&#39;, &#39;l&#39;, &#39;l&#39;, &#39;o&#39;, &#39;,&#39;, &#39; &#39;, &#39;w&#39;, &#39;o&#39;, &#39;r&#39;, &#39;l&#39;, &#39;d&#39;]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">a</span><span class="p">[</span><span class="mi">7</span><span class="p">:]</span> <span class="o">=</span> <span class="nb">list</span><span class="p">(</span><span class="s">&quot;there!&quot;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="s">&#39;&#39;</span><span class="o">.</span><span class="n">join</span><span class="p">(</span><span class="n">a</span><span class="p">)</span>
<span class="go">&#39;Hello, there!&#39;</span>

<span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">array</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">a</span> <span class="o">=</span> <span class="n">array</span><span class="o">.</span><span class="n">array</span><span class="p">(</span><span class="s">&#39;c&#39;</span><span class="p">,</span> <span class="n">s</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">print</span> <span class="n">a</span>
<span class="go">array(&#39;c&#39;, &#39;Hello, world&#39;)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">a</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span> <span class="o">=</span> <span class="s">&#39;y&#39;</span> <span class="p">;</span> <span class="k">print</span> <span class="n">a</span>
<span class="go">array(&#39;c&#39;, &#39;yello world&#39;)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">a</span><span class="o">.</span><span class="n">tostring</span><span class="p">()</span>
<span class="go">&#39;yello, world&#39;</span>
</pre></div>
</div>
</div>
<div class="section" id="how-do-i-use-strings-to-call-functions-methods">
<h3><a class="toc-backref" href="#id28">How do I use strings to call functions/methods?</a><a class="headerlink" href="#how-do-i-use-strings-to-call-functions-methods" title="Permalink to this headline">¶</a></h3>
<p>There are various techniques.</p>
<ul>
<li><p class="first">The best is to use a dictionary that maps strings to functions.  The primary
advantage of this technique is that the strings do not need to match the names
of the functions.  This is also the primary technique used to emulate a case
construct:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">def</span> <span class="nf">a</span><span class="p">():</span>
    <span class="k">pass</span>

<span class="k">def</span> <span class="nf">b</span><span class="p">():</span>
    <span class="k">pass</span>

<span class="n">dispatch</span> <span class="o">=</span> <span class="p">{</span><span class="s">&#39;go&#39;</span><span class="p">:</span> <span class="n">a</span><span class="p">,</span> <span class="s">&#39;stop&#39;</span><span class="p">:</span> <span class="n">b</span><span class="p">}</span>  <span class="c"># Note lack of parens for funcs</span>

<span class="n">dispatch</span><span class="p">[</span><span class="n">get_input</span><span class="p">()]()</span>  <span class="c"># Note trailing parens to call function</span>
</pre></div>
</div>
</li>
<li><p class="first">Use the built-in function <a title="getattr" class="reference external" href="../library/functions.html#getattr"><tt class="xref docutils literal"><span class="pre">getattr()</span></tt></a>:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="kn">import</span> <span class="nn">foo</span>
<span class="nb">getattr</span><span class="p">(</span><span class="n">foo</span><span class="p">,</span> <span class="s">&#39;bar&#39;</span><span class="p">)()</span>
</pre></div>
</div>
<p>Note that <a title="getattr" class="reference external" href="../library/functions.html#getattr"><tt class="xref docutils literal"><span class="pre">getattr()</span></tt></a> works on any object, including classes, class
instances, modules, and so on.</p>
<p>This is used in several places in the standard library, like this:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">class</span> <span class="nc">Foo</span><span class="p">:</span>
    <span class="k">def</span> <span class="nf">do_foo</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="o">...</span>

    <span class="k">def</span> <span class="nf">do_bar</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="o">...</span>

<span class="n">f</span> <span class="o">=</span> <span class="nb">getattr</span><span class="p">(</span><span class="n">foo_instance</span><span class="p">,</span> <span class="s">&#39;do_&#39;</span> <span class="o">+</span> <span class="n">opname</span><span class="p">)</span>
<span class="n">f</span><span class="p">()</span>
</pre></div>
</div>
</li>
<li><p class="first">Use <a title="locals" class="reference external" href="../library/functions.html#locals"><tt class="xref docutils literal"><span class="pre">locals()</span></tt></a> or <a title="eval" class="reference external" href="../library/functions.html#eval"><tt class="xref docutils literal"><span class="pre">eval()</span></tt></a> to resolve the function name:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">def</span> <span class="nf">myFunc</span><span class="p">():</span>
    <span class="k">print</span> <span class="s">&quot;hello&quot;</span>

<span class="n">fname</span> <span class="o">=</span> <span class="s">&quot;myFunc&quot;</span>

<span class="n">f</span> <span class="o">=</span> <span class="nb">locals</span><span class="p">()[</span><span class="n">fname</span><span class="p">]</span>
<span class="n">f</span><span class="p">()</span>

<span class="n">f</span> <span class="o">=</span> <span class="nb">eval</span><span class="p">(</span><span class="n">fname</span><span class="p">)</span>
<span class="n">f</span><span class="p">()</span>
</pre></div>
</div>
<p>Note: Using <a title="eval" class="reference external" href="../library/functions.html#eval"><tt class="xref docutils literal"><span class="pre">eval()</span></tt></a> is slow and dangerous.  If you don&#8217;t have absolute
control over the contents of the string, someone could pass a string that
resulted in an arbitrary function being executed.</p>
</li>
</ul>
</div>
<div class="section" id="is-there-an-equivalent-to-perl-s-chomp-for-removing-trailing-newlines-from-strings">
<h3><a class="toc-backref" href="#id29">Is there an equivalent to Perl&#8217;s chomp() for removing trailing newlines from strings?</a><a class="headerlink" href="#is-there-an-equivalent-to-perl-s-chomp-for-removing-trailing-newlines-from-strings" title="Permalink to this headline">¶</a></h3>
<p>Starting with Python 2.2, you can use <tt class="docutils literal"><span class="pre">S.rstrip(&quot;\r\n&quot;)</span></tt> to remove all
occurences of any line terminator from the end of the string <tt class="docutils literal"><span class="pre">S</span></tt> without
removing other trailing whitespace.  If the string <tt class="docutils literal"><span class="pre">S</span></tt> represents more than
one line, with several empty lines at the end, the line terminators for all the
blank lines will be removed:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">lines</span> <span class="o">=</span> <span class="p">(</span><span class="s">&quot;line 1 </span><span class="se">\r\n</span><span class="s">&quot;</span>
<span class="gp">... </span>         <span class="s">&quot;</span><span class="se">\r\n</span><span class="s">&quot;</span>
<span class="gp">... </span>         <span class="s">&quot;</span><span class="se">\r\n</span><span class="s">&quot;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">lines</span><span class="o">.</span><span class="n">rstrip</span><span class="p">(</span><span class="s">&quot;</span><span class="se">\n\r</span><span class="s">&quot;</span><span class="p">)</span>
<span class="go">&#39;line 1 &#39;</span>
</pre></div>
</div>
<p>Since this is typically only desired when reading text one line at a time, using
<tt class="docutils literal"><span class="pre">S.rstrip()</span></tt> this way works well.</p>
<p>For older versions of Python, there are two partial substitutes:</p>
<ul class="simple">
<li>If you want to remove all trailing whitespace, use the <tt class="docutils literal"><span class="pre">rstrip()</span></tt> method of
string objects.  This removes all trailing whitespace, not just a single
newline.</li>
<li>Otherwise, if there is only one line in the string <tt class="docutils literal"><span class="pre">S</span></tt>, use
<tt class="docutils literal"><span class="pre">S.splitlines()[0]</span></tt>.</li>
</ul>
</div>
<div class="section" id="is-there-a-scanf-or-sscanf-equivalent">
<h3><a class="toc-backref" href="#id30">Is there a scanf() or sscanf() equivalent?</a><a class="headerlink" href="#is-there-a-scanf-or-sscanf-equivalent" title="Permalink to this headline">¶</a></h3>
<p>Not as such.</p>
<p>For simple input parsing, the easiest approach is usually to split the line into
whitespace-delimited words using the <a title="str.split" class="reference external" href="../library/stdtypes.html#str.split"><tt class="xref docutils literal"><span class="pre">split()</span></tt></a> method of string objects
and then convert decimal strings to numeric values using <a title="int" class="reference external" href="../library/functions.html#int"><tt class="xref docutils literal"><span class="pre">int()</span></tt></a> or
<a title="float" class="reference external" href="../library/functions.html#float"><tt class="xref docutils literal"><span class="pre">float()</span></tt></a>.  <tt class="docutils literal"><span class="pre">split()</span></tt> supports an optional &#8220;sep&#8221; parameter which is useful
if the line uses something other than whitespace as a separator.</p>
<p>For more complicated input parsing, regular expressions more powerful than C&#8217;s
<tt class="xref docutils literal"><span class="pre">sscanf()</span></tt> and better suited for the task.</p>
</div>
<div class="section" id="what-does-unicodeerror-ascii-decoding-encoding-error-ordinal-not-in-range-128-mean">
<h3><a class="toc-backref" href="#id31">What does &#8216;UnicodeError: ASCII [decoding,encoding] error: ordinal not in range(128)&#8217; mean?</a><a class="headerlink" href="#what-does-unicodeerror-ascii-decoding-encoding-error-ordinal-not-in-range-128-mean" title="Permalink to this headline">¶</a></h3>
<p>This error indicates that your Python installation can handle only 7-bit ASCII
strings.  There are a couple ways to fix or work around the problem.</p>
<p>If your programs must handle data in arbitrary character set encodings, the
environment the application runs in will generally identify the encoding of the
data it is handing you.  You need to convert the input to Unicode data using
that encoding.  For example, a program that handles email or web input will
typically find character set encoding information in Content-Type headers.  This
can then be used to properly convert input data to Unicode. Assuming the string
referred to by <tt class="docutils literal"><span class="pre">value</span></tt> is encoded as UTF-8:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">value</span> <span class="o">=</span> <span class="nb">unicode</span><span class="p">(</span><span class="n">value</span><span class="p">,</span> <span class="s">&quot;utf-8&quot;</span><span class="p">)</span>
</pre></div>
</div>
<p>will return a Unicode object.  If the data is not correctly encoded as UTF-8,
the above call will raise a <a title="exceptions.UnicodeError" class="reference external" href="../library/exceptions.html#exceptions.UnicodeError"><tt class="xref docutils literal"><span class="pre">UnicodeError</span></tt></a> exception.</p>
<p>If you only want strings converted to Unicode which have non-ASCII data, you can
try converting them first assuming an ASCII encoding, and then generate Unicode
objects if that fails:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">try</span><span class="p">:</span>
    <span class="n">x</span> <span class="o">=</span> <span class="nb">unicode</span><span class="p">(</span><span class="n">value</span><span class="p">,</span> <span class="s">&quot;ascii&quot;</span><span class="p">)</span>
<span class="k">except</span> <span class="ne">UnicodeError</span><span class="p">:</span>
    <span class="n">value</span> <span class="o">=</span> <span class="nb">unicode</span><span class="p">(</span><span class="n">value</span><span class="p">,</span> <span class="s">&quot;utf-8&quot;</span><span class="p">)</span>
<span class="k">else</span><span class="p">:</span>
    <span class="c"># value was valid ASCII data</span>
    <span class="k">pass</span>
</pre></div>
</div>
<p>It&#8217;s possible to set a default encoding in a file called <tt class="docutils literal"><span class="pre">sitecustomize.py</span></tt>
that&#8217;s part of the Python library.  However, this isn&#8217;t recommended because
changing the Python-wide default encoding may cause third-party extension
modules to fail.</p>
<p>Note that on Windows, there is an encoding known as &#8220;mbcs&#8221;, which uses an
encoding specific to your current locale.  In many cases, and particularly when
working with COM, this may be an appropriate default encoding to use.</p>
</div>
</div>
<div class="section" id="sequences-tuples-lists">
<h2><a class="toc-backref" href="#id32">Sequences (Tuples/Lists)</a><a class="headerlink" href="#sequences-tuples-lists" title="Permalink to this headline">¶</a></h2>
<div class="section" id="how-do-i-convert-between-tuples-and-lists">
<h3><a class="toc-backref" href="#id33">How do I convert between tuples and lists?</a><a class="headerlink" href="#how-do-i-convert-between-tuples-and-lists" title="Permalink to this headline">¶</a></h3>
<p>The type constructor <tt class="docutils literal"><span class="pre">tuple(seq)</span></tt> converts any sequence (actually, any
iterable) into a tuple with the same items in the same order.</p>
<p>For example, <tt class="docutils literal"><span class="pre">tuple([1,</span> <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>
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 tuple, it does not make a copy
but returns the same object, so it is cheap to call <a title="tuple" class="reference external" href="../library/functions.html#tuple"><tt class="xref docutils literal"><span class="pre">tuple()</span></tt></a> when you
aren&#8217;t sure that an object is already a tuple.</p>
<p>The type constructor <tt class="docutils literal"><span class="pre">list(seq)</span></tt> converts any sequence or iterable into a list
with the same items in the same order.  For example, <tt class="docutils literal"><span class="pre">list((1,</span> <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> 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, it makes a copy just like <tt class="docutils literal"><span class="pre">seq[:]</span></tt> would.</p>
</div>
<div class="section" id="what-s-a-negative-index">
<h3><a class="toc-backref" href="#id34">What&#8217;s a negative index?</a><a class="headerlink" href="#what-s-a-negative-index" title="Permalink to this headline">¶</a></h3>
<p>Python sequences are indexed with positive numbers and negative numbers.  For
positive numbers 0 is the first index 1 is the second index and so forth.  For
negative indices -1 is the last index and -2 is the penultimate (next to last)
index and so forth.  Think of <tt class="docutils literal"><span class="pre">seq[-n]</span></tt> as the same as <tt class="docutils literal"><span class="pre">seq[len(seq)-n]</span></tt>.</p>
<p>Using negative indices can be very convenient.  For example <tt class="docutils literal"><span class="pre">S[:-1]</span></tt> is all of
the string except for its last character, which is useful for removing the
trailing newline from a string.</p>
</div>
<div class="section" id="how-do-i-iterate-over-a-sequence-in-reverse-order">
<h3><a class="toc-backref" href="#id35">How do I iterate over a sequence in reverse order?</a><a class="headerlink" href="#how-do-i-iterate-over-a-sequence-in-reverse-order" title="Permalink to this headline">¶</a></h3>
<p>Use the <a title="reversed" class="reference external" href="../library/functions.html#reversed"><tt class="xref docutils literal"><span class="pre">reversed()</span></tt></a> built-in function, which is new in Python 2.4:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">for</span> <span class="n">x</span> <span class="ow">in</span> <span class="nb">reversed</span><span class="p">(</span><span class="n">sequence</span><span class="p">):</span>
    <span class="o">...</span> <span class="c"># do something with x...</span>
</pre></div>
</div>
<p>This won&#8217;t touch your original sequence, but build a new copy with reversed
order to iterate over.</p>
<p>With Python 2.3, you can use an extended slice syntax:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">for</span> <span class="n">x</span> <span class="ow">in</span> <span class="n">sequence</span><span class="p">[::</span><span class="o">-</span><span class="mi">1</span><span class="p">]:</span>
    <span class="o">...</span> <span class="c"># do something with x...</span>
</pre></div>
</div>
</div>
<div class="section" id="how-do-you-remove-duplicates-from-a-list">
<h3><a class="toc-backref" href="#id36">How do you remove duplicates from a list?</a><a class="headerlink" href="#how-do-you-remove-duplicates-from-a-list" title="Permalink to this headline">¶</a></h3>
<p>See the Python Cookbook for a long discussion of many ways to do this:</p>
<blockquote>
<a class="reference external" href="http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52560">http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52560</a></blockquote>
<p>If you don&#8217;t mind reordering the list, sort it and then scan from the end of the
list, deleting duplicates as you go:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">if</span> <span class="n">mylist</span><span class="p">:</span>
    <span class="n">mylist</span><span class="o">.</span><span class="n">sort</span><span class="p">()</span>
    <span class="n">last</span> <span class="o">=</span> <span class="n">mylist</span><span class="p">[</span><span class="o">-</span><span class="mi">1</span><span class="p">]</span>
    <span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="nb">len</span><span class="p">(</span><span class="n">mylist</span><span class="p">)</span><span class="o">-</span><span class="mi">2</span><span class="p">,</span> <span class="o">-</span><span class="mi">1</span><span class="p">,</span> <span class="o">-</span><span class="mi">1</span><span class="p">):</span>
        <span class="k">if</span> <span class="n">last</span> <span class="o">==</span> <span class="n">mylist</span><span class="p">[</span><span class="n">i</span><span class="p">]:</span>
            <span class="k">del</span> <span class="n">mylist</span><span class="p">[</span><span class="n">i</span><span class="p">]</span>
        <span class="k">else</span><span class="p">:</span>
            <span class="n">last</span> <span class="o">=</span> <span class="n">mylist</span><span class="p">[</span><span class="n">i</span><span class="p">]</span>
</pre></div>
</div>
<p>If all elements of the list may be used as dictionary keys (i.e. they are all
hashable) this is often faster</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">d</span> <span class="o">=</span> <span class="p">{}</span>
<span class="k">for</span> <span class="n">x</span> <span class="ow">in</span> <span class="n">mylist</span><span class="p">:</span>
    <span class="n">d</span><span class="p">[</span><span class="n">x</span><span class="p">]</span> <span class="o">=</span> <span class="mi">1</span>
<span class="n">mylist</span> <span class="o">=</span> <span class="nb">list</span><span class="p">(</span><span class="n">d</span><span class="o">.</span><span class="n">keys</span><span class="p">())</span>
</pre></div>
</div>
<p>In Python 2.5 and later, the following is possible instead:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">mylist</span> <span class="o">=</span> <span class="nb">list</span><span class="p">(</span><span class="nb">set</span><span class="p">(</span><span class="n">mylist</span><span class="p">))</span>
</pre></div>
</div>
<p>This converts the list into a set, thereby removing duplicates, and then back
into a list.</p>
</div>
<div class="section" id="how-do-you-make-an-array-in-python">
<h3><a class="toc-backref" href="#id37">How do you make an array in Python?</a><a class="headerlink" href="#how-do-you-make-an-array-in-python" title="Permalink to this headline">¶</a></h3>
<p>Use a list:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="p">[</span><span class="s">&quot;this&quot;</span><span class="p">,</span> <span class="mi">1</span><span class="p">,</span> <span class="s">&quot;is&quot;</span><span class="p">,</span> <span class="s">&quot;an&quot;</span><span class="p">,</span> <span class="s">&quot;array&quot;</span><span class="p">]</span>
</pre></div>
</div>
<p>Lists are equivalent to C or Pascal arrays in their time complexity; the primary
difference is that a Python list can contain objects of many different types.</p>
<p>The <tt class="docutils literal"><span class="pre">array</span></tt> module also provides methods for creating arrays of fixed types
with compact representations, but they are slower to index than lists.  Also
note that the Numeric extensions and others define array-like structures with
various characteristics as well.</p>
<p>To get Lisp-style linked lists, you can emulate cons cells using tuples:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">lisp_list</span> <span class="o">=</span> <span class="p">(</span><span class="s">&quot;like&quot;</span><span class="p">,</span>  <span class="p">(</span><span class="s">&quot;this&quot;</span><span class="p">,</span>  <span class="p">(</span><span class="s">&quot;example&quot;</span><span class="p">,</span> <span class="bp">None</span><span class="p">)</span> <span class="p">)</span> <span class="p">)</span>
</pre></div>
</div>
<p>If mutability is desired, you could use lists instead of tuples.  Here the
analogue of lisp car is <tt class="docutils literal"><span class="pre">lisp_list[0]</span></tt> and the analogue of cdr is
<tt class="docutils literal"><span class="pre">lisp_list[1]</span></tt>.  Only do this if you&#8217;re sure you really need to, because it&#8217;s
usually a lot slower than using Python lists.</p>
</div>
<div class="section" id="how-do-i-create-a-multidimensional-list">
<h3><a class="toc-backref" href="#id38">How do I create a multidimensional list?</a><a class="headerlink" href="#how-do-i-create-a-multidimensional-list" title="Permalink to this headline">¶</a></h3>
<p>You probably tried to make a multidimensional array like this:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">A</span> <span class="o">=</span> <span class="p">[[</span><span class="bp">None</span><span class="p">]</span> <span class="o">*</span> <span class="mi">2</span><span class="p">]</span> <span class="o">*</span> <span class="mi">3</span>
</pre></div>
</div>
<p>This looks correct if you print it:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">A</span>
<span class="go">[[None, None], [None, None], [None, None]]</span>
</pre></div>
</div>
<p>But when you assign a value, it shows up in multiple places:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">A</span><span class="p">[</span><span class="mi">0</span><span class="p">][</span><span class="mi">0</span><span class="p">]</span> <span class="o">=</span> <span class="mi">5</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">A</span>
<span class="go">[[5, None], [5, None], [5, None]]</span>
</pre></div>
</div>
<p>The reason is that replicating a list with <tt class="docutils literal"><span class="pre">*</span></tt> doesn&#8217;t create copies, it only
creates references to the existing objects.  The <tt class="docutils literal"><span class="pre">*3</span></tt> creates a list
containing 3 references to the same list of length two.  Changes to one row will
show in all rows, which is almost certainly not what you want.</p>
<p>The suggested approach is to create a list of the desired length first and then
fill in each element with a newly created list:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">A</span> <span class="o">=</span> <span class="p">[</span><span class="bp">None</span><span class="p">]</span> <span class="o">*</span> <span class="mi">3</span>
<span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">3</span><span class="p">):</span>
    <span class="n">A</span><span class="p">[</span><span class="n">i</span><span class="p">]</span> <span class="o">=</span> <span class="p">[</span><span class="bp">None</span><span class="p">]</span> <span class="o">*</span> <span class="mi">2</span>
</pre></div>
</div>
<p>This generates a list containing 3 different lists of length two.  You can also
use a list comprehension:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">w</span><span class="p">,</span> <span class="n">h</span> <span class="o">=</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span>
<span class="n">A</span> <span class="o">=</span> <span class="p">[[</span><span class="bp">None</span><span class="p">]</span> <span class="o">*</span> <span class="n">w</span> <span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="n">h</span><span class="p">)]</span>
</pre></div>
</div>
<p>Or, you can use an extension that provides a matrix datatype; <a class="reference external" href="http://numpy.scipy.org/">Numeric Python</a> is the best known.</p>
</div>
<div class="section" id="how-do-i-apply-a-method-to-a-sequence-of-objects">
<h3><a class="toc-backref" href="#id39">How do I apply a method to a sequence of objects?</a><a class="headerlink" href="#how-do-i-apply-a-method-to-a-sequence-of-objects" title="Permalink to this headline">¶</a></h3>
<p>Use a list comprehension:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">result</span> <span class="o">=</span> <span class="p">[</span><span class="n">obj</span><span class="o">.</span><span class="n">method</span><span class="p">()</span> <span class="k">for</span> <span class="n">obj</span> <span class="ow">in</span> <span class="n">mylist</span><span class="p">]</span>
</pre></div>
</div>
<p>More generically, you can try the following function:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">def</span> <span class="nf">method_map</span><span class="p">(</span><span class="n">objects</span><span class="p">,</span> <span class="n">method</span><span class="p">,</span> <span class="n">arguments</span><span class="p">):</span>
    <span class="sd">&quot;&quot;&quot;method_map([a,b], &quot;meth&quot;, (1,2)) gives [a.meth(1,2), b.meth(1,2)]&quot;&quot;&quot;</span>
    <span class="n">nobjects</span> <span class="o">=</span> <span class="nb">len</span><span class="p">(</span><span class="n">objects</span><span class="p">)</span>
    <span class="n">methods</span> <span class="o">=</span> <span class="nb">map</span><span class="p">(</span><span class="nb">getattr</span><span class="p">,</span> <span class="n">objects</span><span class="p">,</span> <span class="p">[</span><span class="n">method</span><span class="p">]</span><span class="o">*</span><span class="n">nobjects</span><span class="p">)</span>
    <span class="k">return</span> <span class="nb">map</span><span class="p">(</span><span class="nb">apply</span><span class="p">,</span> <span class="n">methods</span><span class="p">,</span> <span class="p">[</span><span class="n">arguments</span><span class="p">]</span><span class="o">*</span><span class="n">nobjects</span><span class="p">)</span>
</pre></div>
</div>
</div>
</div>
<div class="section" id="dictionaries">
<h2><a class="toc-backref" href="#id40">Dictionaries</a><a class="headerlink" href="#dictionaries" title="Permalink to this headline">¶</a></h2>
<div class="section" id="how-can-i-get-a-dictionary-to-display-its-keys-in-a-consistent-order">
<h3><a class="toc-backref" href="#id41">How can I get a dictionary to display its keys in a consistent order?</a><a class="headerlink" href="#how-can-i-get-a-dictionary-to-display-its-keys-in-a-consistent-order" title="Permalink to this headline">¶</a></h3>
<p>You can&#8217;t.  Dictionaries store their keys in an unpredictable order, so the
display order of a dictionary&#8217;s elements will be similarly unpredictable.</p>
<p>This can be frustrating if you want to save a printable version to a file, make
some changes and then compare it with some other printed dictionary.  In this
case, use the <tt class="docutils literal"><span class="pre">pprint</span></tt> module to pretty-print the dictionary; the items will
be presented in order sorted by the key.</p>
<p>A more complicated solution is to subclass <tt class="docutils literal"><span class="pre">dict</span></tt> to create a
<tt class="docutils literal"><span class="pre">SortedDict</span></tt> class that prints itself in a predictable order.  Here&#8217;s one
simpleminded implementation of such a class:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">class</span> <span class="nc">SortedDict</span><span class="p">(</span><span class="nb">dict</span><span class="p">):</span>
    <span class="k">def</span> <span class="nf">__repr__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="n">keys</span> <span class="o">=</span> <span class="nb">sorted</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">keys</span><span class="p">())</span>
        <span class="n">result</span> <span class="o">=</span> <span class="p">(</span><span class="s">&quot;{!r}: {!r}&quot;</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="n">k</span><span class="p">,</span> <span class="bp">self</span><span class="p">[</span><span class="n">k</span><span class="p">])</span> <span class="k">for</span> <span class="n">k</span> <span class="ow">in</span> <span class="n">keys</span><span class="p">)</span>
        <span class="k">return</span> <span class="s">&quot;{{{}}}&quot;</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="s">&quot;, &quot;</span><span class="o">.</span><span class="n">join</span><span class="p">(</span><span class="n">result</span><span class="p">))</span>

    <span class="n">__str__</span> <span class="o">=</span> <span class="n">__repr__</span>
</pre></div>
</div>
<p>This will work for many common situations you might encounter, though it&#8217;s far
from a perfect solution. The largest flaw is that if some values in the
dictionary are also dictionaries, their values won&#8217;t be presented in any
particular order.</p>
</div>
<div class="section" id="i-want-to-do-a-complicated-sort-can-you-do-a-schwartzian-transform-in-python">
<h3><a class="toc-backref" href="#id42">I want to do a complicated sort: can you do a Schwartzian Transform in Python?</a><a class="headerlink" href="#i-want-to-do-a-complicated-sort-can-you-do-a-schwartzian-transform-in-python" title="Permalink to this headline">¶</a></h3>
<p>The technique, attributed to Randal Schwartz of the Perl community, sorts the
elements of a list by a metric which maps each element to its &#8220;sort value&#8221;. In
Python, just use the <tt class="docutils literal"><span class="pre">key</span></tt> argument for the <tt class="docutils literal"><span class="pre">sort()</span></tt> method:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">Isorted</span> <span class="o">=</span> <span class="n">L</span><span class="p">[:]</span>
<span class="n">Isorted</span><span class="o">.</span><span class="n">sort</span><span class="p">(</span><span class="n">key</span><span class="o">=</span><span class="k">lambda</span> <span class="n">s</span><span class="p">:</span> <span class="nb">int</span><span class="p">(</span><span class="n">s</span><span class="p">[</span><span class="mi">10</span><span class="p">:</span><span class="mi">15</span><span class="p">]))</span>
</pre></div>
</div>
<p>The <tt class="docutils literal"><span class="pre">key</span></tt> argument is new in Python 2.4, for older versions this kind of
sorting is quite simple to do with list comprehensions.  To sort a list of
strings by their uppercase values:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">tmp1</span> <span class="o">=</span> <span class="p">[(</span><span class="n">x</span><span class="o">.</span><span class="n">upper</span><span class="p">(),</span> <span class="n">x</span><span class="p">)</span> <span class="k">for</span> <span class="n">x</span> <span class="ow">in</span> <span class="n">L</span><span class="p">]</span>  <span class="c"># Schwartzian transform</span>
<span class="n">tmp1</span><span class="o">.</span><span class="n">sort</span><span class="p">()</span>
<span class="n">Usorted</span> <span class="o">=</span> <span class="p">[</span><span class="n">x</span><span class="p">[</span><span class="mi">1</span><span class="p">]</span> <span class="k">for</span> <span class="n">x</span> <span class="ow">in</span> <span class="n">tmp1</span><span class="p">]</span>
</pre></div>
</div>
<p>To sort by the integer value of a subfield extending from positions 10-15 in
each string:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">tmp2</span> <span class="o">=</span> <span class="p">[(</span><span class="nb">int</span><span class="p">(</span><span class="n">s</span><span class="p">[</span><span class="mi">10</span><span class="p">:</span><span class="mi">15</span><span class="p">]),</span> <span class="n">s</span><span class="p">)</span> <span class="k">for</span> <span class="n">s</span> <span class="ow">in</span> <span class="n">L</span><span class="p">]</span>  <span class="c"># Schwartzian transform</span>
<span class="n">tmp2</span><span class="o">.</span><span class="n">sort</span><span class="p">()</span>
<span class="n">Isorted</span> <span class="o">=</span> <span class="p">[</span><span class="n">x</span><span class="p">[</span><span class="mi">1</span><span class="p">]</span> <span class="k">for</span> <span class="n">x</span> <span class="ow">in</span> <span class="n">tmp2</span><span class="p">]</span>
</pre></div>
</div>
<p>Note that Isorted may also be computed by</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">def</span> <span class="nf">intfield</span><span class="p">(</span><span class="n">s</span><span class="p">):</span>
    <span class="k">return</span> <span class="nb">int</span><span class="p">(</span><span class="n">s</span><span class="p">[</span><span class="mi">10</span><span class="p">:</span><span class="mi">15</span><span class="p">])</span>

<span class="k">def</span> <span class="nf">Icmp</span><span class="p">(</span><span class="n">s1</span><span class="p">,</span> <span class="n">s2</span><span class="p">):</span>
    <span class="k">return</span> <span class="nb">cmp</span><span class="p">(</span><span class="n">intfield</span><span class="p">(</span><span class="n">s1</span><span class="p">),</span> <span class="n">intfield</span><span class="p">(</span><span class="n">s2</span><span class="p">))</span>

<span class="n">Isorted</span> <span class="o">=</span> <span class="n">L</span><span class="p">[:]</span>
<span class="n">Isorted</span><span class="o">.</span><span class="n">sort</span><span class="p">(</span><span class="n">Icmp</span><span class="p">)</span>
</pre></div>
</div>
<p>but since this method calls <tt class="docutils literal"><span class="pre">intfield()</span></tt> many times for each element of L, it
is slower than the Schwartzian Transform.</p>
</div>
<div class="section" id="how-can-i-sort-one-list-by-values-from-another-list">
<h3><a class="toc-backref" href="#id43">How can I sort one list by values from another list?</a><a class="headerlink" href="#how-can-i-sort-one-list-by-values-from-another-list" title="Permalink to this headline">¶</a></h3>
<p>Merge them into a single list of tuples, sort the resulting list, and then pick
out the element you want.</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">list1</span> <span class="o">=</span> <span class="p">[</span><span class="s">&quot;what&quot;</span><span class="p">,</span> <span class="s">&quot;I&#39;m&quot;</span><span class="p">,</span> <span class="s">&quot;sorting&quot;</span><span class="p">,</span> <span class="s">&quot;by&quot;</span><span class="p">]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">list2</span> <span class="o">=</span> <span class="p">[</span><span class="s">&quot;something&quot;</span><span class="p">,</span> <span class="s">&quot;else&quot;</span><span class="p">,</span> <span class="s">&quot;to&quot;</span><span class="p">,</span> <span class="s">&quot;sort&quot;</span><span class="p">]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">pairs</span> <span class="o">=</span> <span class="nb">zip</span><span class="p">(</span><span class="n">list1</span><span class="p">,</span> <span class="n">list2</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">pairs</span>
<span class="go">[(&#39;what&#39;, &#39;something&#39;), (&quot;I&#39;m&quot;, &#39;else&#39;), (&#39;sorting&#39;, &#39;to&#39;), (&#39;by&#39;, &#39;sort&#39;)]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">pairs</span><span class="o">.</span><span class="n">sort</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">result</span> <span class="o">=</span> <span class="p">[</span> <span class="n">x</span><span class="p">[</span><span class="mi">1</span><span class="p">]</span> <span class="k">for</span> <span class="n">x</span> <span class="ow">in</span> <span class="n">pairs</span> <span class="p">]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">result</span>
<span class="go">[&#39;else&#39;, &#39;sort&#39;, &#39;to&#39;, &#39;something&#39;]</span>
</pre></div>
</div>
<p>An alternative for the last step is:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">result</span> <span class="o">=</span> <span class="p">[]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">for</span> <span class="n">p</span> <span class="ow">in</span> <span class="n">pairs</span><span class="p">:</span> <span class="n">result</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">p</span><span class="p">[</span><span class="mi">1</span><span class="p">])</span>
</pre></div>
</div>
<p>If you find this more legible, you might prefer to use this instead of the final
list comprehension.  However, it is almost twice as slow for long lists.  Why?
First, the <tt class="docutils literal"><span class="pre">append()</span></tt> operation has to reallocate memory, and while it uses
some tricks to avoid doing that each time, it still has to do it occasionally,
and that costs quite a bit.  Second, the expression &#8220;result.append&#8221; requires an
extra attribute lookup, and third, there&#8217;s a speed reduction from having to make
all those function calls.</p>
</div>
</div>
<div class="section" id="objects">
<h2><a class="toc-backref" href="#id44">Objects</a><a class="headerlink" href="#objects" title="Permalink to this headline">¶</a></h2>
<div class="section" id="what-is-a-class">
<h3><a class="toc-backref" href="#id45">What is a class?</a><a class="headerlink" href="#what-is-a-class" title="Permalink to this headline">¶</a></h3>
<p>A class is the particular object type created by executing a class statement.
Class objects are used as templates to create instance objects, which embody
both the data (attributes) and code (methods) specific to a datatype.</p>
<p>A class can be based on one or more other classes, called its base class(es). It
then inherits the attributes and methods of its base classes. This allows an
object model to be successively refined by inheritance.  You might have a
generic <tt class="docutils literal"><span class="pre">Mailbox</span></tt> class that provides basic accessor methods for a mailbox,
and subclasses such as <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 various specific mailbox formats.</p>
</div>
<div class="section" id="what-is-a-method">
<h3><a class="toc-backref" href="#id46">What is a method?</a><a class="headerlink" href="#what-is-a-method" title="Permalink to this headline">¶</a></h3>
<p>A method is a function on some object <tt class="docutils literal"><span class="pre">x</span></tt> that you normally call as
<tt class="docutils literal"><span class="pre">x.name(arguments...)</span></tt>.  Methods are defined as functions inside the class
definition:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">class</span> <span class="nc">C</span><span class="p">:</span>
    <span class="k">def</span> <span class="nf">meth</span> <span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">arg</span><span class="p">):</span>
        <span class="k">return</span> <span class="n">arg</span> <span class="o">*</span> <span class="mi">2</span> <span class="o">+</span> <span class="bp">self</span><span class="o">.</span><span class="n">attribute</span>
</pre></div>
</div>
</div>
<div class="section" id="what-is-self">
<h3><a class="toc-backref" href="#id47">What is self?</a><a class="headerlink" href="#what-is-self" title="Permalink to this headline">¶</a></h3>
<p>Self is merely a conventional name for the first argument of a method.  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 <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 definition occurs; the called
method will think it is called as <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>
<p>See also <a class="reference external" href="design.html#why-self"><em>Why must &#8216;self&#8217; be used explicitly in method definitions and calls?</em></a>.</p>
</div>
<div class="section" id="how-do-i-check-if-an-object-is-an-instance-of-a-given-class-or-of-a-subclass-of-it">
<h3><a class="toc-backref" href="#id48">How do I check if an object is an instance of a given class or of a subclass of it?</a><a class="headerlink" href="#how-do-i-check-if-an-object-is-an-instance-of-a-given-class-or-of-a-subclass-of-it" title="Permalink to this headline">¶</a></h3>
<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 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>, and can also
check whether an object is one of Python&#8217;s built-in types, e.g.
<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>
<p>Note that most programs do not use <a title="isinstance" class="reference external" href="../library/functions.html#isinstance"><tt class="xref docutils literal"><span class="pre">isinstance()</span></tt></a> on user-defined classes
very often.  If you are developing the classes yourself, a more proper
object-oriented style is to define methods on the classes that encapsulate a
particular behaviour, instead of checking the object&#8217;s class and doing a
different thing based on what class it is.  For example, if you have a function
that does something:</p>
<div class="highlight-python"><pre>def search(obj):
    if isinstance(obj, Mailbox):
        # ... code to search a mailbox
    elif isinstance(obj, Document):
        # ... code to search a document
    elif ...</pre>
</div>
<p>A better approach is to define a <tt class="docutils literal"><span class="pre">search()</span></tt> method on all the classes and just
call it:</p>
<div class="highlight-python"><pre>class Mailbox:
    def search(self):
        # ... code to search a mailbox

class Document:
    def search(self):
        # ... code to search a document

obj.search()</pre>
</div>
</div>
<div class="section" id="what-is-delegation">
<h3><a class="toc-backref" href="#id49">What is delegation?</a><a class="headerlink" href="#what-is-delegation" title="Permalink to this headline">¶</a></h3>
<p>Delegation is an object oriented technique (also called a design pattern).
Let&#8217;s say you have an object <tt class="docutils literal"><span class="pre">x</span></tt> and want to change the behaviour of just one
of its methods.  You can create a new class that provides a new implementation
of the method you&#8217;re interested in changing and delegates all other methods to
the corresponding method of <tt class="docutils literal"><span class="pre">x</span></tt>.</p>
<p>Python programmers can easily implement delegation.  For example, the following
class implements a class that behaves like a file but converts all written data
to uppercase:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">class</span> <span class="nc">UpperOut</span><span class="p">:</span>

    <span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">outfile</span><span class="p">):</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">_outfile</span> <span class="o">=</span> <span class="n">outfile</span>

    <span class="k">def</span> <span class="nf">write</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">s</span><span class="p">):</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">_outfile</span><span class="o">.</span><span class="n">write</span><span class="p">(</span><span class="n">s</span><span class="o">.</span><span class="n">upper</span><span class="p">())</span>

    <span class="k">def</span> <span class="nf">__getattr__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">name</span><span class="p">):</span>
        <span class="k">return</span> <span class="nb">getattr</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">_outfile</span><span class="p">,</span> <span class="n">name</span><span class="p">)</span>
</pre></div>
</div>
<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 convert the
argument string to uppercase before calling the underlying
<tt class="docutils literal"><span class="pre">self.__outfile.write()</span></tt> method.  All other methods are delegated to the
underlying <tt class="docutils literal"><span class="pre">self.__outfile</span></tt> object.  The delegation is accomplished via the
<tt class="docutils literal"><span class="pre">__getattr__</span></tt> method; consult <a class="reference external" href="../reference/datamodel.html#attribute-access"><em>the language reference</em></a>
for more information about controlling attribute access.</p>
<p>Note that for more general cases delegation can get trickier. When attributes
must be set as well as retrieved, the class must define a <a title="object.__setattr__" class="reference external" href="../reference/datamodel.html#object.__setattr__"><tt class="xref docutils literal"><span class="pre">__setattr__()</span></tt></a>
method too, and it must do so carefully.  The basic implementation of
<a title="object.__setattr__" class="reference external" href="../reference/datamodel.html#object.__setattr__"><tt class="xref docutils literal"><span class="pre">__setattr__()</span></tt></a> is roughly equivalent to the following:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">class</span> <span class="nc">X</span><span class="p">:</span>
    <span class="o">...</span>
    <span class="k">def</span> <span class="nf">__setattr__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">name</span><span class="p">,</span> <span class="n">value</span><span class="p">):</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">__dict__</span><span class="p">[</span><span class="n">name</span><span class="p">]</span> <span class="o">=</span> <span class="n">value</span>
    <span class="o">...</span>
</pre></div>
</div>
<p>Most <a title="object.__setattr__" class="reference external" href="../reference/datamodel.html#object.__setattr__"><tt class="xref docutils literal"><span class="pre">__setattr__()</span></tt></a> implementations must modify <tt class="docutils literal"><span class="pre">self.__dict__</span></tt> to store
local state for self without causing an infinite recursion.</p>
</div>
<div class="section" id="how-do-i-call-a-method-defined-in-a-base-class-from-a-derived-class-that-overrides-it">
<h3><a class="toc-backref" href="#id50">How do I call a method defined in a base class from a derived class that overrides it?</a><a class="headerlink" href="#how-do-i-call-a-method-defined-in-a-base-class-from-a-derived-class-that-overrides-it" title="Permalink to this headline">¶</a></h3>
<p>If you&#8217;re using new-style classes, use the built-in <a title="super" class="reference external" href="../library/functions.html#super"><tt class="xref docutils literal"><span class="pre">super()</span></tt></a> function:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">class</span> <span class="nc">Derived</span><span class="p">(</span><span class="n">Base</span><span class="p">):</span>
    <span class="k">def</span> <span class="nf">meth</span> <span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="nb">super</span><span class="p">(</span><span class="n">Derived</span><span class="p">,</span> <span class="bp">self</span><span class="p">)</span><span class="o">.</span><span class="n">meth</span><span class="p">()</span>
</pre></div>
</div>
<p>If you&#8217;re using classic classes: For a class definition such as <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 <tt class="docutils literal"><span class="pre">Base</span></tt> (or one
of <tt class="docutils literal"><span class="pre">Base</span></tt>&#8216;s base classes) as <tt class="docutils literal"><span class="pre">Base.meth(self,</span> <span class="pre">arguments...)</span></tt>.  Here,
<tt class="docutils literal"><span class="pre">Base.meth</span></tt> is an unbound method, so you need to provide the <tt class="docutils literal"><span class="pre">self</span></tt>
argument.</p>
</div>
<div class="section" id="how-can-i-organize-my-code-to-make-it-easier-to-change-the-base-class">
<h3><a class="toc-backref" href="#id51">How can I organize my code to make it easier to change the base class?</a><a class="headerlink" href="#how-can-i-organize-my-code-to-make-it-easier-to-change-the-base-class" title="Permalink to this headline">¶</a></h3>
<p>You could define an alias for the base class, assign the real base class to it
before your class definition, and use the alias throughout your class.  Then all
you have to change is the value assigned to the alias.  Incidentally, this trick
is also handy if you want to decide dynamically (e.g. depending on availability
of resources) which base class to use.  Example:</p>
<div class="highlight-python"><pre>BaseAlias = &lt;real base class&gt;

class Derived(BaseAlias):
    def meth(self):
        BaseAlias.meth(self)
        ...</pre>
</div>
</div>
<div class="section" id="how-do-i-create-static-class-data-and-static-class-methods">
<h3><a class="toc-backref" href="#id52">How do I create static class data and static class methods?</a><a class="headerlink" href="#how-do-i-create-static-class-data-and-static-class-methods" title="Permalink to this headline">¶</a></h3>
<p>Both static data and static methods (in the sense of C++ or Java) are supported
in Python.</p>
<p>For static data, simply define a class attribute.  To assign a new value to the
attribute, you have to explicitly use the class name in the assignment:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">class</span> <span class="nc">C</span><span class="p">:</span>
    <span class="n">count</span> <span class="o">=</span> <span class="mi">0</span>   <span class="c"># number of times C.__init__ called</span>

    <span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="n">C</span><span class="o">.</span><span class="n">count</span> <span class="o">=</span> <span class="n">C</span><span class="o">.</span><span class="n">count</span> <span class="o">+</span> <span class="mi">1</span>

    <span class="k">def</span> <span class="nf">getcount</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="k">return</span> <span class="n">C</span><span class="o">.</span><span class="n">count</span>  <span class="c"># or return self.count</span>
</pre></div>
</div>
<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 <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 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>
<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> creates a
new and unrelated instance named &#8220;count&#8221; in <tt class="docutils literal"><span class="pre">self</span></tt>&#8216;s own dict.  Rebinding of a
class-static data name must always specify the class whether inside a method or
not:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">C</span><span class="o">.</span><span class="n">count</span> <span class="o">=</span> <span class="mi">314</span>
</pre></div>
</div>
<p>Static methods are possible since Python 2.2:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">class</span> <span class="nc">C</span><span class="p">:</span>
    <span class="k">def</span> <span class="nf">static</span><span class="p">(</span><span class="n">arg1</span><span class="p">,</span> <span class="n">arg2</span><span class="p">,</span> <span class="n">arg3</span><span class="p">):</span>
        <span class="c"># No &#39;self&#39; parameter!</span>
        <span class="o">...</span>
    <span class="n">static</span> <span class="o">=</span> <span class="nb">staticmethod</span><span class="p">(</span><span class="n">static</span><span class="p">)</span>
</pre></div>
</div>
<p>With Python 2.4&#8217;s decorators, this can also be written as</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">class</span> <span class="nc">C</span><span class="p">:</span>
    <span class="nd">@staticmethod</span>
    <span class="k">def</span> <span class="nf">static</span><span class="p">(</span><span class="n">arg1</span><span class="p">,</span> <span class="n">arg2</span><span class="p">,</span> <span class="n">arg3</span><span class="p">):</span>
        <span class="c"># No &#39;self&#39; parameter!</span>
        <span class="o">...</span>
</pre></div>
</div>
<p>However, a far more straightforward way to get the effect of a static method is
via a simple module-level function:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">def</span> <span class="nf">getcount</span><span class="p">():</span>
    <span class="k">return</span> <span class="n">C</span><span class="o">.</span><span class="n">count</span>
</pre></div>
</div>
<p>If your code is structured so as to define one class (or tightly related class
hierarchy) per module, this supplies the desired encapsulation.</p>
</div>
<div class="section" id="how-can-i-overload-constructors-or-methods-in-python">
<h3><a class="toc-backref" href="#id53">How can I overload constructors (or methods) in Python?</a><a class="headerlink" href="#how-can-i-overload-constructors-or-methods-in-python" title="Permalink to this headline">¶</a></h3>
<p>This answer actually applies to all methods, but the question usually comes up
first in the context of constructors.</p>
<p>In C++ you&#8217;d write</p>
<div class="highlight-c"><div class="highlight"><pre><span class="n">class</span> <span class="n">C</span> <span class="p">{</span>
    <span class="n">C</span><span class="p">()</span> <span class="p">{</span> <span class="n">cout</span> <span class="o">&lt;&lt;</span> <span class="s">&quot;No arguments</span><span class="se">\n</span><span class="s">&quot;</span><span class="p">;</span> <span class="p">}</span>
    <span class="n">C</span><span class="p">(</span><span class="kt">int</span> <span class="n">i</span><span class="p">)</span> <span class="p">{</span> <span class="n">cout</span> <span class="o">&lt;&lt;</span> <span class="s">&quot;Argument is &quot;</span> <span class="o">&lt;&lt;</span> <span class="n">i</span> <span class="o">&lt;&lt;</span> <span class="s">&quot;</span><span class="se">\n</span><span class="s">&quot;</span><span class="p">;</span> <span class="p">}</span>
<span class="p">}</span>
</pre></div>
</div>
<p>In Python you have to write a single constructor that catches all cases using
default arguments.  For example:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">class</span> <span class="nc">C</span><span class="p">:</span>
    <span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">i</span><span class="o">=</span><span class="bp">None</span><span class="p">):</span>
        <span class="k">if</span> <span class="n">i</span> <span class="ow">is</span> <span class="bp">None</span><span class="p">:</span>
            <span class="k">print</span> <span class="s">&quot;No arguments&quot;</span>
        <span class="k">else</span><span class="p">:</span>
            <span class="k">print</span> <span class="s">&quot;Argument is&quot;</span><span class="p">,</span> <span class="n">i</span>
</pre></div>
</div>
<p>This is not entirely equivalent, but close enough in practice.</p>
<p>You could also try a variable-length argument list, e.g.</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="o">*</span><span class="n">args</span><span class="p">):</span>
    <span class="o">...</span>
</pre></div>
</div>
<p>The same approach works for all method definitions.</p>
</div>
<div class="section" id="i-try-to-use-spam-and-i-get-an-error-about-someclassname-spam">
<h3><a class="toc-backref" href="#id54">I try to use __spam and I get an error about _SomeClassName__spam.</a><a class="headerlink" href="#i-try-to-use-spam-and-i-get-an-error-about-someclassname-spam" title="Permalink to this headline">¶</a></h3>
<p>Variable names with double leading underscores are &#8220;mangled&#8221; to provide a simple
but effective way to define class private variables.  Any identifier of the form
<tt class="docutils literal"><span class="pre">__spam</span></tt> (at least two leading underscores, at most one trailing underscore)
is textually 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
current class name with any leading underscores stripped.</p>
<p>This doesn&#8217;t guarantee privacy: an outside user can still deliberately access
the &#8220;_classname__spam&#8221; attribute, and private values are visible in the object&#8217;s
<tt class="docutils literal"><span class="pre">__dict__</span></tt>.  Many Python programmers never bother to use private variable
names at all.</p>
</div>
<div class="section" id="my-class-defines-del-but-it-is-not-called-when-i-delete-the-object">
<h3><a class="toc-backref" href="#id55">My class defines __del__ but it is not called when I delete the object.</a><a class="headerlink" href="#my-class-defines-del-but-it-is-not-called-when-i-delete-the-object" title="Permalink to this headline">¶</a></h3>
<p>There are several possible reasons for this.</p>
<p>The del statement does not necessarily call <a title="object.__del__" class="reference external" href="../reference/datamodel.html#object.__del__"><tt class="xref docutils literal"><span class="pre">__del__()</span></tt></a> &#8211; it simply
decrements the object&#8217;s reference count, and if this reaches zero
<a title="object.__del__" class="reference external" href="../reference/datamodel.html#object.__del__"><tt class="xref docutils literal"><span class="pre">__del__()</span></tt></a> is called.</p>
<p>If your data structures contain circular links (e.g. a tree where each child has
a parent reference and each parent has a list of children) the reference counts
will never go back to zero.  Once in a while Python runs an algorithm to detect
such cycles, but the garbage collector might run some time after the last
reference to your data structure vanishes, so your <a title="object.__del__" class="reference external" href="../reference/datamodel.html#object.__del__"><tt class="xref docutils literal"><span class="pre">__del__()</span></tt></a> method may be
called at an inconvenient and random time. This is inconvenient if you&#8217;re trying
to reproduce a problem. Worse, the order in which object&#8217;s <a title="object.__del__" class="reference external" href="../reference/datamodel.html#object.__del__"><tt class="xref docutils literal"><span class="pre">__del__()</span></tt></a>
methods are executed is arbitrary.  You can run <a title="gc.collect" class="reference external" href="../library/gc.html#gc.collect"><tt class="xref docutils literal"><span class="pre">gc.collect()</span></tt></a> to force a
collection, but there <em>are</em> pathological cases where objects will never be
collected.</p>
<p>Despite the cycle collector, it&#8217;s still a good idea to define an explicit
<tt class="docutils literal"><span class="pre">close()</span></tt> method on objects to be called whenever you&#8217;re done with them.  The
<tt class="docutils literal"><span class="pre">close()</span></tt> method can then remove attributes that refer to subobjecs.  Don&#8217;t
call <a title="object.__del__" class="reference external" href="../reference/datamodel.html#object.__del__"><tt class="xref docutils literal"><span class="pre">__del__()</span></tt></a> directly &#8211; <a title="object.__del__" class="reference external" href="../reference/datamodel.html#object.__del__"><tt class="xref docutils literal"><span class="pre">__del__()</span></tt></a> 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 that it can be called more than once for the same
object.</p>
<p>Another way to avoid cyclical references is to use the <a title="Support for weak references and weak dictionaries." class="reference external" href="../library/weakref.html#module-weakref"><tt class="xref docutils literal"><span class="pre">weakref</span></tt></a> module,
which allows you to point to objects without incrementing their reference count.
Tree data structures, for instance, should use weak references for their parent
and sibling references (if they need them!).</p>
<p>If the object has ever been a local variable in a function that caught an
expression in an except clause, chances are that a reference to the object still
exists in that function&#8217;s stack frame as contained in the stack trace.
Normally, calling <a title="sys.exc_clear" class="reference external" href="../library/sys.html#sys.exc_clear"><tt class="xref docutils literal"><span class="pre">sys.exc_clear()</span></tt></a> will take care of this by clearing the
last recorded exception.</p>
<p>Finally, if your <a title="object.__del__" class="reference external" href="../reference/datamodel.html#object.__del__"><tt class="xref docutils literal"><span class="pre">__del__()</span></tt></a> method raises an exception, a warning message
is printed to <a title="sys.stderr" class="reference external" href="../library/sys.html#sys.stderr"><tt class="xref docutils literal"><span class="pre">sys.stderr</span></tt></a>.</p>
</div>
<div class="section" id="how-do-i-get-a-list-of-all-instances-of-a-given-class">
<h3><a class="toc-backref" href="#id56">How do I get a list of all instances of a given class?</a><a class="headerlink" href="#how-do-i-get-a-list-of-all-instances-of-a-given-class" title="Permalink to this headline">¶</a></h3>
<p>Python does not keep track of all instances of a class (or of a built-in type).
You can program the class&#8217;s constructor to keep track of all instances by
keeping a list of weak references to each instance.</p>
</div>
</div>
<div class="section" id="modules">
<h2><a class="toc-backref" href="#id57">Modules</a><a class="headerlink" href="#modules" title="Permalink to this headline">¶</a></h2>
<div class="section" id="how-do-i-create-a-pyc-file">
<h3><a class="toc-backref" href="#id58">How do I create a .pyc file?</a><a class="headerlink" href="#how-do-i-create-a-pyc-file" title="Permalink to this headline">¶</a></h3>
<p>When a module is imported for the first time (or when the source is more recent
than the current compiled file) a <tt class="docutils literal"><span class="pre">.pyc</span></tt> file containing the compiled code
should be created in the same directory as the <tt class="docutils literal"><span class="pre">.py</span></tt> file.</p>
<p>One reason that a <tt class="docutils literal"><span class="pre">.pyc</span></tt> file may not be created is permissions problems with
the directory. This can happen, for example, if you develop as one user but run
as another, such as if you are testing with a web server.  Creation of a .pyc
file is automatic if you&#8217;re importing a module and Python has the ability
(permissions, free space, etc...) to write the compiled module back to the
directory.</p>
<p>Running Python on a top level script is not considered an import and no <tt class="docutils literal"><span class="pre">.pyc</span></tt>
will be created.  For example, if you have a top-level 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 abc, <tt class="docutils literal"><span class="pre">xyz.pyc</span></tt> will be created
since xyz is imported, but no <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&#8217;t being imported.</p>
<p>If you need to create abc.pyc &#8211; that is, to create a .pyc file for a module
that is not imported &#8211; you can, using the <a title="Generate byte-code files from Python source files." class="reference external" href="../library/py_compile.html#module-py_compile"><tt class="xref docutils literal"><span class="pre">py_compile</span></tt></a> and
<a title="Tools for byte-compiling all Python source files in a directory tree." class="reference external" href="../library/compileall.html#module-compileall"><tt class="xref docutils literal"><span class="pre">compileall</span></tt></a> modules.</p>
<p>The <a title="Generate byte-code files from Python source files." class="reference external" href="../library/py_compile.html#module-py_compile"><tt class="xref docutils literal"><span class="pre">py_compile</span></tt></a> module can manually compile any module.  One way is to use
the <tt class="docutils literal"><span class="pre">compile()</span></tt> function in that module interactively:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">py_compile</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">py_compile</span><span class="o">.</span><span class="n">compile</span><span class="p">(</span><span class="s">&#39;abc.py&#39;</span><span class="p">)</span>
</pre></div>
</div>
<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 you can
override that with the optional parameter <tt class="docutils literal"><span class="pre">cfile</span></tt>).</p>
<p>You can also automatically compile all files in a directory or directories using
the <a title="Tools for byte-compiling all Python source files in a directory tree." class="reference external" href="../library/compileall.html#module-compileall"><tt class="xref docutils literal"><span class="pre">compileall</span></tt></a> module.  You can do it from the shell prompt by running
<tt class="docutils literal"><span class="pre">compileall.py</span></tt> and providing the path of a directory containing Python files
to compile:</p>
<div class="highlight-python"><pre>python -m compileall .</pre>
</div>
</div>
<div class="section" id="how-do-i-find-the-current-module-name">
<h3><a class="toc-backref" href="#id59">How do I find the current module name?</a><a class="headerlink" href="#how-do-i-find-the-current-module-name" title="Permalink to this headline">¶</a></h3>
<p>A module can find out its own module name by looking at the predefined global
variable <tt class="docutils literal"><span class="pre">__name__</span></tt>.  If this has the value <tt class="docutils literal"><span class="pre">'__main__'</span></tt>, the program is
running as a script.  Many modules that are usually used by importing them also
provide a command-line interface or a self-test, and only execute this code
after checking <tt class="docutils literal"><span class="pre">__name__</span></tt>:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">def</span> <span class="nf">main</span><span class="p">():</span>
    <span class="k">print</span> <span class="s">&#39;Running test...&#39;</span>
    <span class="o">...</span>

<span class="k">if</span> <span class="n">__name__</span> <span class="o">==</span> <span class="s">&#39;__main__&#39;</span><span class="p">:</span>
    <span class="n">main</span><span class="p">()</span>
</pre></div>
</div>
</div>
<div class="section" id="how-can-i-have-modules-that-mutually-import-each-other">
<h3><a class="toc-backref" href="#id60">How can I have modules that mutually import each other?</a><a class="headerlink" href="#how-can-i-have-modules-that-mutually-import-each-other" title="Permalink to this headline">¶</a></h3>
<p>Suppose you have the following modules:</p>
<p>foo.py:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="kn">from</span> <span class="nn">bar</span> <span class="kn">import</span> <span class="n">bar_var</span>
<span class="n">foo_var</span> <span class="o">=</span> <span class="mi">1</span>
</pre></div>
</div>
<p>bar.py:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="kn">from</span> <span class="nn">foo</span> <span class="kn">import</span> <span class="n">foo_var</span>
<span class="n">bar_var</span> <span class="o">=</span> <span class="mi">2</span>
</pre></div>
</div>
<p>The problem is that the interpreter will perform the following steps:</p>
<ul class="simple">
<li>main imports foo</li>
<li>Empty globals for foo are created</li>
<li>foo is compiled and starts executing</li>
<li>foo imports bar</li>
<li>Empty globals for bar are created</li>
<li>bar is compiled and starts executing</li>
<li>bar imports foo (which is a no-op since there already is a module named foo)</li>
<li>bar.foo_var = foo.foo_var</li>
</ul>
<p>The last step fails, because Python isn&#8217;t done with interpreting <tt class="docutils literal"><span class="pre">foo</span></tt> yet and
the global symbol dictionary for <tt class="docutils literal"><span class="pre">foo</span></tt> is still empty.</p>
<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 access
<tt class="docutils literal"><span class="pre">foo.foo_var</span></tt> in global code.</p>
<p>There are (at least) three possible workarounds for this problem.</p>
<p>Guido van Rossum recommends avoiding all uses of <tt class="docutils literal"><span class="pre">from</span> <span class="pre">&lt;module&gt;</span> <span class="pre">import</span> <span class="pre">...</span></tt>,
and placing all code inside functions.  Initializations of global variables and
class variables should use constants or built-in functions only.  This means
everything from an imported module is referenced as <tt class="docutils literal"><span class="pre">&lt;module&gt;.&lt;name&gt;</span></tt>.</p>
<p>Jim Roskind suggests performing steps in the following order in each module:</p>
<ul class="simple">
<li>exports (globals, functions, and classes that don&#8217;t need imported base
classes)</li>
<li><tt class="docutils literal"><span class="pre">import</span></tt> statements</li>
<li>active code (including globals that are initialized from imported values).</li>
</ul>
<p>van Rossum doesn&#8217;t like this approach much because the imports appear in a
strange place, but it does work.</p>
<p>Matthias Urlichs recommends restructuring your code so that the recursive import
is not necessary in the first place.</p>
<p>These solutions are not mutually exclusive.</p>
</div>
<div class="section" id="import-x-y-z-returns-module-x-how-do-i-get-z">
<h3><a class="toc-backref" href="#id61">__import__(&#8216;x.y.z&#8217;) returns &lt;module &#8216;x&#8217;&gt;; how do I get z?</a><a class="headerlink" href="#import-x-y-z-returns-module-x-how-do-i-get-z" title="Permalink to this headline">¶</a></h3>
<p>Try:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="nb">__import__</span><span class="p">(</span><span class="s">&#39;x.y.z&#39;</span><span class="p">)</span><span class="o">.</span><span class="n">y</span><span class="o">.</span><span class="n">z</span>
</pre></div>
</div>
<p>For more realistic situations, you may have to do something like</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">m</span> <span class="o">=</span> <span class="nb">__import__</span><span class="p">(</span><span class="n">s</span><span class="p">)</span>
<span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="n">s</span><span class="o">.</span><span class="n">split</span><span class="p">(</span><span class="s">&quot;.&quot;</span><span class="p">)[</span><span class="mi">1</span><span class="p">:]:</span>
    <span class="n">m</span> <span class="o">=</span> <span class="nb">getattr</span><span class="p">(</span><span class="n">m</span><span class="p">,</span> <span class="n">i</span><span class="p">)</span>
</pre></div>
</div>
<p>See <tt class="xref docutils literal"><span class="pre">importlib</span></tt> for a convenience function called
<tt class="xref docutils literal"><span class="pre">import_module()</span></tt>.</p>
</div>
<div class="section" id="when-i-edit-an-imported-module-and-reimport-it-the-changes-don-t-show-up-why-does-this-happen">
<h3><a class="toc-backref" href="#id62">When I edit an imported module and reimport it, the changes don&#8217;t show up.  Why does this happen?</a><a class="headerlink" href="#when-i-edit-an-imported-module-and-reimport-it-the-changes-don-t-show-up-why-does-this-happen" title="Permalink to this headline">¶</a></h3>
<p>For reasons of efficiency as well as consistency, Python only reads the module
file on the first time a module is imported.  If it didn&#8217;t, in a program
consisting of many modules where each one imports the same basic module, the
basic module would be parsed and re-parsed many times.  To force rereading of a
changed module, do this:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="kn">import</span> <span class="nn">modname</span>
<span class="nb">reload</span><span class="p">(</span><span class="n">modname</span><span class="p">)</span>
</pre></div>
</div>
<p>Warning: this technique is not 100% fool-proof.  In particular, modules
containing statements like</p>
<div class="highlight-python"><div class="highlight"><pre><span class="kn">from</span> <span class="nn">modname</span> <span class="kn">import</span> <span class="n">some_objects</span>
</pre></div>
</div>
<p>will continue to work with the old version of the imported objects.  If the
module contains class definitions, existing class instances will <em>not</em> be
updated to use the new class definition.  This can result in the following
paradoxical behaviour:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">cls</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">c</span> <span class="o">=</span> <span class="n">cls</span><span class="o">.</span><span class="n">C</span><span class="p">()</span>                <span class="c"># Create an instance of C</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">reload</span><span class="p">(</span><span class="n">cls</span><span class="p">)</span>
<span class="go">&lt;module &#39;cls&#39; from &#39;cls.pyc&#39;&gt;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">isinstance</span><span class="p">(</span><span class="n">c</span><span class="p">,</span> <span class="n">cls</span><span class="o">.</span><span class="n">C</span><span class="p">)</span>       <span class="c"># isinstance is false?!?</span>
<span class="go">False</span>
</pre></div>
</div>
<p>The nature of the problem is made clear if you print out the class objects:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">c</span><span class="o">.</span><span class="n">__class__</span>
<span class="go">&lt;class cls.C at 0x7352a0&gt;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">cls</span><span class="o">.</span><span class="n">C</span>
<span class="go">&lt;class cls.C at 0x4198d0&gt;</span>
</pre></div>
</div>
</div>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar">
        <div class="sphinxsidebarwrapper">
            <h3><a href="../contents.html">Table Of Contents</a></h3>
            <ul>
<li><a class="reference external" href="#">Programming FAQ</a><ul>
<li><a class="reference external" href="#general-questions">General Questions</a></li>
<li><a class="reference external" href="#core-language">Core Language</a></li>
<li><a class="reference external" href="#numbers-and-strings">Numbers and strings</a></li>
<li><a class="reference external" href="#sequences-tuples-lists">Sequences (Tuples/Lists)</a></li>
<li><a class="reference external" href="#dictionaries">Dictionaries</a></li>
<li><a class="reference external" href="#objects">Objects</a></li>
<li><a class="reference external" href="#modules">Modules</a></li>
</ul>
</li>
</ul>

            <h4>Previous topic</h4>
            <p class="topless"><a href="general.html"
                                  title="previous chapter">General Python FAQ</a></p>
            <h4>Next topic</h4>
            <p class="topless"><a href="design.html"
                                  title="next chapter">Design and History FAQ</a></p>
<h3>This Page</h3>
<ul class="this-page-menu">
  <li><a href="../bugs.html">Report a Bug</a></li>
  <li><a href="../_sources/faq/programming.txt"
         rel="nofollow">Show Source</a></li>
</ul>

          <div id="searchbox" style="display: none">
            <h3>Quick search</h3>
              <form class="search" action="../search.html" method="get">
                <input type="text" name="q" size="18" />
                <input type="submit" value="Go" />
                <input type="hidden" name="check_keywords" value="yes" />
                <input type="hidden" name="area" value="default" />
              </form>
              <p class="searchtip" style="font-size: 90%">
              Enter search terms or a module, class or function name.
              </p>
          </div>
          <script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>
    <div class="related">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../modindex.html" title="Global Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="design.html" title="Design and History FAQ"
             >next</a> |</li>
        <li class="right" >
          <a href="general.html" title="General Python FAQ"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="../index.html">Python v2.6.6 documentation</a> &raquo;</li>

          <li><a href="index.html" >Python Frequently Asked Questions</a> &raquo;</li> 
      </ul>
    </div>
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2011, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.  
    <a href="http://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Jul 20, 2011.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 0.6.6.
    </div>

  </body>
</html>

Copyright 2K16 - 2K18 Indonesian Hacker Rulez