9. Classes

node10.html | tut.html | node12.html | Python Tutorial | node2.html
---
- 9.1 A Word About Terminology (node11.html#SECTION0011100000000000000000)
  9.2 Python Scopes and Name Spaces (node11.html#SECTION0011200000000000000000)
  9.3 A First Look at Classes (node11.html#SECTION0011300000000000000000)
  - 9.3.1 Class Definition Syntax (node11.html#SECTION0011310000000000000000)
  9.3.2 Class Objects (node11.html#SECTION0011320000000000000000)
  9.3.3 Instance Objects (node11.html#SECTION0011330000000000000000)
  9.3.4 Method Objects (node11.html#SECTION0011340000000000000000)
  9.4 Random Remarks (node11.html#SECTION0011400000000000000000)
  9.5 Inheritance (node11.html#SECTION0011500000000000000000)
  - 9.5.1 Multiple Inheritance (node11.html#SECTION0011510000000000000000)
  9.6 Private Variables (node11.html#SECTION0011600000000000000000)
  9.7 Odds and Ends (node11.html#SECTION0011700000000000000000)
  - 9.7.1 Exceptions Can Be Classes (node11.html#SECTION0011710000000000000000)
---
# 9. Classes
Python's class mechanism adds classes to the language with a minimum
of new syntax and semantics. It is a mixture of the class mechanisms
found in C++ and Modula-3. As is true for modules, classes in Python
do not put an absolute barrier between definition and user, but rather
rely on the politeness of the user not to ``break into the
definition.'' The most important features of classes are retained
with full power, however: the class inheritance mechanism allows
multiple base classes, a derived class can override any methods of its
base class or classes, a method can call the method of a base class with the
same name. Objects can contain an arbitrary amount of private data.
In C++ terminology, all class members (including the data members) are
public, and all member functions are virtual. There are
no special constructors or destructors. As in Modula-3, there are no
shorthands for referencing the object's members from its methods: the
method function is declared with an explicit first argument
representing the object, which is provided implicitly by the call. As
in Smalltalk, classes themselves are objects, albeit in the wider
sense of the word: in Python, all data types are objects. This
provides semantics for importing and renaming. But, just like in
C++ or Modula-3, built-in types cannot be used as base classes for
extension by the user. Also, like in C++ but unlike in Modula-3, most
built-in operators with special syntax (arithmetic operators,
subscripting etc.) can be redefined for class instances.
# 9.1 A Word About Terminology
Lacking universally accepted terminology to talk about classes, I will
make occasional use of Smalltalk and C++ terms. (I would use Modula-3
terms, since its object-oriented semantics are closer to those of
Python than C++, but I expect that few readers have heard of it.)
I also have to warn you that there's a terminological pitfall for
object-oriented readers: the word ``object'' in Python does not
necessarily mean a class instance. Like C++ and Modula-3, and
unlike Smalltalk, not all types in Python are classes: the basic
built-in types like integers and lists are not, and even somewhat more
exotic types like files aren't. However, all Python types
share a little bit of common semantics that is best described by using
the word object.
Objects have individuality, and multiple names (in multiple scopes)
can be bound to the same object. This is known as aliasing in other
languages. This is usually not appreciated on a first glance at
Python, and can be safely ignored when dealing with immutable basic
types (numbers, strings, tuples). However, aliasing has an
(intended!) effect on the semantics of Python code involving mutable
objects such as lists, dictionaries, and most types representing
entities outside the program (files, windows, etc.). This is usually
used to the benefit of the program, since aliases behave like pointers
in some respects. For example, passing an object is cheap since only
a pointer is passed by the implementation; and if a function modifies
an object passed as an argument, the caller will see the change -- this
obviates the need for two different argument passing mechanisms as in
Pascal.
# 9.2 Python Scopes and Name Spaces
Before introducing classes, I first have to tell you something about
Python's scope rules. Class definitions play some neat tricks with
name spaces, and you need to know how scopes and name spaces work to
fully understand what's going on. Incidentally, knowledge about this
subject is useful for any advanced Python programmer.
Let's begin with some definitions.
A name space is a mapping from names to objects. Most name
spaces are currently implemented as Python dictionaries, but that's
normally not noticeable in any way (except for performance), and it
may change in the future. Examples of name spaces are: the set of
built-in names (functions such as abs(), and built-in exception
names); the global names in a module; and the local names in a
function invocation. In a sense the set of attributes of an object
also form a name space. The important thing to know about name
spaces is that there is absolutely no relation between names in
different name spaces; for instance, two different modules may both
define a function ``maximize'' without confusion -- users of the
modules must prefix it with the module name.
By the way, I use the word attribute for any name following a
dot -- for example, in the expression `z.real`, `real` is
an attribute of the object `z`. Strictly speaking, references to
names in modules are attribute references: in the expression
`modname.funcname`, `modname` is a module object and
`funcname` is an attribute of it. In this case there happens to
be a straightforward mapping between the module's attributes and the
global names defined in the module: they share the same name
space!9.1 (#foot1279)
Attributes may be read-only or writable. In the latter case,
assignment to attributes is possible. Module attributes are writable:
you can write "modname.the_answer = 42". Writable attributes may
also be deleted with the del statement, e.g.
"del modname.the_answer".
Name spaces are created at different moments and have different
lifetimes. The name space containing the built-in names is created
when the Python interpreter starts up, and is never deleted. The
global name space for a module is created when the module definition
is read in; normally, module name spaces also last until the
interpreter quits. The statements executed by the top-level
invocation of the interpreter, either read from a script file or
interactively, are considered part of a module called
__main__, so they have their own global name space. (The
built-in names actually also live in a module; this is called
__builtin__.)
The local name space for a function is created when the function is
called, and deleted when the function returns or raises an exception
that is not handled within the function. (Actually, forgetting would
be a better way to describe what actually happens.) Of course,
recursive invocations each have their own local name space.
A scope is a textual region of a Python program where a name space
is directly accessible. ``Directly accessible'' here means that an
unqualified reference to a name attempts to find the name in the name
space.
Although scopes are determined statically, they are used dynamically.
At any time during execution, exactly three nested scopes are in use
(i.e., exactly three name spaces are directly accessible): the
innermost scope, which is searched first, contains the local names,
the middle scope, searched next, contains the current module's global
names, and the outermost scope (searched last) is the name space
containing built-in names.
Usually, the local scope references the local names of the (textually)
current function. Outside of functions, the local scope references
the same name space as the global scope: the module's name space.
Class definitions place yet another name space in the local scope.
It is important to realize that scopes are determined textually: the
global scope of a function defined in a module is that module's name
space, no matter from where or by what alias the function is called.
On the other hand, the actual search for names is done dynamically, at
run time -- however, the language definition is evolving towards
static name resolution, at ``compile'' time, so don't rely on dynamic
name resolution! (In fact, local variables are already determined
statically.)
A special quirk of Python is that assignments always go into the
innermost scope. Assignments do not copy data -- they just
bind names to objects. The same is true for deletions: the statement
"del x" removes the binding of `x` from the name space
referenced by the local scope. In fact, all operations that introduce
new names use the local scope: in particular, import statements and
function definitions bind the module or function name in the local
scope. (The global statement can be used to indicate that
particular variables live in the global scope.)
# 9.3 A First Look at Classes
Classes introduce a little bit of new syntax, three new object types,
and some new semantics.
## 9.3.1 Class Definition Syntax
The simplest form of class definition looks like this:
```text

class ClassName:
<statement-1>
.
.
.
<statement-N>
```
Class definitions, like function definitions
(def statements) must be executed before they have any
effect. (You could conceivably place a class definition in a branch
of an if statement, or inside a function.)
In practice, the statements inside a class definition will usually be
function definitions, but other statements are allowed, and sometimes
useful -- we'll come back to this later. The function definitions
inside a class normally have a peculiar form of argument list,
dictated by the calling conventions for methods -- again, this is
explained later.
When a class definition is entered, a new name space is created, and
used as the local scope -- thus, all assignments to local variables
go into this new name space. In particular, function definitions bind
the name of the new function here.
When a class definition is left normally (via the end), a class
object is created. This is basically a wrapper around the contents
of the name space created by the class definition; we'll learn more
about class objects in the next section. The original local scope
(the one in effect just before the class definitions was entered) is
reinstated, and the class object is bound here to the class name given
in the class definition header (ClassName in the example).
## 9.3.2 Class Objects
Class objects support two kinds of operations: attribute references
and instantiation.
Attribute references use the standard syntax used for all
attribute references in Python: `obj.name`. Valid attribute
names are all the names that were in the class's name space when the
class object was created. So, if the class definition looked like
this:
```text

class MyClass:
"A simple example class"
i = 12345
def f(x):
return 'hello world'
```
then `MyClass.i` and `MyClass.f` are valid attribute
references, returning an integer and a method object, respectively.
Class attributes can also be assigned to, so you can change the value
of `MyClass.i` by assignment. __doc__ is also a valid
attribute, returning the docstring belonging to the class: `"A
simple example class"`).
Class instantiation uses function notation. Just pretend that
the class object is a parameterless function that returns a new
instance of the class. For example (assuming the above class):
```text

x = MyClass()
```
creates a new instance of the class and assigns this object to
the local variable `x`.
The instantiation operation (``calling'' a class object) creates an
empty object. Many classes like to create objects in a known initial
state. Therefore a class may define a special method named
__init__(), like this:
```text

def __init__(self):
self.data = []
```
When a class defines an __init__() method, class
instantiation automatically invokes __init__() for the
newly-created class instance. So in this example, a new, initialized
instance can be obtained by:
```text

x = MyClass()
```
Of course, the __init__() method may have arguments for
greater flexibility. In that case, arguments given to the class
instantiation operator are passed on to __init__(). For
example,
```text

>>> class Complex:
... def __init__(self, realpart, imagpart):
... self.r = realpart
... self.i = imagpart
...
>>> x = Complex(3.0,-4.5)
>>> x.r, x.i
(3.0, -4.5)
```
## 9.3.3 Instance Objects
Now what can we do with instance objects? The only operations
understood by instance objects are attribute references. There are
two kinds of valid attribute names.
The first I'll call data attributes. These correspond to
``instance variables'' in Smalltalk, and to ``data members'' in
C++. Data attributes need not be declared; like local variables,
they spring into existence when they are first assigned to. For
example, if `x` is the instance of MyClass created above,
the following piece of code will print the value `16`, without
leaving a trace:
```text

x.counter = 1
while x.counter < 10:
x.counter = x.counter * 2
print x.counter
del x.counter
```
The second kind of attribute references understood by instance objects
are methods. A method is a function that ``belongs to'' an
object. (In Python, the term method is not unique to class instances:
other object types can have methods as well, e.g., list objects have
methods called append, insert, remove, sort, and so on. However,
below, we'll use the term method exclusively to mean methods of class
instance objects, unless explicitly stated otherwise.)
Valid method names of an instance object depend on its class. By
definition, all attributes of a class that are (user-defined) function
objects define corresponding methods of its instances. So in our
example, `x.f` is a valid method reference, since
`MyClass.f` is a function, but `x.i` is not, since
`MyClass.i` is not. But `x.f` is not the same thing as
`MyClass.f` -- it is a method object, not
a function object.
## 9.3.4 Method Objects
Usually, a method is called immediately, e.g.:
```text

x.f()
```
In our example, this will return the string `'hello world'`.
However, it is not necessary to call a method right away:
`x.f` is a method object, and can be stored away and called at a
later time. For example:
```text

xf = x.f
while 1:
print xf()
```
will continue to print "hello world" until the end of time.
What exactly happens when a method is called? You may have noticed
that `x.f()` was called without an argument above, even though
the function definition for f specified an argument. What
happened to the argument? Surely Python raises an exception when a
function that requires an argument is called without any -- even if
the argument isn't actually used...
Actually, you may have guessed the answer: the special thing about
methods is that the object is passed as the first argument of the
function. In our example, the call `x.f()` is exactly equivalent
to `MyClass.f(x)`. In general, calling a method with a list of
n arguments is equivalent to calling the corresponding function
with an argument list that is created by inserting the method's object
before the first argument.
If you still don't understand how methods work, a look at the
implementation can perhaps clarify matters. When an instance
attribute is referenced that isn't a data attribute, its class is
searched. If the name denotes a valid class attribute that is a
function object, a method object is created by packing (pointers to)
the instance object and the function object just found together in an
abstract object: this is the method object. When the method object is
called with an argument list, it is unpacked again, a new argument
list is constructed from the instance object and the original argument
list, and the function object is called with this new argument list.
# 9.4 Random Remarks
[These should perhaps be placed more carefully...]
Data attributes override method attributes with the same name; to
avoid accidental name conflicts, which may cause hard-to-find bugs in
large programs, it is wise to use some kind of convention that
minimizes the chance of conflicts, e.g., capitalize method names,
prefix data attribute names with a small unique string (perhaps just
an underscore), or use verbs for methods and nouns for data attributes.
Data attributes may be referenced by methods as well as by ordinary
users (``clients'') of an object. In other words, classes are not
usable to implement pure abstract data types. In fact, nothing in
Python makes it possible to enforce data hiding -- it is all based
upon convention. (On the other hand, the Python implementation,
written in C, can completely hide implementation details and control
access to an object if necessary; this can be used by extensions to
Python written in C.)
Clients should use data attributes with care -- clients may mess up
invariants maintained by the methods by stamping on their data
attributes. Note that clients may add data attributes of their own to
an instance object without affecting the validity of the methods, as
long as name conflicts are avoided -- again, a naming convention can
save a lot of headaches here.
There is no shorthand for referencing data attributes (or other
methods!) from within methods. I find that this actually increases
the readability of methods: there is no chance of confusing local
variables and instance variables when glancing through a method.
Conventionally, the first argument of methods is often called
`self`. This is nothing more than a convention: the name
`self` has absolutely no special meaning to Python. (Note,
however, that by not following the convention your code may be less
readable by other Python programmers, and it is also conceivable that
a class browser program be written which relies upon such a
convention.)
Any function object that is a class attribute defines a method for
instances of that class. It is not necessary that the function
definition is textually enclosed in the class definition: assigning a
function object to a local variable in the class is also ok. For
example:
```text

# Function defined outside the class
def f1(self, x, y):
return min(x, x+y)

class C:
f = f1
def g(self):
return 'hello world'
h = g
```
Now `f`, `g` and `h` are all attributes of class
C that refer to function objects, and consequently they are all
methods of instances of C -- `h` being exactly equivalent
to `g`. Note that this practice usually only serves to confuse
the reader of a program.
Methods may call other methods by using method attributes of the
`self` argument, e.g.:
```text

class Bag:
def __init__(self):
self.data = []
def add(self, x):
self.data.append(x)
def addtwice(self, x):
self.add(x)
self.add(x)
```
Methods may reference global names in the same way as ordinary
functions. The global scope associated with a method is the module
containing the class definition. (The class itself is never used as a
global scope!) While one rarely encounters a good reason for using
global data in a method, there are many legitimate uses of the global
scope: for one thing, functions and modules imported into the global
scope can be used by methods, as well as functions and classes defined
in it. Usually, the class containing the method is itself defined in
this global scope, and in the next section we'll find some good
reasons why a method would want to reference its own class!
# 9.5 Inheritance
Of course, a language feature would not be worthy of the name ``class''
without supporting inheritance. The syntax for a derived class
definition looks as follows:
```text

class DerivedClassName(BaseClassName):
<statement-1>
.
.
.
<statement-N>
```
The name BaseClassName must be defined in a scope containing
the derived class definition. Instead of a base class name, an
expression is also allowed. This is useful when the base class is
defined in another module, e.g.,
```text

class DerivedClassName(modname.BaseClassName):
```
Execution of a derived class definition proceeds the same as for a
base class. When the class object is constructed, the base class is
remembered. This is used for resolving attribute references: if a
requested attribute is not found in the class, it is searched in the
base class. This rule is applied recursively if the base class itself
is derived from some other class.
There's nothing special about instantiation of derived classes:
`DerivedClassName()` creates a new instance of the class. Method
references are resolved as follows: the corresponding class attribute
is searched, descending down the chain of base classes if necessary,
and the method reference is valid if this yields a function object.
Derived classes may override methods of their base classes. Because
methods have no special privileges when calling other methods of the
same object, a method of a base class that calls another method
defined in the same base class, may in fact end up calling a method of
a derived class that overrides it. (For C++ programmers: all methods
in Python are effectively virtual.)
An overriding method in a derived class may in fact want to extend
rather than simply replace the base class method of the same name.
There is a simple way to call the base class method directly: just
call "BaseClassName.methodname(self, arguments)". This is
occasionally useful to clients as well. (Note that this only works if
the base class is defined or imported directly in the global scope.)
## 9.5.1 Multiple Inheritance
Python supports a limited form of multiple inheritance as well. A
class definition with multiple base classes looks as follows:
```text

class DerivedClassName(Base1, Base2, Base3):
<statement-1>
.
.
.
<statement-N>
```
The only rule necessary to explain the semantics is the resolution
rule used for class attribute references. This is depth-first,
left-to-right. Thus, if an attribute is not found in
DerivedClassName, it is searched in Base1, then
(recursively) in the base classes of Base1, and only if it is
not found there, it is searched in Base2, and so on.
(To some people breadth first -- searching Base2 and
Base3 before the base classes of Base1 -- looks more
natural. However, this would require you to know whether a particular
attribute of Base1 is actually defined in Base1 or in
one of its base classes before you can figure out the consequences of
a name conflict with an attribute of Base2. The depth-first
rule makes no differences between direct and inherited attributes of
Base1.)
It is clear that indiscriminate use of multiple inheritance is a
maintenance nightmare, given the reliance in Python on conventions to
avoid accidental name conflicts. A well-known problem with multiple
inheritance is a class derived from two classes that happen to have a
common base class. While it is easy enough to figure out what happens
in this case (the instance will have a single copy of ``instance
variables'' or data attributes used by the common base class), it is
not clear that these semantics are in any way useful.
# 9.6 Private Variables
There is limited support for class-private
identifiers. Any identifier of the form `__spam` (at least two
leading underscores, at most one trailing underscore) is now textually
replaced with `_classname__spam`, where `classname` is the
current class name with leading underscore(s) stripped. This mangling
is done without regard of the syntactic position of the identifier, so
it can be used to define class-private instance and class variables,
methods, as well as globals, and even to store instance variables
private to this class on instances of other classes. Truncation
may occur when the mangled name would be longer than 255 characters.
Outside classes, or when the class name consists of only underscores,
no mangling occurs.
Name mangling is intended to give classes an easy way to define
``private'' instance variables and methods, without having to worry
about instance variables defined by derived classes, or mucking with
instance variables by code outside the class. Note that the mangling
rules are designed mostly to avoid accidents; it still is possible for
a determined soul to access or modify a variable that is considered
private. This can even be useful, e.g. for the debugger, and that's
one reason why this loophole is not closed. (Buglet: derivation of a
class with the same name as the base class makes use of private
variables of the base class possible.)
Notice that code passed to `exec`, `eval()` or
`evalfile()` does not consider the classname of the invoking
class to be the current class; this is similar to the effect of the
`global` statement, the effect of which is likewise restricted to
code that is byte-compiled together. The same restriction applies to
`getattr()`, `setattr()` and `delattr()`, as well as
when referencing `__dict__` directly.
Here's an example of a class that implements its own
`__getattr__` and `__setattr__` methods and stores all
attributes in a private variable, in a way that works in Python 1.4 as
well as in previous versions:
```text

class VirtualAttributes:
__vdict = None
__vdict_name = locals().keys()[0]

def __init__(self):
self.__dict__[self.__vdict_name] = {}

def __getattr__(self, name):
return self.__vdict[name]

def __setattr__(self, name, value):
self.__vdict[name] = value
```
# 9.7 Odds and Ends
Sometimes it is useful to have a data type similar to the Pascal
``record'' or C ``struct'', bundling together a couple of named data
items. An empty class definition will do nicely, e.g.:
```text

class Employee:
pass

john = Employee() # Create an empty employee record

# Fill the fields of the record
john.name = 'John Doe'
john.dept = 'computer lab'
john.salary = 1000
```
A piece of Python code that expects a particular abstract data type
can often be passed a class that emulates the methods of that data
type instead. For instance, if you have a function that formats some
data from a file object, you can define a class with methods
read() and readline() that gets the data from a string
buffer instead, and pass it as an argument.
Instance method objects have attributes, too: `m.im_self` is the
object of which the method is an instance, and `m.im_func` is the
function object corresponding to the method.
## 9.7.1 Exceptions Can Be Classes
User-defined exceptions are no longer limited to being string objects
-- they can be identified by classes as well. Using this mechanism it
is possible to create extensible hierarchies of exceptions.
There are two new valid (semantic) forms for the raise statement:
```text

raise Class, instance

raise instance
```
In the first form, `instance` must be an instance of
Class or of a class derived from it. The second form is a
shorthand for:
```text

raise instance.__class__, instance
```
An except clause may list classes as well as string objects. A class
in an except clause is compatible with an exception if it is the same
class or a base class thereof (but not the other way around -- an
except clause listing a derived class is not compatible with a base
class). For example, the following code will print B, C, D in that
order:
```text

class B:
pass
class C(B):
pass
class D(C):
pass

for c in [B, C, D]:
try:
raise c()
except D:
print "D"
except C:
print "C"
except B:
print "B"
```
Note that if the except clauses were reversed (with
"except B" first), it would have printed B, B, B -- the first
matching except clause is triggered.
When an error message is printed for an unhandled exception which is a
class, the class name is printed, then a colon and a space, and
finally the instance converted to a string using the built-in function
str().


10. What Now?

node11.html | tut.html | node13.html | Python Tutorial | node2.html
---
# 10. What Now?
Hopefully reading this tutorial has reinforced your interest in using
Python. Now what should you do?
You should read, or at least page through, the Library Reference,
which gives complete (though terse) reference material about types,
functions, and modules that can save you a lot of time when writing
Python programs. The standard Python distribution includes a
lot of code in both C and Python; there are modules to read
Unix mailboxes, retrieve documents via HTTP, generate random
numbers, parse command-line options, write CGI programs, compress
data, and a lot more; skimming through the Library Reference will give
you an idea of what's available.
The major Python Web site is http://www.python.org; it contains
code, documentation, and pointers to Python-related pages around the
Web. This web site is mirrored in various places around the
world, such as Europe, Japan, and Australia; a mirror may be faster
than the main site, depending on your geographical location. A more
informal site is http://starship.python.net/, which contains a
bunch of Python-related personal home pages; many people have
downloadable software there.
For Python-related questions and problem reports, you can post to the
newsgroup comp.lang.python (news:comp.lang.python), or send them to the mailing
list at python-list@cwi.nl. The newsgroup and mailing list
are gatewayed, so messages posted to one will automatically be
forwarded to the other. There are around 35-45 postings a day,
asking (and answering) questions, suggesting new features, and
announcing new modules. Before posting, be sure to check the list of
Frequently Asked Questions (also called the FAQ), at
http://www.python.org/doc/FAQ.html, or look for it in the
Misc/ directory of the Python source distribution. The FAQ
answers many of the questions that come up again and again, and may
already contain the solution for your problem.
You can support the Python community by joining the Python Software
Activity, which runs the python.org web, ftp and email servers, and
organizes Python workshops. See http://www.python.org/psa/ for
information on how to join.


node12.html | tut.html | node14.html | Python Tutorial | node2.html
---
- A.1 Line Editing (node13.html#SECTION0013100000000000000000)
  A.2 History Substitution (node13.html#SECTION0013200000000000000000)
  A.3 Key Bindings (node13.html#SECTION0013300000000000000000)
  A.4 Commentary (node13.html#SECTION0013400000000000000000)
---
# A. Interactive Input Editing and History Substitution
Some versions of the Python interpreter support editing of the current
input line and history substitution, similar to facilities found in
the Korn shell and the GNU Bash shell. This is implemented using the
GNU Readline library, which supports Emacs-style and vi-style
editing. This library has its own documentation which I won't
duplicate here; however, the basics are easily explained. The
interactive editing and history described here are optionally
available in the Unix and CygWin versions of the interpreter.
This chapter does not document the editing facilities of Mark
Hammond's PythonWin package or the Tk-based environment, IDLE,
distributed with Python. The command line history recall which
operates within DOS boxes on NT and some other DOS and Windows flavors
is yet another beast.
# A.1 Line Editing
If supported, input line editing is active whenever the interpreter
prints a primary or secondary prompt. The current line can be edited
using the conventional Emacs control characters. The most important
of these are: C-A (Control-A) moves the cursor to the beginning of the
line, C-E to the end, C-B moves it one position to the left, C-F to
the right. Backspace erases the character to the left of the cursor,
C-D the character to its right. C-K kills (erases) the rest of the
line to the right of the cursor, C-Y yanks back the last killed
string. C-underscore undoes the last change you made; it can be
repeated for cumulative effect.
# A.2 History Substitution
History substitution works as follows. All non-empty input lines
issued are saved in a history buffer, and when a new prompt is given
you are positioned on a new line at the bottom of this buffer. C-P
moves one line up (back) in the history buffer, C-N moves one down.
Any line in the history buffer can be edited; an asterisk appears in
front of the prompt to mark a line as modified. Pressing the Return
key passes the current line to the interpreter. C-R starts an
incremental reverse search; C-S starts a forward search.
# A.3 Key Bindings
The key bindings and some other parameters of the Readline library can
be customized by placing commands in an initialization file called
$HOME/.inputrc. Key bindings have the form
```text

key-name: function-name
```
or
```text

"string": function-name
```
and options can be set with
```text

set option-name value
```
For example:
```text

# I prefer vi-style editing:
set editing-mode vi
# Edit using a single line:
set horizontal-scroll-mode On
# Rebind some keys:
Meta-h: backward-kill-word
"\C-u": universal-argument
"\C-x\C-r": re-read-init-file
```
Note that the default binding for TAB in Python is to insert a TAB
instead of Readline's default filename completion function. If you
insist, you can override this by putting
```text

TAB: complete
```
in your $HOME/.inputrc. (Of course, this makes it hard to type
indented continuation lines...)
Automatic completion of variable and module names is optionally
available. To enable it in the interpreter's interactive mode, add
the following to your $HOME/.pythonrc.py file:
```text

import rlcompleter, readline
readline.parse_and_bind('tab: complete')
```
This binds the TAB key to the completion function, so hitting the TAB
key twice suggests completions; it looks at Python statement names,
the current local variables, and the available module names. For
dotted expressions such as `string.a`, it will evaluate the the
expression up to the final "." and then suggest completions
from the attributes of the resulting object. Note that this may
execute application-defined code if an object with a
__getattr__() method is part of the expression.
# A.4 Commentary
This facility is an enormous step forward compared to previous
versions of the interpreter; however, some wishes are left: It would
be nice if the proper indentation were suggested on continuation lines
(the parser knows if an indent token is required next). The
completion mechanism might use the interpreter's symbol table. A
command to check (or even suggest) matching parentheses, quotes etc.
would also be useful.


About this document ...

node13.html | tut.html | Python Tutorial | node2.html
---
# About this document ...
Python Tutorial,
September 18, 2000, Release 1.6
This document was generated using the LaTeX2HTML (http://saftsack.fs.uni-bayreuth.de/~latex2ht/) translator.
LaTeX2HTML (http://saftsack.fs.uni-bayreuth.de/~latex2ht/) is Copyright ©
1993, 1994, 1995, 1996, 1997, Nikos
Drakos (http://cbl.leeds.ac.uk/nikos/personal.html), Computer Based Learning Unit, University of
Leeds, and Copyright © 1997, 1998, Ross
Moore (http://www.maths.mq.edu.au/~ross/), Mathematics Department, Macquarie University,
Sydney.
The application of LaTeX2HTML (http://saftsack.fs.uni-bayreuth.de/~latex2ht/) to the Python
documentation has been heavily tailored by Fred L. Drake,
Jr. Original navigation icons were contributed by Christopher
Petrilli.
---
## Comments and Questions
General comments and questions regarding this document should
be sent by email to python-docs@python.org (mailto:python-docs@python.org). If you find specific errors in
this document, please report the bug at the Python Bug
Tracker (http://sourceforge.net/bugs/?group_id=5470) at SourceForge (http://sourceforge.net/).
Questions regarding how to use the information in this
document should be sent to the Python news group, comp.lang.python (news:comp.lang.python), or the Python mailing list (http://www.python.org/mailman/listinfo/python-list) (which is gated to the newsgroup and
carries the same content).
For any of these channels, please be sure not to send HTML email.
Thanks.
---
node13.html | tut.html | Python Tutorial | node2.html
---


Contents

node1.html | tut.html | node3.html | Python Tutorial
---
## Contents
Table of Contents
- - 1.1 Where From Here (node3.html)
  2.1 Invoking the Interpreter (node4.html)
  - 2.1.1 Argument Passing (node4.html#SECTION004110000000000000000)
  2.1.2 Interactive Mode (node4.html#SECTION004120000000000000000)
  2.2 The Interpreter and Its Environment (node4.html#SECTION004200000000000000000)
  - 2.2.1 Error Handling (node4.html#SECTION004210000000000000000)
  2.2.2 Executable Python Scripts (node4.html#SECTION004220000000000000000)
  2.2.3 The Interactive Startup File (node4.html#SECTION004230000000000000000)
  3.1 Using Python as a Calculator (node5.html)
  - 3.1.1 Numbers (node5.html#SECTION005110000000000000000)
  3.1.2 Strings (node5.html#SECTION005120000000000000000)
  3.1.3 Unicode Strings (node5.html#SECTION005130000000000000000)
  3.1.4 Lists (node5.html#SECTION005140000000000000000)
  3.2 First Steps Towards Programming (node5.html#SECTION005200000000000000000)
  4.1 if Statements (node6.html)
  4.2 for Statements (node6.html#SECTION006200000000000000000)
  4.3 The range() Function (node6.html#SECTION006300000000000000000)
  4.4 break and continue Statements, and
  else Clauses on Loops (node6.html#SECTION006400000000000000000)
  4.5 pass Statements (node6.html#SECTION006500000000000000000)
  4.6 Defining Functions (node6.html#SECTION006600000000000000000)
  4.7 More on Defining Functions (node6.html#SECTION006700000000000000000)
  - 4.7.1 Default Argument Values (node6.html#SECTION006710000000000000000)
  4.7.2 Keyword Arguments (node6.html#SECTION006720000000000000000)
  4.7.3 Arbitrary Argument Lists (node6.html#SECTION006730000000000000000)
  4.7.4 Lambda Forms (node6.html#SECTION006740000000000000000)
  4.7.5 Documentation Strings (node6.html#SECTION006750000000000000000)
  5.1 More on Lists (node7.html)
  - 5.1.1 Using Lists as Stacks (node7.html#SECTION007110000000000000000)
  5.1.2 Using Lists as Queues (node7.html#SECTION007120000000000000000)
  5.1.3 Functional Programming Tools (node7.html#SECTION007130000000000000000)
  5.2 The del statement (node7.html#SECTION007200000000000000000)
  5.3 Tuples and Sequences (node7.html#SECTION007300000000000000000)
  5.4 Dictionaries (node7.html#SECTION007400000000000000000)
  5.5 More on Conditions (node7.html#SECTION007500000000000000000)
  5.6 Comparing Sequences and Other Types (node7.html#SECTION007600000000000000000)
  6.1 More on Modules (node8.html)
  - 6.1.1 The Module Search Path (node8.html#SECTION008110000000000000000)
  6.1.2 ``Compiled'' Python files (node8.html#SECTION008120000000000000000)
  6.2 Standard Modules (node8.html#SECTION008200000000000000000)
  6.3 The dir() Function (node8.html#SECTION008300000000000000000)
  6.4 Packages (node8.html#SECTION008400000000000000000)
  - 6.4.1 Importing * From a Package (node8.html#SECTION008410000000000000000)
  6.4.2 Intra-package References (node8.html#SECTION008420000000000000000)
  7.1 Fancier Output Formatting (node9.html)
  7.2 Reading and Writing Files (node9.html#SECTION009200000000000000000)
  - 7.2.1 Methods of File Objects (node9.html#SECTION009210000000000000000)
  7.2.2 The pickle Module (node9.html#SECTION009220000000000000000)
  8.1 Syntax Errors (node10.html)
  8.2 Exceptions (node10.html#SECTION0010200000000000000000)
  8.3 Handling Exceptions (node10.html#SECTION0010300000000000000000)
  8.4 Raising Exceptions (node10.html#SECTION0010400000000000000000)
  8.5 User-defined Exceptions (node10.html#SECTION0010500000000000000000)
  8.6 Defining Clean-up Actions (node10.html#SECTION0010600000000000000000)
  9.1 A Word About Terminology (node11.html)
  9.2 Python Scopes and Name Spaces (node11.html#SECTION0011200000000000000000)
  9.3 A First Look at Classes (node11.html#SECTION0011300000000000000000)
  - 9.3.1 Class Definition Syntax (node11.html#SECTION0011310000000000000000)
  9.3.2 Class Objects (node11.html#SECTION0011320000000000000000)
  9.3.3 Instance Objects (node11.html#SECTION0011330000000000000000)
  9.3.4 Method Objects (node11.html#SECTION0011340000000000000000)
  9.4 Random Remarks (node11.html#SECTION0011400000000000000000)
  9.5 Inheritance (node11.html#SECTION0011500000000000000000)
  - 9.5.1 Multiple Inheritance (node11.html#SECTION0011510000000000000000)
  9.6 Private Variables (node11.html#SECTION0011600000000000000000)
  9.7 Odds and Ends (node11.html#SECTION0011700000000000000000)
  - 9.7.1 Exceptions Can Be Classes (node11.html#SECTION0011710000000000000000)
  A.1 Line Editing (node13.html)
  A.2 History Substitution (node13.html#SECTION0013200000000000000000)
  A.3 Key Bindings (node13.html#SECTION0013300000000000000000)
  A.4 Commentary (node13.html#SECTION0013400000000000000000)
End of Table of Contents


1. Whetting Your Appetite

node2.html | tut.html | node4.html | Python Tutorial | node2.html
---
- 1.1 Where From Here (node3.html#SECTION003100000000000000000)
---
# 1. Whetting Your Appetite
If you ever wrote a large shell script, you probably know this
feeling: you'd love to add yet another feature, but it's already so
slow, and so big, and so complicated; or the feature involves a system
call or other function that is only accessible from C ...Usually
the problem at hand isn't serious enough to warrant rewriting the
script in C; perhaps the problem requires variable-length strings or
other data types (like sorted lists of file names) that are easy in
the shell but lots of work to implement in C, or perhaps you're not
sufficiently familiar with C.
Another situation: perhaps you have to work with several C libraries,
and the usual C write/compile/test/re-compile cycle is too slow. You
need to develop software more quickly. Possibly perhaps you've
written a program that could use an extension language, and you don't
want to design a language, write and debug an interpreter for it, then
tie it into your application.
In such cases, Python may be just the language for you. Python is
simple to use, but it is a real programming language, offering much
more structure and support for large programs than the shell has. On
the other hand, it also offers much more error checking than C, and,
being a very-high-level language, it has high-level data types
built in, such as flexible arrays and dictionaries that would cost you
days to implement efficiently in C. Because of its more general data
types Python is applicable to a much larger problem domain than
Awk or even Perl, yet many things are at least as easy
in Python as in those languages.
Python allows you to split up your program in modules that can be
reused in other Python programs. It comes with a large collection of
standard modules that you can use as the basis of your programs -- or
as examples to start learning to program in Python. There are also
built-in modules that provide things like file I/O, system calls,
sockets, and even interfaces to GUI toolkits like Tk.
Python is an interpreted language, which can save you considerable time
during program development because no compilation and linking is
necessary. The interpreter can be used interactively, which makes it
easy to experiment with features of the language, to write throw-away
programs, or to test functions during bottom-up program development.
It is also a handy desk calculator.
Python allows writing very compact and readable programs. Programs
written in Python are typically much shorter than equivalent C or
C++ programs, for several reasons:
- the high-level data types allow you to express complex operations in a
single statement;
- statement grouping is done by indentation instead of begin/end
brackets;
- no variable or argument declarations are necessary.
Python is extensible: if you know how to program in C it is easy
to add a new built-in function or module to the interpreter, either to
perform critical operations at maximum speed, or to link Python
programs to libraries that may only be available in binary form (such
as a vendor-specific graphics library). Once you are really hooked,
you can link the Python interpreter into an application written in C
and use it as an extension or command language for that application.
By the way, the language is named after the BBC show ``Monty Python's
Flying Circus'' and has nothing to do with nasty reptiles. Making
references to Monty Python skits in documentation is not only allowed,
it is encouraged!
# 1.1 Where From Here
Now that you are all excited about Python, you'll want to examine it
in some more detail. Since the best way to learn a language is
using it, you are invited here to do so.
In the next chapter, the mechanics of using the interpreter are
explained. This is rather mundane information, but essential for
trying out the examples shown later.
The rest of the tutorial introduces various features of the Python
language and system through examples, beginning with simple
expressions, statements and data types, through functions and modules,
and finally touching upon advanced concepts like exceptions
and user-defined classes.


2. Using the Python Interpreter

node3.html | tut.html | node5.html | Python Tutorial | node2.html
---
- 2.1 Invoking the Interpreter (node4.html#SECTION004100000000000000000)
  - 2.1.1 Argument Passing (node4.html#SECTION004110000000000000000)
  2.1.2 Interactive Mode (node4.html#SECTION004120000000000000000)
  2.2 The Interpreter and Its Environment (node4.html#SECTION004200000000000000000)
  - 2.2.1 Error Handling (node4.html#SECTION004210000000000000000)
  2.2.2 Executable Python Scripts (node4.html#SECTION004220000000000000000)
  2.2.3 The Interactive Startup File (node4.html#SECTION004230000000000000000)
---
# 2. Using the Python Interpreter
# 2.1 Invoking the Interpreter
The Python interpreter is usually installed as
/usr/local/bin/python on those machines where it is available;
putting /usr/local/bin in your Unix shell's search path
makes it possible to start it by typing the command
```text

python
```
to the shell. Since the choice of the directory where the interpreter
lives is an installation option, other places are possible; check with
your local Python guru or system administrator. (E.g.,
/usr/local/python is a popular alternative location.)
Typing an EOF character (Control-D on Unix, Control-Z on DOS
or Windows) at the primary prompt causes the interpreter to exit with
a zero exit status. If that doesn't work, you can exit the
interpreter by typing the following commands: "import sys;
sys.exit()".
The interpreter's line-editing features usually aren't very
sophisticated. On Unix, whoever installed the interpreter may have
enabled support for the GNU readline library, which adds more
elaborate interactive editing and history features. Perhaps the
quickest check to see whether command line editing is supported is
typing Control-P to the first Python prompt you get. If it beeps, you
have command line editing; see Appendix A for an introduction to the
keys. If nothing appears to happen, or if `P` is echoed,
command line editing isn't available; you'll only be able to use
backspace to remove characters from the current line.
The interpreter operates somewhat like the Unix shell: when called
with standard input connected to a tty device, it reads and executes
commands interactively; when called with a file name argument or with
a file as standard input, it reads and executes a script from
that file.
A third way of starting the interpreter is
"python -c command [arg] ...", which
executes the statement(s) in command, analogous to the shell's
-c option. Since Python statements often contain spaces
or other characters that are special to the shell, it is best to quote
command in its entirety with double quotes.
Note that there is a difference between "python file" and
"python <file". In the latter case, input requests from the
program, such as calls to `input()` and `raw_input()`, are
satisfied from file. Since this file has already been read
until the end by the parser before the program starts executing, the
program will encounter EOF immediately. In the former case (which is
usually what you want) they are satisfied from whatever file or device
is connected to standard input of the Python interpreter.
When a script file is used, it is sometimes useful to be able to run
the script and enter interactive mode afterwards. This can be done by
passing -i before the script. (This does not work if the
script is read from standard input, for the same reason as explained
in the previous paragraph.)
## 2.1.1 Argument Passing
When known to the interpreter, the script name and additional
arguments thereafter are passed to the script in the variable
`sys.argv`, which is a list of strings. Its length is at least
one; when no script and no arguments are given, `sys.argv[0]` is
an empty string. When the script name is given as `'-'` (meaning
standard input), `sys.argv[0]` is set to `'-'`. When
-c command is used, `sys.argv[0]` is set to
`'-c'`. Options found after -c command are
not consumed by the Python interpreter's option processing but left in
`sys.argv` for the command to handle.
## 2.1.2 Interactive Mode
When commands are read from a tty, the interpreter is said to be in
interactive mode. In this mode it prompts for the next command
with the primary prompt, usually three greater-than signs
("»> "); for continuation lines it prompts with the
secondary prompt, by default three dots ("... ").
The interpreter prints a welcome message stating its version number
and a copyright notice before printing the first prompt, e.g.:
```text

python
Python 1.6 (#22, Sep 2 2000, 23:54:55) [GCC egcs-2.91.66 19990314/Linux (egcs-1.1.2 release)] on linux2
Copyright (c) 1995-2000 Corporation for National Research Initiatives.
All Rights Reserved.
Copyright (c) 1991-1995 Stichting Mathematisch Centrum, Amsterdam.
All Rights Reserved.
>>>
```
Continuation lines are needed when entering a multi-line construct.
As an example, take a look at this if statement:
```text

>>> the_world_is_flat = 1
>>> if the_world_is_flat:
... print "Be careful not to fall off!"
...
Be careful not to fall off!
```
# 2.2 The Interpreter and Its Environment
## 2.2.1 Error Handling
When an error occurs, the interpreter prints an error
message and a stack trace. In interactive mode, it then returns to
the primary prompt; when input came from a file, it exits with a
nonzero exit status after printing
the stack trace. (Exceptions handled by an `except` clause in a
`try` statement are not errors in this context.) Some errors are
unconditionally fatal and cause an exit with a nonzero exit; this
applies to internal inconsistencies and some cases of running out of
memory. All error messages are written to the standard error stream;
normal output from the executed commands is written to standard
output.
Typing the interrupt character (usually Control-C or DEL) to the
primary or secondary prompt cancels the input and returns to the
primary prompt.2.1 (#foot108)Typing an interrupt while a command is executing raises the
`KeyboardInterrupt` exception, which may be handled by a
`try` statement.
## 2.2.2 Executable Python Scripts
On BSD'ish Unix systems, Python scripts can be made directly
executable, like shell scripts, by putting the line
```text

#! /usr/bin/env python
```
(assuming that the interpreter is on the user's $PATH) at the
beginning of the script and giving the file an executable mode. The
"#!" must be the first two characters of the file. Note that
the hash, or pound, character, "#", is used to start a
comment in Python.
## 2.2.3 The Interactive Startup File
When you use Python interactively, it is frequently handy to have some
standard commands executed every time the interpreter is started. You
can do this by setting an environment variable named
$PYTHONSTARTUP to the name of a file containing your start-up
commands. This is similar to the .profile feature of the
Unix shells.
This file is only read in interactive sessions, not when Python reads
commands from a script, and not when /dev/tty is given as the
explicit source of commands (which otherwise behaves like an
interactive session). It is executed in the same name space where
interactive commands are executed, so that objects that it defines or
imports can be used without qualification in the interactive session.
You can also change the prompts `sys.ps1` and `sys.ps2` in
this file.
If you want to read an additional start-up file from the current
directory, you can program this in the global start-up file,
e.g. "execfile('.pythonrc.py')". If
you want to use the startup file in a script, you must do this
explicitly in the script:
```text

import os
if os.environ.get('PYTHONSTARTUP') \
and os.path.isfile(os.environ['PYTHONSTARTUP']):
execfile(os.environ['PYTHONSTARTUP'])
```


3. An Informal Introduction to Python

node4.html | tut.html | node6.html | Python Tutorial | node2.html
---
- 3.1 Using Python as a Calculator (node5.html#SECTION005100000000000000000)
  - 3.1.1 Numbers (node5.html#SECTION005110000000000000000)
  3.1.2 Strings (node5.html#SECTION005120000000000000000)
  3.1.3 Unicode Strings (node5.html#SECTION005130000000000000000)
  3.1.4 Lists (node5.html#SECTION005140000000000000000)
  3.2 First Steps Towards Programming (node5.html#SECTION005200000000000000000)
---
# 3. An Informal Introduction to Python
In the following examples, input and output are distinguished by the
presence or absence of prompts ("»> " and "... "): to repeat
the example, you must type everything after the prompt, when the
prompt appears; lines that do not begin with a prompt are output from
the interpreter. Note that a secondary prompt on a line by itself in an example means
you must type a blank line; this is used to end a multi-line command.
Many of the examples in this manual, even those entered at the
interactive prompt, include comments. Comments in Python start with
the hash character, "#", and extend to the end of the
physical line. A comment may appear at the start of a line or
following whitespace or code, but not within a string literal. A hash
character within a string literal is just a hash character.
Some examples:
```text

# this is the first comment
SPAM = 1 # and this is the second comment
# ... and now a third!
STRING = "# This is not a comment."
```
# 3.1 Using Python as a Calculator
Let's try some simple Python commands. Start the interpreter and wait
for the primary prompt, "»> ". (It shouldn't take long.)
## 3.1.1 Numbers
The interpreter acts as a simple calculator: you can type an
expression at it and it will write the value. Expression syntax is
straightforward: the operators `+`, `-`, `*` and
`/` work just like in most other languages (for example, Pascal
or C); parentheses can be used for grouping. For example:
```text

>>> 2+2
4
>>> # This is a comment
... 2+2
4
>>> 2+2 # and a comment on the same line as code
4
>>> (50-5*6)/4
5
>>> # Integer division returns the floor:
... 7/3
2
>>> 7/-3
-3
```
Like in C, the equal sign ("=") is used to assign a value to a
variable. The value of an assignment is not written:
```text

>>> width = 20
>>> height = 5*9
>>> width * height
900
```
A value can be assigned to several variables simultaneously:
```text

>>> x = y = z = 0 # Zero x, y and z
>>> x
0
>>> y
0
>>> z
0
```
There is full support for floating point; operators with mixed type
operands convert the integer operand to floating point:
```text

>>> 4 * 2.5 / 3.3
3.0303030303
>>> 7.0 / 2
3.5
```
Complex numbers are also supported; imaginary numbers are written with
a suffix of "j" or "J". Complex numbers with a nonzero
real component are written as "(real+imagj)", or can
be created with the "complex(real, imag)" function.
```text

>>> 1j * 1J
(-1+0j)
>>> 1j * complex(0,1)
(-1+0j)
>>> 3+1j*3
(3+3j)
>>> (3+1j)*3
(9+3j)
>>> (1+2j)/(1+1j)
(1.5+0.5j)
```
Complex numbers are always represented as two floating point numbers,
the real and imaginary part. To extract these parts from a complex
number z, use `z .real` and `z .imag`.
```text

>>> a=1.5+0.5j
>>> a.real
1.5
>>> a.imag
0.5
```
The conversion functions to floating point and integer
(float(), int() and long()) don't
work for complex numbers -- there is no one correct way to convert a
complex number to a real number. Use `abs( z )` to get its
magnitude (as a float) or `z.real` to get its real part.
```text

>>> a=1.5+0.5j
>>> float(a)
Traceback (innermost last):
File "<stdin>", line 1, in ?
TypeError: can't convert complex to float; use e.g. abs(z)
>>> a.real
1.5
>>> abs(a)
1.58113883008
```
In interactive mode, the last printed expression is assigned to the
variable `_`. This means that when you are using Python as a
desk calculator, it is somewhat easier to continue calculations, for
example:
```text

>>> tax = 17.5 / 100
>>> price = 3.50
>>> price * tax
0.6125
>>> price + _
4.1125
>>> round(_, 2)
4.11
```
This variable should be treated as read-only by the user. Don't
explicitly assign a value to it -- you would create an independent
local variable with the same name masking the built-in variable with
its magic behavior.
## 3.1.2 Strings
Besides numbers, Python can also manipulate strings, which can be
expressed in several ways. They can be enclosed in single quotes or
double quotes:
```text

>>> 'spam eggs'
'spam eggs'
>>> 'doesn\'t'
"doesn't"
>>> "doesn't"
"doesn't"
>>> '"Yes," he said.'
'"Yes," he said.'
>>> "\"Yes,\" he said."
'"Yes," he said.'
>>> '"Isn\'t," she said.'
'"Isn\'t," she said.'
```
String literals can span multiple lines in several ways. Newlines can
be escaped with backslashes, e.g.:
```text

hello = "This is a rather long string containing\n\
several lines of text just as you would do in C.\n\
Note that whitespace at the beginning of the line is\
significant.\n"
print hello
```
which would print the following:
```text

This is a rather long string containing
several lines of text just as you would do in C.
Note that whitespace at the beginning of the line is significant.
```
Or, strings can be surrounded in a pair of matching triple-quotes:
`"""` or `'''`. End of lines do not need to be escaped
when using triple-quotes, but they will be included in the string.
```text

print """
Usage: thingy [OPTIONS]
-h Display this usage message
-H hostname Hostname to connect to
"""
```
produces the following output:
```text

Usage: thingy [OPTIONS]
-h Display this usage message
-H hostname Hostname to connect to
```
The interpreter prints the result of string operations in the same way
as they are typed for input: inside quotes, and with quotes and other
funny characters escaped by backslashes, to show the precise
value. The string is enclosed in double quotes if the string contains
a single quote and no double quotes, else it's enclosed in single
quotes. (The print statement, described later, can be used
to write strings without quotes or escapes.)
Strings can be concatenated (glued together) with the
`+` operator, and repeated with `*`:
```text

>>> word = 'Help' + 'A'
>>> word
'HelpA'
>>> '<' + word*5 + '>'
'<HelpAHelpAHelpAHelpAHelpA>'
```
Two string literals next to each other are automatically concatenated;
the first line above could also have been written "word = 'Help'
'A'"; this only works with two literals, not with arbitrary string
expressions:
```text

>>> import string
>>> 'str' 'ing' # <- This is ok
'string'
>>> string.strip('str') + 'ing' # <- This is ok
'string'
>>> string.strip('str') 'ing' # <- This is invalid
File "<stdin>", line 1
string.strip('str') 'ing'
^
SyntaxError: invalid syntax
```
Strings can be subscripted (indexed); like in C, the first character
of a string has subscript (index) 0. There is no separate character
type; a character is simply a string of size one. Like in Icon,
substrings can be specified with the slice notation: two indices
separated by a colon.
```text

>>> word[4]
'A'
>>> word[0:2]
'He'
>>> word[2:4]
'lp'
```
Unlike a C string, Python strings cannot be changed. Assigning to an
indexed position in the string results in an error:
```text

>>> word[0] = 'x'
Traceback (innermost last):
File "<stdin>", line 1, in ?
TypeError: object doesn't support item assignment
>>> word[:-1] = 'Splat'
Traceback (innermost last):
File "<stdin>", line 1, in ?
TypeError: object doesn't support slice assignment
```
However, creating a new string with the combined content is easy and
efficient:
```text

>>> 'x' + word[1:]
'xelpA'
>>> 'Splat' + word[-1:]
'SplatA'
```
Slice indices have useful defaults; an omitted first index defaults to
zero, an omitted second index defaults to the size of the string being
sliced.
```text

>>> word[:2] # The first two characters
'He'
>>> word[2:] # All but the first two characters
'lpA'
```
Here's a useful invariant of slice operations:
`s[:i] + s[i:]` equals `s`.
```text

>>> word[:2] + word[2:]
'HelpA'
>>> word[:3] + word[3:]
'HelpA'
```
Degenerate slice indices are handled gracefully: an index that is too
large is replaced by the string size, an upper bound smaller than the
lower bound returns an empty string.
```text

>>> word[1:100]
'elpA'
>>> word[10:]
''
>>> word[2:1]
''
```
Indices may be negative numbers, to start counting from the right.
For example:
```text

>>> word[-1] # The last character
'A'
>>> word[-2] # The last-but-one character
'p'
>>> word[-2:] # The last two characters
'pA'
>>> word[:-2] # All but the last two characters
'Hel'
```
But note that -0 is really the same as 0, so it does not count from
the right!
```text

>>> word[-0] # (since -0 equals 0)
'H'
```
Out-of-range negative slice indices are truncated, but don't try this
for single-element (non-slice) indices:
```text

>>> word[-100:]
'HelpA'
>>> word[-10] # error
Traceback (innermost last):
File "<stdin>", line 1
IndexError: string index out of range
```
The best way to remember how slices work is to think of the indices as
pointing between characters, with the left edge of the first
character numbered 0. Then the right edge of the last character of a
string of n characters has index n, for example:
```text

+---+---+---+---+---+
| H | e | l | p | A |
+---+---+---+---+---+
0 1 2 3 4 5
-5 -4 -3 -2 -1
```
The first row of numbers gives the position of the indices 0...5 in
the string; the second row gives the corresponding negative indices.
The slice from i to j consists of all characters between
the edges labeled i and j, respectively.
For non-negative indices, the length of a slice is the difference of
the indices, if both are within bounds, e.g., the length of
`word[1:3]` is 2.
The built-in function len() returns the length of a string:
```text

>>> s = 'supercalifragilisticexpialidocious'
>>> len(s)
34
```
## 3.1.3 Unicode Strings
Starting with Python 1.6 a new data type for storing text data is
available to the programmer: the Unicode object. It can be used to
store and manipulate Unicode data (see http://www.unicode.org)
and intergrates well with the existing string objects providing
auto-conversions where necessary.
Unicode has the advantage of providing one ordinal for every character
in every script used in modern and ancient texts. Previously, there
were only 256 possible ordinals for script characters and texts were
typically bound to a code page which mapped the ordinals to script
characters. This lead to very much confusion especially with respect
to internalization (usually written as "i18n" -- "i" +
18 characters + "n") of software. Unicode solves these
problems by defining one code page for all scripts.
Creating Unicode strings in Python is just as simple as creating
normal strings:
```text

>>> u'Hello World !'
u'Hello World !'
```
The small "u" in front of the quote indicates that an
Unicode string is supposed to be created. If you want to include
special characters in the string, you can do so by using the Python
Unicode-Escape encoding. The following example shows how:
```text

>>> u'Hello\\u0020World !'
u'Hello World !'
```
The escape sequence `u0020` indicates to insert the Unicode
character with the HEX ordinal 0x0020 (the space character) at the
given position.
Other characters are interpreted by using their respective ordinal
value directly as Unicode ordinal. Due to the fact that the lower 256
Unicode are the same as the standard Latin-1 encoding used in many
western countries, the process of entering Unicode is greatly
simplified.
For experts, there is also a raw mode just like for normal
strings. You have to prepend the string with a small 'r' to have
Python use the Raw-Unicode-Escape encoding. It will only apply
the above `uXXXX` conversion if there is an uneven number of
backslashes in front of the small 'u'.
```text

>>> ur'Hello\u0020World !'
u'Hello World !'
>>> ur'Hello\\u0020World !'
u'Hello\\\\u0020World !'
```
The raw mode is most useful when you have to enter lots of backslashes
e.g. in regular expressions.
Apart from these standard encodings, Python provides a whole set of
other ways of creating Unicod strings on the basis of a known
encoding.
The builtin unicode() provides access
to all registered Unicode codecs (COders and DECoders). Some of the
more well known encodings which these codecs can convert are
Latin-1, ASCII, UTF-8 and UTF-16. The latter two
are variable length encodings which permit to store Unicode characters
in 8 or 16 bits. Python uses UTF-8 as default encoding. This becomes
noticable when printing Unicode strings or writing them to files.
```text

>>> u""
u'\344\366\374'
>>> str(u"")
'\303\244\303\266\303\274'
```
If you have data in a specific encoding and want to produce a
corresponding Unicode string from it, you can use the
unicode() builtin with the encoding name as second
argument.
```text

>>> unicode('\303\244\303\266\303\274','UTF-8')
u'\344\366\374'
```
To convert the Unicode string back into a string using the original
encoding, the objects provide an encode() method.
```text

>>> u"".encode('UTF-8')
'\303\244\303\266\303\274'
```
## 3.1.4 Lists
Python knows a number of compound data types, used to group
together other values. The most versatile is the list, which
can be written as a list of comma-separated values (items) between
square brackets. List items need not all have the same type.
```text

>>> a = ['spam', 'eggs', 100, 1234]
>>> a
['spam', 'eggs', 100, 1234]
```
Like string indices, list indices start at 0, and lists can be sliced,
concatenated and so on:
```text

>>> a[0]
'spam'
>>> a[3]
1234
>>> a[-2]
100
>>> a[1:-1]
['eggs', 100]
>>> a[:2] + ['bacon', 2*2]
['spam', 'eggs', 'bacon', 4]
>>> 3*a[:3] + ['Boe!']
['spam', 'eggs', 100, 'spam', 'eggs', 100, 'spam', 'eggs', 100, 'Boe!']
```
Unlike strings, which are immutable, it is possible to change
individual elements of a list:
```text

>>> a
['spam', 'eggs', 100, 1234]
>>> a[2] = a[2] + 23
>>> a
['spam', 'eggs', 123, 1234]
```
Assignment to slices is also possible, and this can even change the size
of the list:
```text

>>> # Replace some items:
... a[0:2] = [1, 12]
>>> a
[1, 12, 123, 1234]
>>> # Remove some:
... a[0:2] = []
>>> a
[123, 1234]
>>> # Insert some:
... a[1:1] = ['bletch', 'xyzzy']
>>> a
[123, 'bletch', 'xyzzy', 1234]
>>> a[:0] = a # Insert (a copy of) itself at the beginning
>>> a
[123, 'bletch', 'xyzzy', 1234, 123, 'bletch', 'xyzzy', 1234]
```
The built-in function len() also applies to lists:
```text

>>> len(a)
8
```
It is possible to nest lists (create lists containing other lists),
for example:
```text

>>> q = [2, 3]
>>> p = [1, q, 4]
>>> len(p)
3
>>> p[1]
[2, 3]
>>> p[1][0]
2
>>> p[1].append('xtra') # See section 5.1
>>> p
[1, [2, 3, 'xtra'], 4]
>>> q
[2, 3, 'xtra']
```
Note that in the last example, `p[1]` and `q` really refer to
the same object! We'll come back to object semantics later.
# 3.2 First Steps Towards Programming
Of course, we can use Python for more complicated tasks than adding
two and two together. For instance, we can write an initial
subsequence of the Fibonacci series as follows:
```text

>>> # Fibonacci series:
... # the sum of two elements defines the next
... a, b = 0, 1
>>> while b < 10:
... print b
... a, b = b, a+b
...
1
1
2
3
5
8
```
This example introduces several new features.
- The first line contains a multiple assignment: the variables
`a` and `b` simultaneously get the new values 0 and 1. On the
last line this is used again, demonstrating that the expressions on
the right-hand side are all evaluated first before any of the
assignments take place. The right-hand side expressions are evaluated
from the left to the right.
- The while loop executes as long as the condition (here:
`b < 10`) remains true. In Python, like in C, any non-zero
integer value is true; zero is false. The condition may also be a
string or list value, in fact any sequence; anything with a non-zero
length is true, empty sequences are false. The test used in the
example is a simple comparison. The standard comparison operators are
written the same as in C: `<` (less than), `>` (greater than),
`==` (equal to), `<=` (less than or equal to),
`>=` (greater than or equal to) and `!=` (not equal to).
- The body of the loop is indented: indentation is Python's
way of grouping statements. Python does not (yet!) provide an
intelligent input line editing facility, so you have to type a tab or
space(s) for each indented line. In practice you will prepare more
complicated input for Python with a text editor; most text editors have
an auto-indent facility. When a compound statement is entered
interactively, it must be followed by a blank line to indicate
completion (since the parser cannot guess when you have typed the last
line). Note that each line within a basic block must be indented by
the same amount.
- The print statement writes the value of the expression(s) it is
given. It differs from just writing the expression you want to write
(as we did earlier in the calculator examples) in the way it handles
multiple expressions and strings. Strings are printed without quotes,
and a space is inserted between items, so you can format things nicely,
like this:
```text

>>> i = 256*256
>>> print 'The value of i is', i
The value of i is 65536
```
A trailing comma avoids the newline after the output:
```text

>>> a, b = 0, 1
>>> while b < 1000:
... print b,
... a, b = b, a+b
...
1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987
```
Note that the interpreter inserts a newline before it prints the next
prompt if the last line was not completed.


4. More Control Flow Tools

node5.html | tut.html | node7.html | Python Tutorial | node2.html
---
- 4.1 if Statements (node6.html#SECTION006100000000000000000)
  4.2 for Statements (node6.html#SECTION006200000000000000000)
  4.3 The range() Function (node6.html#SECTION006300000000000000000)
  4.4 break and continue Statements, and
  else Clauses on Loops (node6.html#SECTION006400000000000000000)
  4.5 pass Statements (node6.html#SECTION006500000000000000000)
  4.6 Defining Functions (node6.html#SECTION006600000000000000000)
  4.7 More on Defining Functions (node6.html#SECTION006700000000000000000)
  - 4.7.1 Default Argument Values (node6.html#SECTION006710000000000000000)
  4.7.2 Keyword Arguments (node6.html#SECTION006720000000000000000)
  4.7.3 Arbitrary Argument Lists (node6.html#SECTION006730000000000000000)
  4.7.4 Lambda Forms (node6.html#SECTION006740000000000000000)
  4.7.5 Documentation Strings (node6.html#SECTION006750000000000000000)
---
# 4. More Control Flow Tools
Besides the while statement just introduced, Python knows
the usual control flow statements known from other languages, with
some twists.
# 4.1 if Statements
Perhaps the most well-known statement type is the
if statement. For example:
```text

>>> x = int(raw_input("Please enter a number: "))
>>> if x < 0:
... x = 0
... print 'Negative changed to zero'
... elif x == 0:
... print 'Zero'
... elif x == 1:
... print 'Single'
... else:
... print 'More'
...
```
There can be zero or more elif parts, and the
else part is optional. The keyword `elif' is
short for `else if', and is useful to avoid excessive indentation. An
if ... elif ... elif ... sequence
is a substitute for the switch or
case statements found in other languages.
# 4.2 for Statements
The for statement in Python differs a bit from
what you may be used to in C or Pascal. Rather than always
iterating over an arithmetic progression of numbers (like in Pascal),
or giving the user the ability to define both the iteration step and
halting condition (as C), Python's
for statement iterates over the items of any
sequence (e.g., a list or a string), in the order that they appear in
the sequence. For example (no pun intended):
```text

>>> # Measure some strings:
... a = ['cat', 'window', 'defenestrate']
>>> for x in a:
... print x, len(x)
...
cat 3
window 6
defenestrate 12
```
It is not safe to modify the sequence being iterated over in the loop
(this can only happen for mutable sequence types, i.e., lists). If
you need to modify the list you are iterating over, e.g., duplicate
selected items, you must iterate over a copy. The slice notation
makes this particularly convenient:
```text

>>> for x in a[:]: # make a slice copy of the entire list
... if len(x) > 6: a.insert(0, x)
...
>>> a
['defenestrate', 'cat', 'window', 'defenestrate']
```
# 4.3 The range() Function
If you do need to iterate over a sequence of numbers, the built-in
function range() comes in handy. It generates lists
containing arithmetic progressions, e.g.:
```text

>>> range(10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
```
The given end point is never part of the generated list;
`range(10)` generates a list of 10 values, exactly the legal
indices for items of a sequence of length 10. It is possible to let
the range start at another number, or to specify a different increment
(even negative; sometimes this is called the `step'):
```text

>>> range(5, 10)
[5, 6, 7, 8, 9]
>>> range(0, 10, 3)
[0, 3, 6, 9]
>>> range(-10, -100, -30)
[-10, -40, -70]
```
To iterate over the indices of a sequence, combine
range() and len() as follows:
```text

>>> a = ['Mary', 'had', 'a', 'little', 'lamb']
>>> for i in range(len(a)):
... print i, a[i]
...
0 Mary
1 had
2 a
3 little
4 lamb
```
# 4.4 break and continue Statements, and
else Clauses on Loops
The break statement, like in C, breaks out of the smallest
enclosing for or while loop.
The continue statement, also borrowed from C, continues
with the next iteration of the loop.
Loop statements may have an `else` clause; it is executed when
the loop terminates through exhaustion of the list (with
for) or when the condition becomes false (with
while), but not when the loop is terminated by a
break statement. This is exemplified by the following loop,
which searches for prime numbers:
```text

>>> for n in range(2, 10):
... for x in range(2, n):
... if n % x == 0:
... print n, 'equals', x, '*', n/x
... break
... else:
... print n, 'is a prime number'
...
2 is a prime number
3 is a prime number
4 equals 2 * 2
5 is a prime number
6 equals 2 * 3
7 is a prime number
8 equals 2 * 4
9 equals 3 * 3
```
# 4.5 pass Statements
The pass statement does nothing.
It can be used when a statement is required syntactically but the
program requires no action.
For example:
```text

>>> while 1:
... pass # Busy-wait for keyboard interrupt
...
```
# 4.6 Defining Functions
We can create a function that writes the Fibonacci series to an
arbitrary boundary:
```text

>>> def fib(n): # write Fibonacci series up to n
... "Print a Fibonacci series up to n"
... a, b = 0, 1
... while b < n:
... print b,
... a, b = b, a+b
...
>>> # Now call the function we just defined:
... fib(2000)
1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597
```
The keyword def introduces a function definition. It
must be followed by the function name and the parenthesized list of
formal parameters. The statements that form the body of the function
start at the next line, and must be indented. The first statement of
the function body can optionally be a string literal; this string
literal is the function's documentation
string, or docstring.
There are tools which use docstrings to automatically produce online
or printed documentation, or to let the user interactively browse
through code; it's good practice to include docstrings in code that
you write, so try to make a habit of it.
The execution of a function introduces a new symbol table used
for the local variables of the function. More precisely, all variable
assignments in a function store the value in the local symbol table;
whereas variable references first look in the local symbol table, then
in the global symbol table, and then in the table of built-in names.
Thus, global variables cannot be directly assigned a value within a
function (unless named in a global statement), although
they may be referenced.
The actual parameters (arguments) to a function call are introduced in
the local symbol table of the called function when it is called; thus,
arguments are passed using call by value (where the
value is always an object reference, not the value of
the object).4.1 (#foot1221) When a function calls another function, a new local symbol table is
created for that call.
A function definition introduces the function name in the current
symbol table. The value of the function name
has a type that is recognized by the interpreter as a user-defined
function. This value can be assigned to another name which can then
also be used as a function. This serves as a general renaming
mechanism:
```text

>>> fib
<function object at 10042ed0>
>>> f = fib
>>> f(100)
1 1 2 3 5 8 13 21 34 55 89
```
You might object that `fib` is not a function but a procedure. In
Python, like in C, procedures are just functions that don't return a
value. In fact, technically speaking, procedures do return a value,
albeit a rather boring one. This value is called `None` (it's a
built-in name). Writing the value `None` is normally suppressed by
the interpreter if it would be the only value written. You can see it
if you really want to:
```text

>>> print fib(0)
None
```
It is simple to write a function that returns a list of the numbers of
the Fibonacci series, instead of printing it:
```text

>>> def fib2(n): # return Fibonacci series up to n
... "Return a list containing the Fibonacci series up to n"
... result = []
... a, b = 0, 1
... while b < n:
... result.append(b) # see below
... a, b = b, a+b
... return result
...
>>> f100 = fib2(100) # call it
>>> f100 # write the result
[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
```
This example, as usual, demonstrates some new Python features:
- The return statement returns with a value from a function.
return without an expression argument is used to return from
the middle of a procedure (falling off the end also returns from a
procedure), in which case the `None` value is returned.
- The statement `result.append(b)` calls a method of the list
object `result`. A method is a function that `belongs' to an
object and is named `obj.methodname`, where `obj` is some
object (this may be an expression), and `methodname` is the name
of a method that is defined by the object's type. Different types
define different methods. Methods of different types may have the
same name without causing ambiguity. (It is possible to define your
own object types and methods, using classes, as discussed later
in this tutorial.)
The method append() shown in the example, is defined for
list objects; it adds a new element at the end of the list. In this
example it is equivalent to "result = result + [b]", but more
efficient.
# 4.7 More on Defining Functions
It is also possible to define functions with a variable number of
arguments. There are three forms, which can be combined.
## 4.7.1 Default Argument Values
The most useful form is to specify a default value for one or more
arguments. This creates a function that can be called with fewer
arguments than it is defined, e.g.
```text

def ask_ok(prompt, retries=4, complaint='Yes or no, please!'):
while 1:
ok = raw_input(prompt)
if ok in ('y', 'ye', 'yes'): return 1
if ok in ('n', 'no', 'nop', 'nope'): return 0
retries = retries - 1
if retries < 0: raise IOError, 'refusenik user'
print complaint
```
This function can be called either like this:
`ask_ok('Do you really want to quit?')` or like this:
`ask_ok('OK to overwrite the file?', 2)`.
The default values are evaluated at the point of function definition
in the defining scope, so that e.g.
```text

i = 5
def f(arg = i): print arg
i = 6
f()
```
will print `5`.
Important warning: The default value is evaluated only once.
This makes a difference when the default is a mutable object such as a
list or dictionary. For example, the following function accumulates
the arguments passed to it on subsequent calls:
```text

def f(a, l = []):
l.append(a)
return l
print f(1)
print f(2)
print f(3)
```
This will print
```text

[1]
[1, 2]
[1, 2, 3]
```
If you don't want the default to be shared between subsequent calls,
you can write the function like this instead:
```text

def f(a, l = None):
if l is None:
l = []
l.append(a)
return l
```
## 4.7.2 Keyword Arguments
Functions can also be called using
keyword arguments of the form "keyword = value". For
instance, the following function:
```text

def parrot(voltage, state='a stiff', action='voom', type='Norwegian Blue'):
print "-- This parrot wouldn't", action,
print "if you put", voltage, "Volts through it."
print "-- Lovely plumage, the", type
print "-- It's", state, "!"
```
could be called in any of the following ways:
```text

parrot(1000)
parrot(action = 'VOOOOOM', voltage = 1000000)
parrot('a thousand', state = 'pushing up the daisies')
parrot('a million', 'bereft of life', 'jump')
```
but the following calls would all be invalid:
```text

parrot() # required argument missing
parrot(voltage=5.0, 'dead') # non-keyword argument following keyword
parrot(110, voltage=220) # duplicate value for argument
parrot(actor='John Cleese') # unknown keyword
```
In general, an argument list must have any positional arguments
followed by any keyword arguments, where the keywords must be chosen
from the formal parameter names. It's not important whether a formal
parameter has a default value or not. No argument may receive a
value more than once -- formal parameter names corresponding to
positional arguments cannot be used as keywords in the same calls.
Here's an example that fails due to this restriction:
```text

>>> def function(a):
... pass
...
>>> function(0, a=0)
Traceback (innermost last):
File "<stdin>", line 1, in ?
TypeError: keyword parameter redefined
```
When a final formal parameter of the form `** name` is
present, it receives a dictionary containing all keyword arguments
whose keyword doesn't correspond to a formal parameter. This may be
combined with a formal parameter of the form
`* name` (described in the next subsection) which receives a
tuple containing the positional arguments beyond the formal parameter
list. (`* name` must occur before `** name`.)
For example, if we define a function like this:
```text

def cheeseshop(kind, *arguments, **keywords):
print "-- Do you have any", kind, '?'
print "-- I'm sorry, we're all out of", kind
for arg in arguments: print arg
print '-'*40
for kw in keywords.keys(): print kw, ':', keywords[kw]
```
It could be called like this:
```text

cheeseshop('Limburger', "It's very runny, sir.",
"It's really very, VERY runny, sir.",
client='John Cleese',
shopkeeper='Michael Palin',
sketch='Cheese Shop Sketch')
```
and of course it would print:
```text

-- Do you have any Limburger ?
-- I'm sorry, we're all out of Limburger
It's very runny, sir.
It's really very, VERY runny, sir.
----------------------------------------
client : John Cleese
shopkeeper : Michael Palin
sketch : Cheese Shop Sketch
```
## 4.7.3 Arbitrary Argument Lists
Finally, the least frequently used option is to specify that a
function can be called with an arbitrary number of arguments. These
arguments will be wrapped up in a tuple. Before the variable number
of arguments, zero or more normal arguments may occur.
```text

def fprintf(file, format, *args):
file.write(format % args)
```
## 4.7.4 Lambda Forms
By popular demand, a few features commonly found in functional
programming languages and Lisp have been added to Python. With the
lambda keyword, small anonymous functions can be created.
Here's a function that returns the sum of its two arguments:
"lambda a, b: a+b". Lambda forms can be used wherever function
objects are required. They are syntactically restricted to a single
expression. Semantically, they are just syntactic sugar for a normal
function definition. Like nested function definitions, lambda forms
cannot reference variables from the containing scope, but this can be
overcome through the judicious use of default argument values, e.g.
```text

def make_incrementor(n):
return lambda x, incr=n: x+incr
```
## 4.7.5 Documentation Strings
There are emerging conventions about the content and formatting of
documentation strings.
The first line should always be a short, concise summary of the
object's purpose. For brevity, it should not explicitly state the
object's name or type, since these are available by other means
(except if the name happens to be a verb describing a function's
operation). This line should begin with a capital letter and end with
a period.
If there are more lines in the documentation string, the second line
should be blank, visually separating the summary from the rest of the
description. The following lines should be one or more paragraphs
describing the object's calling conventions, its side effects, etc.
The Python parser does not strip indentation from multi-line string
literals in Python, so tools that process documentation have to strip
indentation if desired. This is done using the following convention.
The first non-blank line after the first line of the string
determines the amount of indentation for the entire documentation
string. (We can't use the first line since it is generally adjacent
to the string's opening quotes so its indentation is not apparent in
the string literal.) Whitespace ``equivalent'' to this indentation is
then stripped from the start of all lines of the string. Lines that
are indented less should not occur, but if they occur all their
leading whitespace should be stripped. Equivalence of whitespace
should be tested after expansion of tabs (to 8 spaces, normally).
Here is an example of a multi-line docstring:
```text

>>> def my_function():
... """Do nothing, but document it.
...
... No, really, it doesn't do anything.
... """
... pass
...
>>> print my_function.__doc__
Do nothing, but document it.

No, really, it doesn't do anything.
```