<li><a class="reference internal" href="#general-questions" id="id1">1 General Questions</a><ul class="auto-toc">
<li><a class="reference internal" href="#is-there-a-source-code-level-debugger-with-breakpoints-single-stepping-etc" id="id2">1.1 Is there a source code level debugger with breakpoints, single-stepping, etc.?</a></li>
<li><a class="reference internal" href="#is-there-a-tool-to-help-find-bugs-or-perform-static-analysis" id="id3">1.2 Is there a tool to help find bugs or perform static analysis?</a></li>
<li><a class="reference internal" href="#how-can-i-create-a-stand-alone-binary-from-a-python-script" id="id4">1.3 How can I create a stand-alone binary from a Python script?</a></li>
<li><a class="reference internal" href="#are-there-coding-standards-or-a-style-guide-for-python-programs" id="id5">1.4 Are there coding standards or a style guide for Python programs?</a></li>
<li><a class="reference internal" href="#my-program-is-too-slow-how-do-i-speed-it-up" id="id6">1.5 My program is too slow. How do I speed it up?</a></li>
<li><a class="reference internal" href="#how-do-you-set-a-global-variable-in-a-function" id="id8">2.1 How do you set a global variable in a function?</a></li>
<li><a class="reference internal" href="#what-are-the-rules-for-local-and-global-variables-in-python" id="id9">2.2 What are the rules for local and global variables in Python?</a></li>
<li><a class="reference internal" href="#how-do-i-share-global-variables-across-modules" id="id10">2.3 How do I share global variables across modules?</a></li>
<li><a class="reference internal" href="#what-are-the-best-practices-for-using-import-in-a-module" id="id11">2.4 What are the "best practices" for using import in a module?</a></li>
<li><a class="reference internal" href="#how-can-i-pass-optional-or-keyword-parameters-from-one-function-to-another" id="id12">2.5 How can I pass optional or keyword parameters from one function to another?</a></li>
<li><a class="reference internal" href="#how-do-i-write-a-function-with-output-parameters-call-by-reference" id="id13">2.6 How do I write a function with output parameters (call by reference)?</a></li>
<li><a class="reference internal" href="#how-do-you-make-a-higher-order-function-in-python" id="id14">2.7 How do you make a higher order function in Python?</a></li>
<li><a class="reference internal" href="#how-do-i-copy-an-object-in-python" id="id15">2.8 How do I copy an object in Python?</a></li>
<li><a class="reference internal" href="#how-can-i-find-the-methods-or-attributes-of-an-object" id="id16">2.9 How can I find the methods or attributes of an object?</a></li>
<li><a class="reference internal" href="#how-can-my-code-discover-the-name-of-an-object" id="id17">2.10 How can my code discover the name of an object?</a></li>
<li><a class="reference internal" href="#is-there-an-equivalent-of-c-s-ternary-operator" id="id18">2.11 Is there an equivalent of C's "?:" ternary operator?</a></li>
<li><a class="reference internal" href="#is-it-possible-to-write-obfuscated-one-liners-in-python" id="id19">2.12 Is it possible to write obfuscated one-liners in Python?</a></li>
</ul>
</li>
<li><a class="reference internal" href="#numbers-and-strings" id="id20">3 Numbers and strings</a><ul class="auto-toc">
<li><a class="reference internal" href="#how-do-i-specify-hexadecimal-and-octal-integers" id="id21">3.1 How do I specify hexadecimal and octal integers?</a></li>
<li><a class="reference internal" href="#how-do-i-convert-a-string-to-a-number" id="id23">3.3 How do I convert a string to a number?</a></li>
<li><a class="reference internal" href="#how-do-i-convert-a-number-to-a-string" id="id24">3.4 How do I convert a number to a string?</a></li>
<li><a class="reference internal" href="#how-do-i-modify-a-string-in-place" id="id25">3.5 How do I modify a string in place?</a></li>
<li><a class="reference internal" href="#how-do-i-use-strings-to-call-functions-methods" id="id26">3.6 How do I use strings to call functions/methods?</a></li>
<li><a class="reference internal" href="#is-there-an-equivalent-to-perl-s-chomp-for-removing-trailing-newlines-from-strings" id="id27">3.7 Is there an equivalent to Perl's chomp() for removing trailing newlines from strings?</a></li>
<li><a class="reference internal" href="#is-there-a-scanf-or-sscanf-equivalent" id="id28">3.8 Is there a scanf() or sscanf() equivalent?</a></li>
<li><a class="reference internal" href="#what-does-unicodeerror-ascii-decoding-encoding-error-ordinal-not-in-range-128-mean" id="id29">3.9 What does 'UnicodeError: ASCII [decoding,encoding] error: ordinal not in range(128)' mean?</a></li>
<li><a class="reference internal" href="#how-do-i-convert-between-tuples-and-lists" id="id31">4.1 How do I convert between tuples and lists?</a></li>
<li><a class="reference internal" href="#what-s-a-negative-index" id="id32">4.2 What's a negative index?</a></li>
<li><a class="reference internal" href="#how-do-i-iterate-over-a-sequence-in-reverse-order" id="id33">4.3 How do I iterate over a sequence in reverse order?</a></li>
<li><a class="reference internal" href="#how-do-you-remove-duplicates-from-a-list" id="id34">4.4 How do you remove duplicates from a list?</a></li>
<li><a class="reference internal" href="#how-do-you-make-an-array-in-python" id="id35">4.5 How do you make an array in Python?</a></li>
<li><a class="reference internal" href="#how-do-i-create-a-multidimensional-list" id="id36">4.6 How do I create a multidimensional list?</a></li>
<li><a class="reference internal" href="#how-do-i-apply-a-method-to-a-sequence-of-objects" id="id37">4.7 How do I apply a method to a sequence of objects?</a></li>
<li><a class="reference internal" href="#how-can-i-get-a-dictionary-to-display-its-keys-in-a-consistent-order" id="id39">5.1 How can I get a dictionary to display its keys in a consistent order?</a></li>
<li><a class="reference internal" href="#i-want-to-do-a-complicated-sort-can-you-do-a-schwartzian-transform-in-python" id="id40">5.2 I want to do a complicated sort: can you do a Schwartzian Transform in Python?</a></li>
<li><a class="reference internal" href="#how-can-i-sort-one-list-by-values-from-another-list" id="id41">5.3 How can I sort one list by values from another list?</a></li>
<li><a class="reference internal" href="#what-is-a-class" id="id43">6.1 What is a class?</a></li>
<li><a class="reference internal" href="#what-is-a-method" id="id44">6.2 What is a method?</a></li>
<li><a class="reference internal" href="#what-is-self" id="id45">6.3 What is self?</a></li>
<li><a class="reference internal" href="#how-do-i-check-if-an-object-is-an-instance-of-a-given-class-or-of-a-subclass-of-it" id="id46">6.4 How do I check if an object is an instance of a given class or of a subclass of it?</a></li>
<li><a class="reference internal" href="#what-is-delegation" id="id47">6.5 What is delegation?</a></li>
<li><a class="reference internal" href="#how-do-i-call-a-method-defined-in-a-base-class-from-a-derived-class-that-overrides-it" id="id48">6.6 How do I call a method defined in a base class from a derived class that overrides it?</a></li>
<li><a class="reference internal" href="#how-can-i-organize-my-code-to-make-it-easier-to-change-the-base-class" id="id49">6.7 How can I organize my code to make it easier to change the base class?</a></li>
<li><a class="reference internal" href="#how-do-i-create-static-class-data-and-static-class-methods" id="id50">6.8 How do I create static class data and static class methods?</a></li>
<li><a class="reference internal" href="#how-can-i-overload-constructors-or-methods-in-python" id="id51">6.9 How can I overload constructors (or methods) in Python?</a></li>
<li><a class="reference internal" href="#i-try-to-use-spam-and-i-get-an-error-about-someclassname-spam" id="id52">6.10 I try to use __spam and I get an error about _SomeClassName__spam.</a></li>
<li><a class="reference internal" href="#my-class-defines-del-but-it-is-not-called-when-i-delete-the-object" id="id53">6.11 My class defines __del__ but it is not called when I delete the object.</a></li>
<li><a class="reference internal" href="#how-do-i-get-a-list-of-all-instances-of-a-given-class" id="id54">6.12 How do I get a list of all instances of a given class?</a></li>
<li><a class="reference internal" href="#how-do-i-create-a-pyc-file" id="id56">7.1 How do I create a .pyc file?</a></li>
<li><a class="reference internal" href="#how-do-i-find-the-current-module-name" id="id57">7.2 How do I find the current module name?</a></li>
<li><a class="reference internal" href="#how-can-i-have-modules-that-mutually-import-each-other" id="id58">7.3 How can I have modules that mutually import each other?</a></li>
<li><a class="reference internal" href="#import-x-y-z-returns-module-x-how-do-i-get-z" id="id59">7.4 __import__('x.y.z') returns <module 'x'>; how do I get z?</a></li>
<li><a class="reference internal" href="#when-i-edit-an-imported-module-and-reimport-it-the-changes-don-t-show-up-why-does-this-happen" id="id60">7.5 When I edit an imported module and reimport it, the changes don't show up. Why does this happen?</a></li>
</ul>
</li>
</ul>
</div>
<div class="section" id="general-questions">
<h1><a class="toc-backref" href="#id1">1 General Questions</a></h1>
<h2><a class="toc-backref" href="#id2">1.1 Is there a source code level debugger with breakpoints, single-stepping, etc.?</a></h2>
<p>Yes.</p>
<p>The pdb module is a simple but adequate console-mode debugger for
Python. It is part of the standard Python library, and is <a class="reference external" href="http://docs.python.org/lib/module-pdb.html">documented
in the Library Reference Manual</a>. You can
also write your own debugger by using the code for pdb as an example.</p>
<p>The IDLE interactive development environment, which is part of the
standard Python distribution (normally available as Tools/scripts/idle),
includes a graphical debugger. There is documentation for the IDLE
debugger at <a class="reference external" href="http://www.python.org/idle/doc/idle2.html#Debugger">http://www.python.org/idle/doc/idle2.html#Debugger</a></p>
<p>PythonWin is a Python IDE that includes a GUI debugger based on pdb.
The Pythonwin debugger colors breakpoints and has quite a few cool
features such as debugging non-Pythonwin programs. A reference can be
found at <a class="reference external" href="http://www.python.org/windows/pythonwin/">http://www.python.org/windows/pythonwin/</a>. Recent versions of
PythonWin are available as a part of the ActivePython distribution
(see <a class="reference external" href="http://www.activestate.com/Products/ActivePython/index.html">http://www.activestate.com/Products/ActivePython/index.html</a>).</p>
<p><a class="reference external" href="http://boa-constructor.sourceforge.net/">Boa Constructor</a> is an IDE
and GUI builder that uses wxPython. It offers visual frame creation
and manipulation, an object
inspector, many views on the source like object browsers, inheritance
hierarchies, doc string generated html documentation, an advanced
debugger, integrated help, and Zope support.</p>
<p><a class="reference external" href="http://www.die-offenbachs.de/detlev/eric3.html">Eric3</a> is an IDE
built on PyQt and the Scintilla editing component.</p>
<p>Pydb is a version of the standard Python debugger pdb, modified for
use with DDD (Data Display Debugger), a popular graphical debugger
front end. Pydb can be found at
<a class="reference external" href="http://packages.debian.org/unstable/devel/pydb.html">http://packages.debian.org/unstable/devel/pydb.html</a>> and DDD can be
found at <a class="reference external" href="http://www.gnu.org/software/ddd">http://www.gnu.org/software/ddd</a>.</p>
<p>There are a number of commmercial Python IDEs that include graphical
debuggers. They include:</p>
<ul class="simple">
<li>Wing IDE (<a class="reference external" href="http://wingide.com">http://wingide.com</a>)</li>
<li>Komodo IDE (<a class="reference external" href="http://www.activestate.com/Products/Komodo">http://www.activestate.com/Products/Komodo</a>)</li>
<h2><a class="toc-backref" href="#id3">1.2 Is there a tool to help find bugs or perform static analysis?</a></h2>
<p>Yes.</p>
<p>PyChecker is a static analysis tool that finds bugs in Python source
code and warns about code complexity and style. You can get PyChecker
from <a class="reference external" href="http://pychecker.sf.net">http://pychecker.sf.net</a>.</p>
<p><a class="reference external" href="http://www.logilab.org/projects/pylint">Pylint</a> is another tool
that checks if a module satisfies a coding standard, and also makes it
possible to write plug-ins to add a custom feature. In addition to
the bug checking that PyChecker performs, Pylint offers some
additional features such as checking line length, whether variable
names are well-formed according to your coding standard, whether
declared interfaces are fully implemented, and more.
<a class="reference external" href="http://www.logilab.org/projects/pylint/documentation">http://www.logilab.org/projects/pylint/documentation</a> provides a full
<h2><a class="toc-backref" href="#id6">1.5 My program is too slow. How do I speed it up?</a></h2>
<p>That's a tough one, in general. There are many tricks to speed up
Python code; consider rewriting parts in C as a last resort.</p>
<p>In some cases it's possible to automatically translate Python to C or
x86 assembly language, meaning that you don't have to modify your code
to gain increased speed.</p>
<p><a class="reference external" href="http://www.cosc.canterbury.ac.nz/~greg/python/Pyrex/">Pyrex</a> can
compile a slightly modified version of Python code into a C extension,
and can be used on many different platforms.</p>
<p><a class="reference external" href="http://psyco.sourceforge.net">Psyco</a> is a just-in-time compiler
that translates Python code into x86 assembly language. If you can
use it, Psyco can provide dramatic speedups for critical functions.</p>
<p>The rest of this answer will discuss various tricks for squeezing a
bit more speed out of Python code. <em>Never</em> apply any optimization
tricks unless you know you need them, after profiling has indicated
that a particular function is the heavily executed hot spot in the
code. Optimizations almost always make the code less clear, and you
shouldn't pay the costs of reduced clarity (increased development
time, greater likelihood of bugs) unless the resulting performance
benefit is worth it.</p>
<p>There is a page on the wiki devoted to <a class="reference external" href="http://wiki.python.org/moin/PythonSpeed/PerformanceTips">performance tips</a>.</p>
<p>Guido van Rossum has written up an anecdote related to optimization at
<p>One thing to notice is that function and (especially) method calls are
rather expensive; if you have designed a purely OO interface with lots
of tiny functions that don't do much more than get or set an instance
variable or call another method, you might consider using a more
direct way such as directly accessing instance variables. Also see the
standard module "profile" (<a class="reference external" href="http://docs.python.org/lib/module-profile.html">described in the Library Reference manual</a>) which
makes it possible to find out where your program is spending most of
its time (if you have some patience -- the profiling itself can slow
your program down by an order of magnitude).</p>
<p>Remember that many standard optimization heuristics you
may know from other programming experience may well apply
to Python. For example it may be faster to send output to output
devices using larger writes rather than smaller ones in order to
reduce the overhead of kernel system calls. Thus CGI scripts
that write all output in "one shot" may be faster than
those that write lots of small pieces of output.</p>
<p>Also, be sure to use Python's core features where appropriate.
For example, slicing allows programs to chop up
lists and other sequence objects in a single tick of the interpreter's
mainloop using highly optimized C implementations. Thus to
get the same effect as:</p>
<pre class="literal-block">
L2 = []
for i in range[3]:
L2.append(L1[i])
</pre>
<p>it is much shorter and far faster to use</p>
<pre class="literal-block">
L2 = list(L1[:3]) # "list" is redundant if L1 is a list.
</pre>
<p>Note that the functionally-oriented builtins such as
<tt class="docutils literal"><span class="pre">map()</span></tt>, <tt class="docutils literal"><span class="pre">zip()</span></tt>, and friends can be a convenient
accelerator for loops that perform a single task. For example to pair the elements of two
<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>
methods of string objects. For example if s1..s7 are large (10K+) strings then
<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>
<pre class="literal-block">
for value in ffseq(sequence):
...do something with value...
</pre>
<p>Single calls to ff(x) translate to ffseq([x])[0] with little
penalty. Of course this technique is not always appropriate
and there are other variants which you can figure out.</p>
<p>You can gain some performance by explicitly storing the results of
a function or method lookup into a local variable. A loop like:</p>
<pre class="literal-block">
for key in token:
dict[key] = dict.get(key, 0) + 1
</pre>
<p>resolves dict.get every iteration. If the method isn't going to
change, a slightly faster implementation is:</p>
<pre class="literal-block">
dict_get = dict.get # look up the method once
for key in token:
dict[key] = dict_get(key, 0) + 1
</pre>
<p>Default arguments can be used to determine values once, at
compile time instead of at run time. This can only be done for
functions or objects which will not be changed during program
execution, such as replacing</p>
<pre class="literal-block">
def degree_sin(deg):
return math.sin(deg * math.pi / 180.0)
</pre>
<p>with</p>
<pre class="literal-block">
def degree_sin(deg, factor = math.pi/180.0, sin = math.sin):
return sin(deg * factor)
</pre>
<p>Because this trick uses default arguments for terms which should
not be changed, it should only be used when you are not concerned
with presenting a possibly confusing API to your users.</p>
<li>third-party library modules (anything installed in Python's
site-packages directory) -- e.g. mx.DateTime, ZODB, PIL.Image, etc.</li>
<li>locally-developed modules</li>
</ol>
<p>Never use relative package imports. If you're writing code that's
in the <tt class="docutils literal"><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'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.</p>
<p>It is sometimes necessary to move imports to a function or class to
avoid problems with circular imports. Gordon McMillan says:</p>
<blockquote>
Circular imports are fine where both modules use the "import <module>"
form of import. They fail when the 2nd module wants to grab a name
out of the first ("from module import name") and the import is at
the top level. That's because names in the 1st are not yet available,
because the first module is busy importing the 2nd.</blockquote>
<p>In this case, if the second module is only used in one function, then the
import can easily be moved into that function. By the time the import
is called, the first module will have finished initializing, and the
second module can do its import.</p>
<p>It may also be necessary to move imports out of the top level of code
if some of the modules are platform-specific. In that case, it may
not even be possible to import all of the modules at the top of the
file. In this case, importing the correct modules in the
corresponding platform-specific code is a good option.</p>
<p>Only move imports into a local scope, such as inside a function
definition, if it's necessary to solve a problem such as avoiding a
circular import or are trying to reduce the initialization time of a
module. This technique is especially helpful if many of the imports
are unnecessary depending on how the program executes. You may also
want to move imports into a function if the modules are only ever used
in that function. Note that loading a module the first time may be
expensive because of the one time initialization of the module, but
loading a module multiple times is virtually free, costing only a couple of
dictionary lookups. Even if the module name has gone out of scope,
the module is probably available in sys.modules.</p>
<p>If only instances of a specific class use a module, then it is
reasonable to import the module in the class's <tt class="docutils literal"><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
<h2><a class="toc-backref" href="#id12">2.5 How can I pass optional or keyword parameters from one function to another?</a></h2>
<p>Collect the arguments using the <tt class="docutils literal"><span class="pre">*</span></tt> and <tt class="docutils literal"><span class="pre">**</span></tt> specifiers in the function's
parameter list; this gives you the positional arguments as a tuple
and the keyword arguments as a dictionary. You can
then pass these arguments when calling another function by using
<tt class="docutils literal"><span class="pre">*</span></tt> and <tt class="docutils literal"><span class="pre">**</span></tt>:</p>
<pre class="literal-block">
def f(x, *tup, **kwargs):
...
kwargs['width']='14.3c'
...
g(x, *tup, **kwargs)
</pre>
<p>In the unlikely case that you care about Python
<h2><a class="toc-backref" href="#id14">2.7 How do you make a higher order function in Python?</a></h2>
<p>You have two choices: you can use nested scopes
or you can use callable objects. For example, suppose you wanted to
define <tt class="docutils literal"><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>
<pre class="literal-block">
def linear(a,b):
def result(x):
return a*x + b
return result
</pre>
<p>Or using a callable object:</p>
<pre class="literal-block">
class linear:
def __init__(self, a, b):
self.a, self.b = a,b
def __call__(self, x):
return self.a * x + self.b
</pre>
<p>In both cases:</p>
<pre class="literal-block">
taxes = linear(0.3,2)
</pre>
<p>gives a callable object where taxes(10e6) == 0.3 * 10e6 + 2.</p>
<p>The callable object approach has the disadvantage that it is a bit
slower and results in slightly longer code. However, note that a
collection of callables can share their signature via inheritance:</p>
<pre class="literal-block">
class exponential(linear):
# __init__ inherited
def __call__(self, x):
return self.a * (x ** self.b)
</pre>
<p>Object can encapsulate state for several methods:</p>
<pre class="literal-block">
class counter:
value = 0
def set(self, x): self.value = x
def up(self): self.value=self.value+1
def down(self): self.value=self.value-1
count = counter()
inc, dec, reset = count.up, count.down, count.set
</pre>
<p>Here <tt class="docutils literal"><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
<h2><a class="toc-backref" href="#id17">2.10 How can my code discover the name of an object?</a></h2>
<p>Generally speaking, it can't, because objects don't really have
names. Essentially, assignment always binds a name to a value; The
same is true of <tt class="docutils literal"><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>
<pre class="literal-block">
class A:
pass
B = A
a = B()
b = a
print b
<__main__.A instance at 016D07CC>
print a
<__main__.A instance at 016D07CC>
</pre>
<p>Arguably the class has a name: even though it is bound to two names
and invoked through the name B the created instance is still reported
as an instance of class A. However, it is impossible to say whether
the instance's name is a or b, since both names are bound to the same
value.</p>
<p>Generally speaking it should not be necessary for your code to "know
the names" of particular values. Unless you are deliberately writing
introspective programs, this is usually an indication that a change of
approach might be beneficial.</p>
<p>In comp.lang.python, Fredrik Lundh once gave an excellent analogy in
answer to this question:</p>
<blockquote>
<p>The same way as you get the name of that cat you found on your
porch: the cat (object) itself cannot tell you its name, and it
doesn't really care -- so the only way to find out what it's called
is to ask all your neighbours (namespaces) if it's their cat
(object)...</p>
<p>....and don't be surprised if you'll find that it's known by many
<h2><a class="toc-backref" href="#id22">3.2 Why does -22 / 10 return -3?</a></h2>
<p>It's primarily driven by the desire that <tt class="docutils literal"><span class="pre">i%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>
<pre class="literal-block">
i == (i/j)*j + (i%j)
</pre>
<p>then integer division has to return the floor. C also requres that identity
to hold, and then compilers that truncate <tt class="docutils literal"><span class="pre">i/j</span></tt> need to make <tt class="docutils literal"><span class="pre">i%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%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's more useful
for <tt class="docutils literal"><span class="pre">i%j</span></tt> to be <tt class="docutils literal"><span class="pre">>=</span> <span class="pre">0</span></tt>. If the clock says 10 now, what did it say 200
<tt class="docutils literal"><span class="pre">ValueError</span></tt>. <tt class="docutils literal"><span class="pre">int(string,</span> <span class="pre">base)</span></tt> takes the base to convert from
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's
rules: a leading '0' indicates octal, and '0x' indicates a hex number.</p>
<p>Do not use the built-in function <tt class="docutils literal"><span class="pre">eval()</span></tt> if all you need is to
convert strings to numbers. <tt class="docutils literal"><span class="pre">eval()</span></tt> will be significantly slower
and it presents a security risk: someone could pass you a Python
expression that might have unwanted side effects. For example,
someone could pass <tt class="docutils literal"><span class="pre">__import__('os').system("rm</span> <span class="pre">-rf</span> <span class="pre">$HOME")</span></tt> which
would erase your home directory.</p>
<p><tt class="docutils literal"><span class="pre">eval()</span></tt> also has the effect of interpreting numbers as Python
expressions, so that e.g. eval('09') gives a syntax error because Python
regards numbers starting with '0' as octal (base 8).</p>
<h2><a class="toc-backref" href="#id24">3.4 How do I convert a number to a string?</a></h2>
<p>To convert, e.g., the number 144 to the string '144', use the built-in
function <tt class="docutils literal"><span class="pre">str()</span></tt>. If you want a hexadecimal or octal
representation, use the built-in functions <tt class="docutils literal"><span class="pre">hex()</span></tt> or <tt class="docutils literal"><span class="pre">oct()</span></tt>.
For fancy formatting, use <a class="reference external" href="../../doc/lib/typesseq-strings.html">the % operator</a> on strings, e.g. <tt class="docutils literal"><span class="pre">"%04d"</span> <span class="pre">%</span> <span class="pre">144</span></tt>
yields '0144' and <tt class="docutils literal"><span class="pre">"%.3f"</span> <span class="pre">%</span> <span class="pre">(1/3.0)</span></tt> yields '0.333'. See the library
<h2><a class="toc-backref" href="#id26">3.6 How do I use strings to call functions/methods?</a></h2>
<p>There are various techniques.</p>
<ul>
<li><p class="first">The best is to use a dictionary that maps strings to functions. The
primary advantage of this technique is that the strings do not need
to match the names of the functions. This is also the primary
technique used to emulate a case construct:</p>
<pre class="literal-block">
def a():
pass
def b():
pass
dispatch = {'go': a, 'stop': b} # Note lack of parens for funcs
dispatch[get_input()]() # Note trailing parens to call function
</pre>
</li>
<li><p class="first">Use the built-in function <tt class="docutils literal"><span class="pre">getattr()</span></tt>:</p>
<pre class="literal-block">
import foo
getattr(foo, 'bar')()
</pre>
<p>Note that getattr() works on any object, including classes, class
instances, modules, and so on.</p>
<p>This is used in several places in the standard library, like
this:</p>
<pre class="literal-block">
class Foo:
def do_foo(self):
...
def do_bar(self):
...
f = getattr(foo_instance, 'do_' + opname)
f()
</pre>
</li>
<li><p class="first">Use <tt class="docutils literal"><span class="pre">locals()</span></tt> or <tt class="docutils literal"><span class="pre">eval()</span></tt> to resolve the function name:</p>
<pre class="literal-block">
def myFunc():
print "hello"
fname = "myFunc"
f = locals()[fname]
f()
f = eval(fname)
f()
</pre>
<p>Note: Using <tt class="docutils literal"><span class="pre">eval()</span></tt> is slow and dangerous. If you don't have absolute control
over the contents of the string, someone could pass a string that
resulted in an arbitrary function being executed.</p>
<h2><a class="toc-backref" href="#id29">3.9 What does 'UnicodeError: ASCII [decoding,encoding] error: ordinal not in range(128)' mean?</a></h2>
<p>This error indicates that your Python installation can handle
only 7-bit ASCII strings. There are a couple ways to fix or
work around the problem.</p>
<p>If your programs must handle data in arbitary character set encodings,
the environment the application runs in will generally identify the
encoding of the data it is handing you. You need to convert the input
to Unicode data using that encoding. For example, a program that
handles email or web input will typically find character set encoding
information in Content-Type headers. This can then be used to
properly convert input data to Unicode. Assuming the string referred
to by <tt class="docutils literal"><span class="pre">value</span></tt> is encoded as UTF-8:</p>
<pre class="literal-block">
value = unicode(value, "utf-8")
</pre>
<p>will return a Unicode object. If the data is not correctly encoded as
UTF-8, the above call will raise a <tt class="docutils literal"><span class="pre">UnicodeError</span></tt> exception.</p>
<p>If you only want strings coverted to Unicode which have non-ASCII
data, you can try converting them first assuming an ASCII encoding,
and then generate Unicode objects if that fails:</p>
<pre class="literal-block">
try:
x = unicode(value, "ascii")
except UnicodeError:
value = unicode(value, "utf-8")
else:
# value was valid ASCII data
pass
</pre>
<p>It's possible to set a default encoding in a file called <tt class="docutils literal"><span class="pre">sitecustomize.py</span></tt>
that's part of the Python library. However, this isn't recommended because changing the Python-wide default encoding may cause third-party extension modules to fail.</p>
<p>Note that on Windows, there is an encoding known as "mbcs", which uses
an encoding specific to your current locale. In many cases, and
particularly when working with COM, this may be an appropriate default
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 <tt class="docutils literal"><span class="pre">tuple()</span></tt> when you aren't sure that an object
is already a tuple.</p>
<p>The function <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>
<h2><a class="toc-backref" href="#id32">4.2 What's a negative index?</a></h2>
<p>Python sequences are indexed with positive numbers and
negative numbers. For positive numbers 0 is the first index
1 is the second index and so forth. For negative indices -1
is the last index and -2 is the pentultimate (next to last) index
and so forth. Think of <tt class="docutils literal"><span class="pre">seq[-n]</span></tt> as the same as <tt class="docutils literal"><span class="pre">seq[len(seq)-n]</span></tt>.</p>
<p>Using negative indices can be very convenient. For example <tt class="docutils literal"><span class="pre">S[:-1]</span></tt>
is all of the string except for its last character, which is useful
for removing the trailing newline from a string.</p>
<h2><a class="toc-backref" href="#id36">4.6 How do I create a multidimensional list?</a></h2>
<p>You probably tried to make a multidimensional array like this:</p>
<pre class="literal-block">
A = [[None] * 2] * 3
</pre>
<p>This looks correct if you print it:</p>
<pre class="literal-block">
>>> A
[[None, None], [None, None], [None, None]]
</pre>
<p>But when you assign a value, it shows up in multiple places:</p>
<blockquote>
<pre class="doctest-block">
>>> A[0][0] = 5
>>> A
[[5, None], [5, None], [5, None]]
</pre>
</blockquote>
<p>The reason is that replicating a list with <tt class="docutils literal"><span class="pre">*</span></tt> doesn't create copies, it only creates references to the existing objects. The <tt class="docutils literal"><span class="pre">*3</span></tt>
creates a list containing 3 references to the same list of length
two. Changes to one row will show in all rows, which is almost certainly
not what you want.</p>
<p>The suggested approach is to create a list of the desired length first
and then fill in each element with a newly created list:</p>
<pre class="literal-block">
A = [None]*3
for i in range(3):
A[i] = [None] * 2
</pre>
<p>This generates a list containing 3 different lists of length two.
You can also use a list comprehension:</p>
<pre class="literal-block">
w,h = 2,3
A = [ [None]*w for i in range(h) ]
</pre>
<p>Or, you can use an extension that provides a matrix datatype; <a class="reference external" href="http://www.pfdubois.com/numpy/">Numeric
<h2><a class="toc-backref" href="#id44">6.2 What is a method?</a></h2>
<p>A method is a function on some object <tt class="docutils literal"><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>
<pre class="literal-block">
class C:
def meth (self, arg):
return arg*2 + self.attribute
</pre>
</div>
<div class="section" id="what-is-self">
<h2><a class="toc-backref" href="#id45">6.3 What is self?</a></h2>
<p>Self is merely a conventional name for the first argument of a method.
A method defined as <tt class="docutils literal"><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
<a class="reference external" href="general.html#why-must-self-be-used-explicitly-in-method-definitions-and-calls">Why must 'self' be used explicitly in method definitions and calls?</a></p>
<h2><a class="toc-backref" href="#id46">6.4 How do I check if an object is an instance of a given class or of a subclass of it?</a></h2>
<p>Use the built-in function <tt class="docutils literal"><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's built-in types, e.g.
<p>Note that most programs do not use <tt class="docutils literal"><span class="pre">isinstance()</span></tt> on user-defined
classes very often. If you are developing the classes yourself, a
more proper object-oriented style is to define methods on the classes
that encapsulate a particular behaviour, instead of checking the
object's class and doing a different thing based on what class it is.
For example, if you have a function that does something:</p>
<pre class="literal-block">
def search (obj):
if isinstance(obj, Mailbox):
# ... code to search a mailbox
elif isinstance(obj, Document):
# ... code to search a document
elif ...
</pre>
<p>A better approach is to define a <tt class="docutils literal"><span class="pre">search()</span></tt> method on all the
classes and just call it:</p>
<pre class="literal-block">
class Mailbox:
def search(self):
# ... code to search a mailbox
class Document:
def search(self):
# ... code to search a document
obj.search()
</pre>
</div>
<div class="section" id="what-is-delegation">
<h2><a class="toc-backref" href="#id47">6.5 What is delegation?</a></h2>
<p>Delegation is an object oriented technique (also called a design
pattern). Let's say you have an object <tt class="docutils literal"><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'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>
<pre class="literal-block">
class UpperOut:
def __init__(self, outfile):
self.__outfile = outfile
def write(self, s):
self.__outfile.write(s.upper())
def __getattr__(self, name):
return getattr(self.__outfile, name)
</pre>
<p>Here the <tt class="docutils literal"><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="../../doc/ref/attribute-access.html">the language
reference</a> for
more information about controlling attribute access.</p>
<p>Note that for more general cases delegation can get trickier. When
attributes must be set as well as retrieved, the class must define a
<tt class="docutils literal"><span class="pre">__settattr__</span></tt> method too, and it must do so carefully. The basic
implementation of __setattr__ is roughly equivalent to the following:</p>
<pre class="literal-block">
class X:
...
def __setattr__(self, name, value):
self.__dict__[name] = value
...
</pre>
<p>Most __setattr__ implementations must modify
self.__dict__ to store local state for self without
<h2><a class="toc-backref" href="#id48">6.6 How do I call a method defined in a base class from a derived class that overrides it?</a></h2>
<p>If you're using new-style classes, use the built-in <tt class="docutils literal"><span class="pre">super()</span></tt> function:</p>
<pre class="literal-block">
class Derived(Base):
def meth (self):
super(Derived, self).meth()
</pre>
<p>If you're using classic classes: For a class definition such as
<tt class="docutils literal"><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>'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>
<h2><a class="toc-backref" href="#id50">6.8 How do I create static class data and static class methods?</a></h2>
<p>Static data (in the sense of C++ or Java) is easy; static methods
(again in the sense of C++ or Java) are not supported directly.</p>
<p>For static data, simply define a class attribute. To assign a new
value to the attribute, you have to explicitly use the class name in
the assignment:</p>
<pre class="literal-block">
class C:
count = 0 # number of times C.__init__ called
def __init__(self):
C.count = C.count + 1
def getcount(self):
return C.count # or return self.count
</pre>
<p><tt class="docutils literal"><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 vrbl named "count" in <tt class="docutils literal"><span class="pre">self</span></tt>'s own dict.
Rebinding of a class-static data name must always specify the class
whether inside a method or not:</p>
<pre class="literal-block">
C.count = 314
</pre>
<p>Static methods are possible when you're using new-style classes:</p>
<pre class="literal-block">
class C:
def static(arg1, arg2, arg3):
# No 'self' parameter!
...
static = staticmethod(static)
</pre>
<p>However, a far more straightforward way to get the effect of a static
method is via a simple module-level function:</p>
<pre class="literal-block">
def getcount():
return C.count
</pre>
<p>If your code is structured so as to define one class (or tightly
related class hierarchy) per module, this supplies the desired
<h2><a class="toc-backref" href="#id52">6.10 I try to use __spam and I get an error about _SomeClassName__spam.</a></h2>
<p>Variables with double leading underscore are "mangled" to provide a
simple but effective way to define class private variables. Any
identifier of the form <tt class="docutils literal"><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't guarantee privacy: an outside user can still deliberately
access the "_classname__spam" attribute, and private values are visible
in the object's <tt class="docutils literal"><span class="pre">__dict__</span></tt>. Many Python programmers never bother to use
<h2><a class="toc-backref" href="#id53">6.11 My class defines __del__ but it is not called when I delete the object.</a></h2>
<p>There are several possible reasons for this.</p>
<p>The del statement does not necessarily call __del__ -- it simply
decrements the object's reference count, and if this reaches zero
__del__ is called.</p>
<p>If your data structures contain circular links (e.g. a tree where each
child has a parent reference and each parent has a list of children)
the reference counts will never go back to zero. Once in a while
Python runs an algorithm to detect such cycles, but the garbage
collector might run some time after the last reference to your data
structure vanishes, so your __del__ method may be called at an
inconvenient and random time. This is inconvenient if you're trying to
reproduce a problem. Worse, the order in which object's __del__
methods are executed is arbitrary. You can run <tt class="docutils literal"><span class="pre">gc.collect()</span></tt> to
force a collection, but there <em>are</em> pathological cases where objects will
never be collected.</p>
<p>Despite the cycle collector, it's still a good idea to define an
explicit <tt class="docutils literal"><span class="pre">close()</span></tt> method on objects to be called whenever you'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't call <tt class="docutils literal"><span class="pre">__del__</span></tt> directly --
<tt class="docutils literal"><span class="pre">__del__</span></tt> should call <tt class="docutils literal"><span class="pre">close()</span></tt> and <tt class="docutils literal"><span class="pre">close()</span></tt> should make sure
that it can be called more than once for the same object.</p>
<p>Another way to avoid cyclical references is to use the "weakref"
module, which allows you to point to objects without incrementing
their reference count. Tree data structures, for instance, should use
weak references for their parent and sibling references (if they need
them!).</p>
<p>If the object has ever been a local variable in a function that caught
an expression in an except clause, chances are that a reference to the
object still exists in that function's stack frame as contained in the
stack trace. Normally, calling <tt class="docutils literal"><span class="pre">sys.exc_clear()</span></tt> will take care of
this by clearing the last recorded exception.</p>
<p>Finally, if your __del__ method raises an exception, a warning message
<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'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't being
imported.</p>
<p>If you need to create abc.pyc -- that is, to create a .pyc file for a
module that is not imported -- you can, using the py_compile and
compileall modules.</p>
<p>The <tt class="docutils literal"><span class="pre">py_compile</span></tt> 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>
<pre class="literal-block">
>>> import py_compile
>>> py_compile.compile('abc.py')
</pre>
<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 <tt class="docutils literal"><span class="pre">compileall</span></tt> 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>