8. Errors and Exceptions

node9.html | tut.html | node11.html | Python Tutorial | node2.html
---
- 8.1 Syntax Errors (#SECTION0010100000000000000000)
  8.2 Exceptions (#SECTION0010200000000000000000)
  8.3 Handling Exceptions (#SECTION0010300000000000000000)
  8.4 Raising Exceptions (#SECTION0010400000000000000000)
  8.5 User-defined Exceptions (#SECTION0010500000000000000000)
  8.6 Defining Clean-up Actions (#SECTION0010600000000000000000)
---
# 8. Errors and Exceptions
Until now error messages haven't been more than mentioned, but if you
have tried out the examples you have probably seen some. There are
(at least) two distinguishable kinds of errors:
syntax errors and exceptions.
# 8.1 Syntax Errors
Syntax errors, also known as parsing errors, are perhaps the most common
kind of complaint you get while you are still learning Python:
```text

>>> while 1 print 'Hello world'
File "<stdin>", line 1, in ?
while 1 print 'Hello world'
^
SyntaxError: invalid syntax
```
The parser repeats the offending line and displays a little `arrow'
pointing at the earliest point in the line where the error was
detected. The error is caused by (or at least detected at) the token
preceding the arrow: in the example, the error is detected at
the keyword print, since a colon (":") is missing
before it. File name and line number are printed so you know where to
look in case the input came from a script.
# 8.2 Exceptions
Even if a statement or expression is syntactically correct, it may
cause an error when an attempt is made to execute it.
Errors detected during execution are called exceptions and are
not unconditionally fatal: you will soon learn how to handle them in
Python programs. Most exceptions are not handled by programs,
however, and result in error messages as shown here:
```text

>>> 10 * (1/0)
Traceback (most recent call last):
File "<stdin>", line 1, in ?
ZeroDivisionError: integer division or modulo
>>> 4 + spam*3
Traceback (most recent call last):
File "<stdin>", line 1, in ?
NameError: spam
>>> '2' + 2
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: illegal argument type for built-in operation
```
The last line of the error message indicates what happened.
Exceptions come in different types, and the type is printed as part of
the message: the types in the example are
ZeroDivisionError, NameError and
TypeError.
The string printed as the exception type is the name of the built-in
name for the exception that occurred. This is true for all built-in
exceptions, but need not be true for user-defined exceptions (although
it is a useful convention).
Standard exception names are built-in identifiers (not reserved
keywords).
The rest of the line is a detail whose interpretation depends on the
exception type; its meaning is dependent on the exception type.
The preceding part of the error message shows the context where the
exception happened, in the form of a stack backtrace.
In general it contains a stack backtrace listing source lines; however,
it will not display lines read from standard input.
The Python Library
Reference (../lib/module-exceptions.html) lists the built-in exceptions and their meanings.
# 8.3 Handling Exceptions
It is possible to write programs that handle selected exceptions.
Look at the following example, which asks the user for input until a
valid integer has been entered, but allows the user to interrupt the
program (using Control-C or whatever the operating system
supports); note that a user-generated interruption is signalled by
raising the KeyboardInterrupt exception.
```text

>>> while 1:
... try:
... x = int(raw_input("Please enter a number: "))
... break
... except ValueError:
... print "Oops! That was no valid number. Try again..."
...
```
The try statement works as follows.
- First, the try clause (the statement(s) between the
try and except keywords) is executed.
- If no exception occurs, the except clause is skipped and
execution of the try statement is finished.
- If an exception occurs during execution of the try clause, the rest of
the clause is skipped. Then if its type matches the exception named
after the except keyword, the rest of the try clause is
skipped, the except clause is executed, and then execution continues
after the try statement.
- If an exception occurs which does not match the exception named in the
except clause, it is passed on to outer try statements; if
no handler is found, it is an unhandled exception and execution
stops with a message as shown above.
A try statement may have more than one except clause, to
specify handlers for different exceptions. At most one handler will
be executed. Handlers only handle exceptions that occur in the
corresponding try clause, not in other handlers of the same
try statement. An except clause may name multiple exceptions
as a parenthesized list, for example:
```text

... except (RuntimeError, TypeError, NameError):
... pass
```
The last except clause may omit the exception name(s), to serve as a
wildcard. Use this with extreme caution, since it is easy to mask a
real programming error in this way! It can also be used to print an
error message and then re-raise the exception (allowing a caller to
handle the exception as well):
```text

import string, sys

try:
f = open('myfile.txt')
s = f.readline()
i = int(string.strip(s))
except IOError, (errno, strerror):
print "I/O error(%s): %s" % (errno, strerror)
except ValueError:
print "Could not convert data to an integer."
except:
print "Unexpected error:", sys.exc_info()[0]
raise
```
The try ... except statement has an optional
else clause, which, when present, must follow all except
clauses. It is useful for code that must be executed if the try
clause does not raise an exception. For example:
```text

for arg in sys.argv[1:]:
try:
f = open(arg, 'r')
except IOError:
print 'cannot open', arg
else:
print arg, 'has', len(f.readlines()), 'lines'
f.close()
```
The use of the else clause is better than adding additional
code to the try clause because it avoids accidentally
catching an exception that wasn't raised by the code being protected
by the try ... except statement.
When an exception occurs, it may have an associated value, also known as
the exception's argument.
The presence and type of the argument depend on the exception type.
For exception types which have an argument, the except clause may
specify a variable after the exception name (or list) to receive the
argument's value, as follows:
```text

>>> try:
... spam()
... except NameError, x:
... print 'name', x, 'undefined'
...
name spam undefined
```
If an exception has an argument, it is printed as the last part
(`detail') of the message for unhandled exceptions.
Exception handlers don't just handle exceptions if they occur
immediately in the try clause, but also if they occur inside functions
that are called (even indirectly) in the try clause.
For example:
```text

>>> def this_fails():
... x = 1/0
...
>>> try:
... this_fails()
... except ZeroDivisionError, detail:
... print 'Handling run-time error:', detail
...
Handling run-time error: integer division or modulo
```
# 8.4 Raising Exceptions
The raise statement allows the programmer to force a
specified exception to occur.
For example:
```text

>>> raise NameError, 'HiThere'
Traceback (most recent call last):
File "<stdin>", line 1, in ?
NameError: HiThere
```
The first argument to raise names the exception to be
raised. The optional second argument specifies the exception's
argument.
If you need to determine whether an exception was raised but don't
intend to handle it, a simpler form of the raise statement
allows you to re-raise the exception:
```text

>>> try:
... raise NameError, 'HiThere'
... except NameError:
... print 'An exception flew by!'
... raise
...
An exception flew by!
Traceback (most recent call last):
File "<stdin>", line 2, in ?
NameError: HiThere
```
# 8.5 User-defined Exceptions
Programs may name their own exceptions by creating a new exception
class. Exceptions should typically be derived from the
Exception class, either directly or indirectly. For
example:
```text

>>> class MyError(Exception):
... def __init__(self, value):
... self.value = value
... def __str__(self):
... return `self.value`
...
>>> try:
... raise MyError(2*2)
... except MyError, e:
... print 'My exception occurred, value:', e.value
...
My exception occurred, value: 4
>>> raise MyError, 'oops!'
Traceback (most recent call last):
File "<stdin>", line 1, in ?
__main__.MyError: 'oops!'
```
Exception classes can be defined which do anything any other class can
do, but are usually kept simple, often only offering a number of
attributes that allow information about the error to be extracted by
handlers for the exception. When creating a module which can raise
several distinct errors, a common practice is to create a base class
for exceptions defined by that module, and subclass that to create
specific exception classes for different error conditions:
```text

class Error(Exception):
"""Base class for exceptions in this module."""
pass

class InputError(Error):
"""Exception raised for errors in the input.

Attributes:
expression -- input expression in which the error occurred
message -- explanation of the error
"""

def __init__(self, expression, message):
self.expression = expression
self.message = message

class TransitionError(Error):
"""Raised when an operation attempts a state transition that's not
allowed.

Attributes:
previous -- state at beginning of transition
next -- attempted new state
message -- explanation of why the specific transition is not allowed
"""

def __init__(self, previous, next, message):
self.previous = previous
self.next = next
self.message = message
```
Most exceptions are defined with names that end in ``Error,'' similar
to the naming of the standard exceptions.
Many standard modules define their own exceptions to report errors
that may occur in functions they define. More information on classes
is presented in chapter 9 (node11.html#classes), ``Classes.''
# 8.6 Defining Clean-up Actions
The try statement has another optional clause which is
intended to define clean-up actions that must be executed under all
circumstances. For example:
```text

>>> try:
... raise KeyboardInterrupt
... finally:
... print 'Goodbye, world!'
...
Goodbye, world!
Traceback (most recent call last):
File "<stdin>", line 2, in ?
KeyboardInterrupt
```
A finally clause is executed whether or not an exception has
occurred in the try clause. When an exception has occurred, it is
re-raised after the finally clause is executed. The finally clause is
also executed ``on the way out'' when the try statement is
left via a break or return statement.
The code in the finally clause is useful for releasing external
resources (such as files or network connections), regardless of
whether or not the use of the resource was successful.
A try statement must either have one or more except clauses
or one finally clause, but not both.


9. Classes

node10.html | tut.html | node12.html | Python Tutorial | node2.html
---
- 9.1 A Word About Terminology (#SECTION0011100000000000000000)
  9.2 Python Scopes and Name Spaces (#SECTION0011200000000000000000)
  9.3 A First Look at Classes (#SECTION0011300000000000000000)
  - 9.3.1 Class Definition Syntax (#SECTION0011310000000000000000)
  9.3.2 Class Objects (#SECTION0011320000000000000000)
  9.3.3 Instance Objects (#SECTION0011330000000000000000)
  9.3.4 Method Objects (#SECTION0011340000000000000000)
  9.4 Random Remarks (#SECTION0011400000000000000000)
  9.5 Inheritance (#SECTION0011500000000000000000)
  - 9.5.1 Multiple Inheritance (#SECTION0011510000000000000000)
  9.6 Private Variables (#SECTION0011600000000000000000)
  9.7 Odds and Ends (#SECTION0011700000000000000000)
  - 9.7.1 Exceptions Can Be Classes (#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
namespaces, and you need to know how scopes and namespaces 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 namespace is a mapping from names to objects. Most
namespaces 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 namespaces 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 namespace. The important thing to know about namespaces
is that there is absolutely no relation between names in different
namespaces; 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 namespace!
9.1 (#foot1407)
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. For example,
"del modname.the_answer" will remove the attribute
the_answer from the object named by `modname`.
Name spaces are created at different moments and have different
lifetimes. The namespace containing the built-in names is created
when the Python interpreter starts up, and is never deleted. The
global namespace for a module is created when the module definition
is read in; normally, module namespaces 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 namespace. (The
built-in names actually also live in a module; this is called
__builtin__.)
The local namespace 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 namespace.
A scope is a textual region of a Python program where a
namespace is directly accessible. ``Directly accessible'' here means
that an unqualified reference to a name attempts to find the name in
the namespace.
Although scopes are determined statically, they are used dynamically.
At any time during execution, exactly three nested scopes are in use
(exactly three namespaces 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 namespace
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 namespace as the global scope: the module's namespace.
Class definitions place yet another namespace 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
namespace, 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 namespace
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 namespace is created, and
used as the local scope -- thus, all assignments to local variables
go into this new namespace. 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 namespace 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 namespace 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(self):
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. For example, 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:
```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. Possible conventions include
capitalizing method names, prefixing data attribute names with a small
unique string (perhaps just an underscore), or using 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:
```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,
```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 in special circumstances, such as in
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 all
versions of Python, including those available before this feature was
added:
```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:
```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?
Reading this tutorial has probably reinforced your interest in using
Python -- you should be eager to apply Python to solve your
real-world problems. Now what should you do?
You should read, or at least page through, the
Python Library Reference (../lib/lib.html),
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@python.org. The newsgroup and mailing list
are gatewayed, so messages posted to one will automatically be
forwarded to the other. There are around 120 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. Mailing
list archives are available at http://www.python.org/pipermail/.
The FAQ answers many of the questions that come up again and again,
and may already contain the solution for your problem.


node12.html | tut.html | node14.html | Python Tutorial | node2.html
---
- A.1 Line Editing (#SECTION0013100000000000000000)
  A.2 History Substitution (#SECTION0013200000000000000000)
  A.3 Key Bindings (#SECTION0013300000000000000000)
  A.4 Commentary (#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
~/.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 character instead of Readline's default filename completion
function. If you insist, you can override this by putting
```text

Tab: complete
```
in your ~/.inputrc. (Of course, this makes it harder 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 startup file:A.1 (#foot1426)
```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 more capable startup file might look like this example. Note that
this deletes the names it creates once they are no longer needed; this
is done since the startup file is executed in the same namespace as
the interactive commands, and removing the names avoids creating side
effects in the interactive environments. You may find it convenient
to keep some of the imported modules, such as os, which turn
out to be needed in most sessions with the interpreter.
```text

# Add auto-completion and a stored history file of commands to your Python
# interactive interpreter. Requires Python 2.0+, readline. Autocomplete is
# bound to the Esc key by default (you can change it - see readline docs).
#
# Store the file in ~/.pystartup, and set an environment variable to point
# to it, e.g. "export PYTHONSTARTUP=/max/home/itamar/.pystartup" in bash.
#
# Note that PYTHONSTARTUP does *not* expand "~", so you have to put in the
# full path to your home directory.

import atexit
import os
import readline
import rlcompleter

historyPath = os.path.expanduser("~/.pyhistory")

def save_history(historyPath=historyPath):
import readline
readline.write_history_file(historyPath)

if os.path.exists(historyPath):
readline.read_history_file(historyPath)

atexit.register(save_history)
del os, atexit, readline, rlcompleter, save_history, historyPath
```
# A.4 Commentary
This facility is an enormous step forward compared to earlier 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.


node13.html | tut.html | node15.html | Python Tutorial | node2.html
---
- B.1 Representation Error (#SECTION0014100000000000000000)
---
# B. Floating Point Arithmetic: Issues and Limitations
Floating-point numbers are represented in computer hardware as
base 2 (binary) fractions. For example, the decimal fraction
```text

0.125
```
has value 1/10 + 2/100 + 5/1000, and in the same way the binary fraction
```text

0.001
```
has value 0/2 + 0/4 + 1/8. These two fractions have identical values,
the only real difference being that the first is written in base 10
fractional notation, and the second in base 2.
Unfortunately, most decimal fractions cannot be represented exactly as
binary fractions. A consequence is that, in general, the decimal
floating-point numbers you enter are only approximated by the binary
floating-point numbers actually stored in the machine.
The problem is easier to understand at first in base 10. Consider the
fraction 1/3. You can approximate that as a base 10 fraction:
```text

0.3
```
or, better,
```text

0.33
```
or, better,
```text

0.333
```
and so on. No matter how many digits you're willing to write down, the
result will never be exactly 1/3, but will be an increasingly better
approximation to 1/3.
In the same way, no matter how many base 2 digits you're willing to
use, the decimal value 0.1 cannot be represented exactly as a base 2
fraction. In base 2, 1/10 is the infinitely repeating fraction
```text

0.0001100110011001100110011001100110011001100110011...
```
Stop at any finite number of bits, and you get an approximation. This
is why you see things like:
```text

>>> 0.1
0.10000000000000001
```
On most machines today, that is what you'll see if you enter 0.1 at
a Python prompt. You may not, though, because the number of bits
used by the hardware to store floating-point values can vary across
machines, and Python only prints a decimal approximation to the true
decimal value of the binary approximation stored by the machine. On
most machines, if Python were to print the true decimal value of
the binary approximation stored for 0.1, it would have to display
```text

>>> 0.1
0.1000000000000000055511151231257827021181583404541015625
```
instead! The Python prompt (implicitly) uses the builtin
repr() function to obtain a string version of everything it
displays. For floats, `repr( float )` rounds the true
decimal value to 17 significant digits, giving
```text

0.10000000000000001
```
`repr( float )` produces 17 significant digits because it
turns out that's enough (on most machines) so that
`eval(repr( x )) == x` exactly for all finite floats
x, but rounding to 16 digits is not enough to make that true.
Note that this is in the very nature of binary floating-point: this is
not a bug in Python, it is not a bug in your code either, and you'll
see the same kind of thing in all languages that support your
hardware's floating-point arithmetic (although some languages may
not display the difference by default, or in all output modes).
Python's builtin str() function produces only 12
significant digits, and you may wish to use that instead. It's
unusual for `eval(str( x ))` to reproduce x, but the
output may be more pleasant to look at:
```text

>>> print str(0.1)
0.1
```
It's important to realize that this is, in a real sense, an illusion:
the value in the machine is not exactly 1/10, you're simply rounding
the display of the true machine value.
Other surprises follow from this one. For example, after seeing
```text

>>> 0.1
0.10000000000000001
```
you may be tempted to use the round() function to chop it
back to the single digit you expect. But that makes no difference:
```text

>>> round(0.1, 1)
0.10000000000000001
```
The problem is that the binary floating-point value stored for "0.1"
was already the best possible binary approximation to 1/10, so trying
to round it again can't make it better: it was already as good as it
gets.
Another consequence is that since 0.1 is not exactly 1/10, adding 0.1
to itself 10 times may not yield exactly 1.0, either:
```text

>>> sum = 0.0
>>> for i in range(10):
... sum += 0.1
...
>>> sum
0.99999999999999989
```
Binary floating-point arithmetic holds many surprises like this. The
problem with "0.1" is explained in precise detail below, in the
"Representation Error" section. See
The Perils of Floating
Point (http://www.lahey.com/float.htm) for a more complete account of other common surprises.
As that says near the end, ``there are no easy answers.'' Still,
don't be unduly wary of floating-point! The errors in Python float
operations are inherited from the floating-point hardware, and on most
machines are on the order of no more than 1 part in 2**53 per
operation. That's more than adequate for most tasks, but you do need
to keep in mind that it's not decimal arithmetic, and that every float
operation can suffer a new rounding error.
While pathological cases do exist, for most casual use of
floating-point arithmetic you'll see the result you expect in the end
if you simply round the display of your final results to the number of
decimal digits you expect. str() usually suffices, and for
finer control see the discussion of Pythons's `%` format
operator: the `%g`, `%f` and `%e` format codes
supply flexible and easy ways to round float results for display.
# B.1 Representation Error
This section explains the ``0.1'' example in detail, and shows how
you can perform an exact analysis of cases like this yourself. Basic
familiarity with binary floating-point representation is assumed.
Representation error refers to that some (most, actually)
decimal fractions cannot be represented exactly as binary (base 2)
fractions. This is the chief reason why Python (or Perl, C, C++,
Java, Fortran, and many others) often won't display the exact decimal
number you expect:
```text

>>> 0.1
0.10000000000000001
```
Why is that? 1/10 is not exactly representable as a binary fraction.
Almost all machines today (November 2000) use IEEE-754 floating point
arithmetic, and almost all platforms map Python floats to IEEE-754
"double precision". 754 doubles contain 53 bits of precision, so on
input the computer strives to convert 0.1 to the closest fraction it can
of the form J/2**N where J is an integer containing
exactly 53 bits. Rewriting
```text

1 / 10 ~= J / (2**N)
```
as
```text

J ~= 2**N / 10
```
and recalling that J has exactly 53 bits (is `>= 2**52` but
`< 2**53`), the best value for N is 56:
```text

>>> 2L**52
4503599627370496L
>>> 2L**53
9007199254740992L
>>> 2L**56/10
7205759403792793L
```
That is, 56 is the only value for N that leaves J with
exactly 53 bits. The best possible value for J is then that
quotient rounded:
```text

>>> q, r = divmod(2L**56, 10)
>>> r
6L
```
Since the remainder is more than half of 10, the best approximation is
obtained by rounding up:
```text

>>> q+1
7205759403792794L
```
Therefore the best possible approximation to 1/10 in 754 double
precision is that over 2**56, or
```text

7205759403792794 / 72057594037927936
```
Note that since we rounded up, this is actually a little bit larger than
1/10; if we had not rounded up, the quotient would have been a little
bit smaller than 1/10. But in no case can it be exactly 1/10!
So the computer never ``sees'' 1/10: what it sees is the exact
fraction given above, the best 754 double approximation it can get:
```text

>>> .1 * 2L**56
7205759403792794.0
```
If we multiply that fraction by 10**30, we can see the (truncated)
value of its 30 most significant decimal digits:
```text

>>> 7205759403792794L * 10L**30 / 2L**56
100000000000000005551115123125L
```
meaning that the exact number stored in the computer is approximately
equal to the decimal value 0.100000000000000005551115123125. Rounding
that to 17 significant digits gives the 0.10000000000000001 that Python
displays (well, will display on any 754-conforming platform that does
best-possible input and output conversions in its C library -- yours may
not!).


C. History and License

node14.html | tut.html | node16.html | Python Tutorial | node2.html
---
- C.1 History of the software (#SECTION0015100000000000000000)
  C.2 Terms and conditions for accessing or otherwise using Python (#SECTION0015200000000000000000)
---
# C. History and License
# C.1 History of the software
Python was created in the early 1990s by Guido van Rossum at Stichting
Mathematisch Centrum (CWI, see http://www.cwi.nl/) in the Netherlands
as a successor of a language called ABC. Guido remains Python's
principal author, although it includes many contributions from others.
In 1995, Guido continued his work on Python at the Corporation for
National Research Initiatives (CNRI, see http://www.cnri.reston.va.us/)
in Reston, Virginia where he released several versions of the
software.
In May 2000, Guido and the Python core development team moved to
BeOpen.com to form the BeOpen PythonLabs team. In October of the same
year, the PythonLabs team moved to Zope Corporation (then Digital
Creations; see http://www.zope.com/). In 2001, the Python
Software Foundation (PSF, see http://www.python.org/psf/) was
formed, a non-profit organization created specifically to own
Python-related Intellectual Property. Digital Creations is a
sponsoring member of the PSF.
All Python releases are Open Source (see
http://www.opensource.org/ for the Open Source Definition).
Historically, most, but not all, Python releases have also been
GPL-compatible; the table below summarizes the various releases.
Note:
GPL-compatible doesn't mean that we're distributing
Python under the GPL. All Python licenses, unlike the GPL, let you
distribute a modified version without making your changes open source.
The GPL-compatible licenses make it possible to combine Python with
other software that is released under the GPL; the others don't.
Thanks to the many outside volunteers who have worked under Guido's
direction to make these releases possible.
# C.2 Terms and conditions for accessing or otherwise using Python
PSF LICENSE AGREEMENT FOR PYTHON 2.2
1. This LICENSE AGREEMENT is between the Python Software Foundation
(``PSF''), and the Individual or Organization (``Licensee'') accessing
and otherwise using Python 2.2 software in source or binary
form and its associated documentation.
2. Subject to the terms and conditions of this License Agreement, PSF
hereby grants Licensee a nonexclusive, royalty-free, world-wide
license to reproduce, analyze, test, perform and/or display publicly,
prepare derivative works, distribute, and otherwise use Python
2.2 alone or in any derivative version, provided, however, that
PSF's License Agreement and PSF's notice of copyright, i.e.,
``Copyright © 2001 Python Software Foundation; All Rights
Reserved'' are retained in Python 2.2 alone or in any
derivative version prepared by Licensee.
3. In the event Licensee prepares a derivative work that is based on
or incorporates Python 2.2 or any part thereof, and wants to
make the derivative work available to others as provided herein, then
Licensee hereby agrees to include in any such work a brief summary of
the changes made to Python 2.2.
4. PSF is making Python 2.2 available to Licensee on an ``AS IS''
basis. PSF MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR
IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, PSF MAKES NO AND
DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS
FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF PYTHON 2.2 WILL
NOT INFRINGE ANY THIRD PARTY RIGHTS.
5. PSF SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON
2.2 FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR
LOSS AS A RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON
2.2, OR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE
POSSIBILITY THEREOF.
6. This License Agreement will automatically terminate upon a material
breach of its terms and conditions.
7. Nothing in this License Agreement shall be deemed to create any
relationship of agency, partnership, or joint venture between PSF and
Licensee. This License Agreement does not grant permission to use PSF
trademarks or trade name in a trademark sense to endorse or promote
products or services of Licensee, or any third party.
8. By copying, installing or otherwise using Python 2.2, Licensee
agrees to be bound by the terms and conditions of this License
Agreement.
BEOPEN.COM LICENSE AGREEMENT FOR PYTHON 2.0
BEOPEN PYTHON OPEN SOURCE LICENSE AGREEMENT VERSION 1
1. This LICENSE AGREEMENT is between BeOpen.com (``BeOpen''), having an
office at 160 Saratoga Avenue, Santa Clara, CA 95051, and the
Individual or Organization (``Licensee'') accessing and otherwise
using this software in source or binary form and its associated
documentation (``the Software'').
2. Subject to the terms and conditions of this BeOpen Python License
Agreement, BeOpen hereby grants Licensee a non-exclusive,
royalty-free, world-wide license to reproduce, analyze, test, perform
and/or display publicly, prepare derivative works, distribute, and
otherwise use the Software alone or in any derivative version,
provided, however, that the BeOpen Python License is retained in the
Software, alone or in any derivative version prepared by Licensee.
3. BeOpen is making the Software available to Licensee on an ``AS IS''
basis. BEOPEN MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR
IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, BEOPEN MAKES NO AND
DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS
FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF THE SOFTWARE WILL NOT
INFRINGE ANY THIRD PARTY RIGHTS.
4. BEOPEN SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF THE
SOFTWARE FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS
AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THE SOFTWARE, OR ANY
DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF.
5. This License Agreement will automatically terminate upon a material
breach of its terms and conditions.
6. This License Agreement shall be governed by and interpreted in all
respects by the law of the State of California, excluding conflict of
law provisions. Nothing in this License Agreement shall be deemed to
create any relationship of agency, partnership, or joint venture
between BeOpen and Licensee. This License Agreement does not grant
permission to use BeOpen trademarks or trade names in a trademark
sense to endorse or promote products or services of Licensee, or any
third party. As an exception, the ``BeOpen Python'' logos available
at http://www.pythonlabs.com/logos.html may be used according to the
permissions granted on that web page.
7. By copying, installing or otherwise using the software, Licensee
agrees to be bound by the terms and conditions of this License
Agreement.
CNRI LICENSE AGREEMENT FOR PYTHON 1.6.1
1. This LICENSE AGREEMENT is between the Corporation for National
Research Initiatives, having an office at 1895 Preston White Drive,
Reston, VA 20191 (``CNRI''), and the Individual or Organization
(``Licensee'') accessing and otherwise using Python 1.6.1 software in
source or binary form and its associated documentation.
2. Subject to the terms and conditions of this License Agreement, CNRI
hereby grants Licensee a nonexclusive, royalty-free, world-wide
license to reproduce, analyze, test, perform and/or display publicly,
prepare derivative works, distribute, and otherwise use Python 1.6.1
alone or in any derivative version, provided, however, that CNRI's
License Agreement and CNRI's notice of copyright, i.e., ``Copyright
© 1995-2001 Corporation for National Research Initiatives;
All Rights Reserved'' are retained in Python 1.6.1 alone or in any
derivative version prepared by Licensee. Alternately, in lieu of
CNRI's License Agreement, Licensee may substitute the following text
(omitting the quotes): ``Python 1.6.1 is made available subject to the
terms and conditions in CNRI's License Agreement. This Agreement
together with Python 1.6.1 may be located on the Internet using the
following unique, persistent identifier (known as a handle):
1895.22/1013. This Agreement may also be obtained from a proxy server
on the Internet using the following URL:
http://hdl.handle.net/1895.22/1013.''
3. In the event Licensee prepares a derivative work that is based on
or incorporates Python 1.6.1 or any part thereof, and wants to make
the derivative work available to others as provided herein, then
Licensee hereby agrees to include in any such work a brief summary of
the changes made to Python 1.6.1.
4. CNRI is making Python 1.6.1 available to Licensee on an ``AS IS''
basis. CNRI MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR
IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, CNRI MAKES NO AND
DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS
FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF PYTHON 1.6.1 WILL NOT
INFRINGE ANY THIRD PARTY RIGHTS.
5. CNRI SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON
1.6.1 FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS
A RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON 1.6.1,
OR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF.
6. This License Agreement will automatically terminate upon a material
breach of its terms and conditions.
7. This License Agreement shall be governed by the federal
intellectual property law of the United States, including without
limitation the federal copyright law, and, to the extent such
U.S. federal law does not apply, by the law of the Commonwealth of
Virginia, excluding Virginia's conflict of law provisions.
Notwithstanding the foregoing, with regard to derivative works based
on Python 1.6.1 that incorporate non-separable material that was
previously distributed under the GNU General Public License (GPL), the
law of the Commonwealth of Virginia shall govern this License
Agreement only as to issues arising under or with respect to
Paragraphs 4, 5, and 7 of this License Agreement. Nothing in this
License Agreement shall be deemed to create any relationship of
agency, partnership, or joint venture between CNRI and Licensee. This
License Agreement does not grant permission to use CNRI trademarks or
trade name in a trademark sense to endorse or promote products or
services of Licensee, or any third party.
8. By clicking on the ``ACCEPT'' button where indicated, or by copying,
installing or otherwise using Python 1.6.1, Licensee agrees to be
bound by the terms and conditions of this License Agreement.
ACCEPT
CWI LICENSE AGREEMENT FOR PYTHON 0.9.0 THROUGH 1.2
Copyright © 1991 - 1995, Stichting Mathematisch Centrum
Amsterdam, The Netherlands. All rights reserved.
Permission to use, copy, modify, and distribute this software and its
documentation for any purpose and without fee is hereby granted,
provided that the above copyright notice appear in all copies and that
both that copyright notice and this permission notice appear in
supporting documentation, and that the name of Stichting Mathematisch
Centrum or CWI not be used in advertising or publicity pertaining to
distribution of the software without specific, written prior
permission.
STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO
THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM BE LIABLE
FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.


About this document ...

node15.html | tut.html | Python Tutorial | node2.html
---
# About this document ...
Python Tutorial,
December 21, 2001, Release 2.2
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.
---
node15.html | tut.html | Python Tutorial | node2.html
---
Release 2.2, documentation updated on December 21, 2001.


Contents

node1.html | tut.html | node3.html | Python Tutorial
---
## Contents
Table of Contents
- Front Matter (node1.html)
  1. Whetting Your Appetite (node3.html)
  - 1.1 Where From Here (node3.html#SECTION003100000000000000000)
  2. Using the Python Interpreter (node4.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)
  3. An Informal Introduction to Python (node5.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)
  4. More Control Flow Tools (node6.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)
  5. Data Structures (node7.html)
  - 5.1 More on Lists (node7.html#SECTION007100000000000000000)
  - 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.1.4 List Comprehensions (node7.html#SECTION007140000000000000000)
  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. Modules (node8.html)
  - 6.1 More on Modules (node8.html#SECTION008100000000000000000)
  - 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. Input and Output (node9.html)
  - 7.1 Fancier Output Formatting (node9.html#SECTION009100000000000000000)
  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. Errors and Exceptions (node10.html)
  - 8.1 Syntax Errors (node10.html#SECTION0010100000000000000000)
  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. Classes (node11.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)
  10. What Now? (node12.html)
  A. Interactive Input Editing and History Substitution (node13.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)
  B. Floating Point Arithmetic: Issues and Limitations (node14.html)
  - B.1 Representation Error (node14.html#SECTION0014100000000000000000)
  C. History and License (node15.html)
  - C.1 History of the software (node15.html#SECTION0015100000000000000000)
  C.2 Terms and conditions for accessing or otherwise using Python (node15.html#SECTION0015200000000000000000)
  About this document ... (node16.html)
End of Table of Contents


1. Whetting Your Appetite

node2.html | tut.html | node4.html | Python Tutorial | node2.html
---
- 1.1 Where From Here (#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 graphical user interface 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 (#SECTION004100000000000000000)
  - 2.1.1 Argument Passing (#SECTION004110000000000000000)
  2.1.2 Interactive Mode (#SECTION004120000000000000000)
  2.2 The Interpreter and Its Environment (#SECTION004200000000000000000)
  - 2.2.1 Error Handling (#SECTION004210000000000000000)
  2.2.2 Executable Python Scripts (#SECTION004220000000000000000)
  2.2.3 The Interactive Startup File (#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 end-of-file 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 (node13.html#interacting) 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 end-of-file 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:
```text

python
Python 1.5.2b2 (#1, Feb 28 1999, 00:02:06) [GCC 2.8.1] on sunos5
Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam
>>>
```
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 namespace 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 using code
like "if os.path.isfile('.pythonrc.py'):
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
filename = os.environ.get('PYTHONSTARTUP')
if filename and os.path.isfile(filename):
execfile(filename)
```