2.4.1 String literals

literals.html | literals.html | string-catenation.html | Python Reference Manual | contents.html | genindex.html
Previous:
2.4 Literals (literals.html)
Up:
2.4 Literals (literals.html)
Next:
2.4.2 String literal concatenation (string-catenation.html)
---
## 2.4.1 String literals
String literals are described by the following lexical definitions:
`stringliteral` | ::= | `[ stringprefix ]( shortstring | longstring )`
`stringprefix` | ::= | `"r" | "u" | "ur" | "R" | "U" | "UR" | "Ur" | "uR"`
`shortstring` | ::= | `"'" shortstringitem * "'"
| '"' shortstringitem * '"'`
`longstring` | ::= | `"'''" longstringitem * "'''"`
`| '"""' longstringitem * '"""'`
`shortstringitem` | ::= | `shortstringchar | escapeseq`
`longstringitem` | ::= | `longstringchar | escapeseq`
`shortstringchar` | ::= | `<any ASCII character except "\" or newline or the quote>`
`longstringchar` | ::= | `<any ASCII character except "\">`
`escapeseq` | ::= | `"\" <any ASCII character>`
Download entire grammar as text. (grammar.txt)
One syntactic restriction not indicated by these productions is that
whitespace is not allowed between the stringprefix (strings.html#tok-stringprefix) and
the rest of the string literal.
In plain English: String literals can be enclosed in matching single
quotes (`'`) or double quotes (`"`). They can also be
enclosed in matching groups of three single or double quotes (these
are generally referred to as triple-quoted strings). The
backslash (`\`) character is used to escape characters that
otherwise have a special meaning, such as newline, backslash itself,
or the quote character. String literals may optionally be prefixed
with a letter "r" or "R"; such strings are called
raw stringsand use different rules for interpreting
backslash escape sequences. A prefix of "u" or "U"
makes the string a Unicode string. Unicode strings use the Unicode character
set as defined by the Unicode Consortium and ISO 10646. Some additional
escape sequences, described below, are available in Unicode strings.
The two prefix characters may be combined; in this case, "u" must
appear before "r".
In triple-quoted strings,
unescaped newlines and quotes are allowed (and are retained), except
that three unescaped quotes in a row terminate the string. (A
``quote'' is the character used to open the string, i.e. either
`'` or `"`.)
Unless an "r" or "R" prefix is present, escape
sequences in strings are interpreted according to rules similar
to those used by Standard C. The recognized escape sequences are:
Notes:
(1): Individual code units which form parts of a surrogate pair can be
encoded using this escape sequence.
(2): Any Unicode character can be encoded this way, but characters
outside the Basic Multilingual Plane (BMP) will be encoded using a
surrogate pair if Python is compiled to use 16-bit code units (the
default). Individual code units which form parts of a surrogate
pair can be encoded using this escape sequence.
(3): As in Standard C, up to three octal digits are accepted.
(4): Unlike in Standard C, at most two hex digits are accepted.
Unlike Standard ,
all unrecognized escape sequences are left in the string unchanged,
i.e., the backslash is left in the string. (This behavior is
useful when debugging: if an escape sequence is mistyped, the
resulting output is more easily recognized as broken.) It is also
important to note that the escape sequences marked as ``(Unicode
only)'' in the table above fall into the category of unrecognized
escapes for non-Unicode string literals.
When an "r" or "R" prefix is present, a character
following a backslash is included in the string without change, and all
backslashes are left in the string. For example, the string literal
`r"\n"` consists of two characters: a backslash and a lowercase
"n". String quotes can be escaped with a backslash, but the
backslash remains in the string; for example, `r"\""` is a valid string
literal consisting of two characters: a backslash and a double quote;
`r"\"` is not a valid string literal (even a raw string cannot
end in an odd number of backslashes). Specifically, a raw
string cannot end in a single backslash (since the backslash would
escape the following quote character). Note also that a single
backslash followed by a newline is interpreted as those two characters
as part of the string, not as a line continuation.
When an "r" or "R" prefix is used in conjunction
with a "u" or "U" prefix, then the `\uXXXX`
escape sequence is processed while all other backslashes are
left in the string. For example, the string literal
`ur"\u0062\n"` consists of three Unicode characters: `LATIN
SMALL LETTER B', `REVERSE SOLIDUS', and `LATIN SMALL LETTER N'.
Backslashes can be escaped with a preceding backslash; however, both
remain in the string. As a result, `\uXXXX` escape sequences
are only recognized when there are an odd number of backslashes.


5.3.2 Subscriptions

attribute-references.html | primaries.html | slicings.html | Python Reference Manual | contents.html | genindex.html
Previous:
5.3.1 Attribute references (attribute-references.html)
Up:
5.3 Primaries (primaries.html)
Next:
5.3.3 Slicings (slicings.html)
---
## 5.3.2 Subscriptions
A subscription selects an item of a sequence (string, tuple or list)
or mapping (dictionary) object:
`subscription` | ::= | `primary "[" expression_list "]"`
Download entire grammar as text. (grammar.txt)
The primary must evaluate to an object of a sequence or mapping type.
If the primary is a mapping, the expression list must evaluate to an
object whose value is one of the keys of the mapping, and the
subscription selects the value in the mapping that corresponds to that
key. (The expression list is a tuple except if it has exactly one
item.)
If the primary is a sequence, the expression (list) must evaluate to a
plain integer. If this value is negative, the length of the sequence
is added to it (so that, e.g., `x[-1]` selects the last item of
`x`.) The resulting value must be a nonnegative integer less
than the number of items in the sequence, and the subscription selects
the item whose index is that value (counting from zero).
A string's items are characters. A character is not a separate data
type but a string of exactly one character.


5.14 Summary

evalorder.html | expressions.html | simple.html | Python Reference Manual | contents.html | genindex.html
Previous:
5.13 Evaluation order (evalorder.html)
Up:
5. Expressions (expressions.html)
Next:
6. Simple statements (simple.html)
---
# 5.14 Summary
The following table summarizes the operator
precedences in Python, from lowest
precedence (least binding) to highest precedence (most binding).
Operators in the same box have the same precedence. Unless the syntax
is explicitly given, operators are binary. Operators in the same box
group left to right (except for comparisons, which chain from left to
right -- see above, and exponentiation, which groups from right to
left).


8. Top-level components

class.html | ref.html | programs.html | Python Reference Manual | contents.html | genindex.html
Previous:
7.6 Class definitions (class.html)
Up:
Python Reference Manual (ref.html)
Next:
8.1 Complete Python programs (programs.html)
---
# 8. Top-level components
The Python interpreter can get its input from a number of sources:
from a script passed to it as standard input or as program argument,
typed in interactively, from a module source file, etc. This chapter
gives the syntax used in these cases.


7.4 The try statement

for.html | compound.html | function.html | Python Reference Manual | contents.html | genindex.html
Previous:
7.3 The for statement (for.html)
Up:
7. Compound statements (compound.html)
Next:
7.5 Function definitions (function.html)
---
# 7.4 The try statement
The try statement specifies exception handlers and/or cleanup
code for a group of statements:
`try_stmt` | ::= | `try_exc_stmt | try_fin_stmt`
`try_exc_stmt` | ::= | `"try" ":" suite`
`("except" [ expression ["," target ]] ":" suite )+`
`["else" ":" suite ]`
`try_fin_stmt` | ::= | `"try" ":" suite "finally" ":" suite`
Download entire grammar as text. (grammar.txt)
There are two forms of try statement:
try...except and
try...finally. These forms cannot be mixed (but
they can be nested in each other).
The try...except form specifies one or more
exception handlers
(the except clauses). When no exception occurs in the
try clause, no exception handler is executed. When an
exception occurs in the try suite, a search for an exception
handler is started. This search inspects the except clauses in turn until
one is found that matches the exception. An expression-less except
clause, if present, must be last; it matches any exception. For an
except clause with an expression, that expression is evaluated, and the
clause matches the exception if the resulting object is ``compatible''
with the exception. An object is compatible with an exception if it
is either the object that identifies the exception, or (for exceptions
that are classes) it is a base class of the exception, or it is a
tuple containing an item that is compatible with the exception. Note
that the object identities must match, i.e. it must be the same
object, not just an object with the same value.
If no except clause matches the exception, the search for an exception
handler continues in the surrounding code and on the invocation stack.
If the evaluation of an expression in the header of an except clause
raises an exception, the original search for a handler is canceled
and a search starts for the new exception in the surrounding code and
on the call stack (it is treated as if the entire try statement
raised the exception).
When a matching except clause is found, the exception's parameter is
assigned to the target specified in that except clause, if present,
and the except clause's suite is executed. All except clauses must
have an executable block. When the end of this block
is reached, execution continues normally after the entire try
statement. (This means that if two nested handlers exist for the same
exception, and the exception occurs in the try clause of the inner
handler, the outer handler will not handle the exception.)
Before an except clause's suite is executed, details about the
exception are assigned to three variables in the
sysmodule: `sys.exc_type` receives
the object identifying the exception; `sys.exc_value` receives
the exception's parameter; `sys.exc_traceback` receives a
traceback object (see section 3.2 (types.html#traceback))
identifying the point in the program where the exception occurred.
These details are also available through the sys.exc_info()
function, which returns a tuple `( exc_type , exc_value , exc_traceback )`. Use of the corresponding variables is
deprecated in favor of this function, since their use is unsafe in a
threaded program. As of Python 1.5, the variables are restored to
their previous values (before the call) when returning from a function
that handled an exception.
The optional else clause is executed if and when control
flows off the end of the try clause.7.1 (#foot6465) Exceptions in the else clause are not handled by the
preceding except clauses.
The try...finally form specifies a `cleanup' handler. The
try clause is executed. When no exception occurs, the
finally clause is executed. When an exception occurs in the
try clause, the exception is temporarily saved, the
finally clause is executed, and then the saved exception is
re-raised. If the finally clause raises another exception or
executes a return or break statement, the saved
exception is lost. A continue statement is illegal in the
finally clause. (The reason is a problem with the current
implementation - this restriction may be lifted in the future). The
exception information is not available to the program during execution of
the finally clause.
When a return, break or continue statement is
executed in the try suite of a try...finally
statement, the finally clause is also executed `on the way out.' A
continue statement is illegal in the finally clause.
(The reason is a problem with the current implementation -- this
restriction may be lifted in the future).
Additional information on exceptions can be found in
section 4.2 (exceptions.html#exceptions), and information on using the raise
statement to generate exceptions may be found in section 6.9 (raise.html#raise).


3.2 The standard type hierarchy

objects.html | datamodel.html | specialnames.html | Python Reference Manual | contents.html | genindex.html
Previous:
3.1 Objects, values and (objects.html)
Up:
3. Data model (datamodel.html)
Next:
3.3 Special method names (specialnames.html)
---
# 3.2 The standard type hierarchy
Below is a list of the types that are built into Python. Extension
modules (written in C, Java, or other languages, depending on
the implementation) can define additional types. Future versions of
Python may add types to the type hierarchy (e.g., rational
numbers, efficiently stored arrays of integers, etc.).
Some of the type descriptions below contain a paragraph listing
`special attributes.' These are attributes that provide access to the
implementation and are not intended for general use. Their definition
may change in the future.
None: This type has a single value. There is a single object with this value.
This object is accessed through the built-in name `None`.
It is used to signify the absence of a value in many situations, e.g.,
it is returned from functions that don't explicitly return anything.
Its truth value is false.
NotImplemented: This type has a single value. There is a single object with this value.
This object is accessed through the built-in name `NotImplemented`.
Numeric methods and rich comparison methods may return this value if
they do not implement the operation for the operands provided. (The
interpreter will then try the reflected operation, or some other
fallback, depending on the operator.) Its truth value is true.
Ellipsis: This type has a single value. There is a single object with this value.
This object is accessed through the built-in name `Ellipsis`.
It is used to indicate the presence of the "..." syntax in a
slice. Its truth value is true.
Numbers: These are created by numeric literals and returned as results by
arithmetic operators and arithmetic built-in functions. Numeric
objects are immutable; once created their value never changes. Python
numbers are of course strongly related to mathematical numbers, but
subject to the limitations of numerical representation in computers.
Python distinguishes between integers, floating point numbers, and
complex numbers:
Integers: These represent elements from the mathematical set of whole numbers.
There are three types of integers:
Plain integers: These represent numbers in the range -2147483648 through 2147483647.
(The range may be larger on machines with a larger natural word
size, but not smaller.)
When the result of an operation would fall outside this range, the
result is normally returned as a long integer (in some cases, the
exception OverflowError is raised instead).
For the purpose of shift and mask operations, integers are assumed to
have a binary, 2's complement notation using 32 or more bits, and
hiding no bits from the user (i.e., all 4294967296 different bit
patterns correspond to different values).
Long integers: These represent numbers in an unlimited range, subject to available
(virtual) memory only. For the purpose of shift and mask operations,
a binary representation is assumed, and negative numbers are
represented in a variant of 2's complement which gives the illusion of
an infinite string of sign bits extending to the left.
Booleans: These represent the truth values False and True. The two objects
representing the values False and True are the only Boolean objects.
The Boolean type is a subtype of plain integers, and Boolean values
behave like the values 0 and 1, respectively, in almost all contexts,
the exception being that when converted to a string, the strings
`"False"` or `"True"` are returned, respectively.
The rules for integer representation are intended to give the most
meaningful interpretation of shift and mask operations involving
negative integers and the least surprises when switching between the
plain and long integer domains. Any operation except left shift,
if it yields a result in the plain integer domain without causing
overflow, will yield the same result in the long integer domain or
when using mixed operands.
Floating point numbers: These represent machine-level double precision floating point numbers.
You are at the mercy of the underlying machine architecture (and
C or Java implementation) for the accepted range and handling of overflow.
Python does not support single-precision floating point numbers; the
savings in processor and memory usage that are usually the reason for using
these is dwarfed by the overhead of using objects in Python, so there
is no reason to complicate the language with two kinds of floating
point numbers.
Complex numbers: These represent complex numbers as a pair of machine-level double
precision floating point numbers. The same caveats apply as for
floating point numbers. The real and imaginary parts of a complex
number `z` can be retrieved through the read-only attributes
`z.real` and `z.imag`.
Sequences: These represent finite ordered sets indexed by non-negative numbers.
The built-in function len() returns the
number of items of a sequence.
When the length of a sequence is n, the
index set contains the numbers 0, 1, ..., n-1. Item
i of sequence a is selected by `a [ i ]`.
Sequences also support slicing: `a [ i : j ]`
selects all items with index k such that i `<=`
k `<` j. When used as an expression, a slice is a
sequence of the same type. This implies that the index set is
renumbered so that it starts at 0.
Some sequences also support ``extended slicing'' with a third ``step''
parameter: `a [ i : j : k ]` selects all items
of a with index x where `x = i + n * k`, n `>=` `0` and i `<=`
x `<` j.
Sequences are distinguished according to their mutability:
Immutable sequences: An object of an immutable sequence type cannot change once it is
created. (If the object contains references to other objects,
these other objects may be mutable and may be changed; however,
the collection of objects directly referenced by an immutable object
cannot change.)
The following types are immutable sequences:
Strings: The items of a string are characters. There is no separate
character type; a character is represented by a string of one item.
Characters represent (at least) 8-bit bytes. The built-in
functions chr() and
ord() convert between characters and
nonnegative integers representing the byte values. Bytes with the
values 0-127 usually represent the corresponding ASCII values, but
the interpretation of values is up to the program. The string
data type is also used to represent arrays of bytes, e.g., to hold data
read from a file.
(On systems whose native character set is not ASCII, strings may use
EBCDIC in their internal representation, provided the functions
chr() and ord() implement a mapping between ASCII and
EBCDIC, and string comparison preserves the ASCII order.
Or perhaps someone can propose a better rule?)
Unicode: The items of a Unicode object are Unicode code units. A Unicode code
unit is represented by a Unicode object of one item and can hold
either a 16-bit or 32-bit value representing a Unicode ordinal (the
maximum value for the ordinal is given in `sys.maxunicode`, and
depends on how Python is configured at compile time). Surrogate pairs
may be present in the Unicode object, and will be reported as two
separate items. The built-in functions
unichr() and
ord() convert between code units and
nonnegative integers representing the Unicode ordinals as defined in
the Unicode Standard 3.0. Conversion from and to other encodings are
possible through the Unicode method encode and the built-in
function unicode().
Tuples: The items of a tuple are arbitrary Python objects.
Tuples of two or more items are formed by comma-separated lists
of expressions. A tuple of one item (a `singleton') can be formed
by affixing a comma to an expression (an expression by itself does
not create a tuple, since parentheses must be usable for grouping of
expressions). An empty tuple can be formed by an empty pair of
parentheses.
Mutable sequences: Mutable sequences can be changed after they are created. The
subscription and slicing notations can be used as the target of
assignment and del (delete) statements.
There is currently a single intrinsic mutable sequence type:
Lists: The items of a list are arbitrary Python objects. Lists are formed
by placing a comma-separated list of expressions in square brackets.
(Note that there are no special cases needed to form lists of length 0
or 1.)
The extension module arrayprovides an
additional example of a mutable sequence type.
Mappings: These represent finite sets of objects indexed by arbitrary index sets.
The subscript notation `a[k]` selects the item indexed
by `k` from the mapping `a`; this can be used in
expressions and as the target of assignments or del statements.
The built-in function len() returns the number of items
in a mapping.
There is currently a single intrinsic mapping type:
Dictionaries: These represent finite sets of objects indexed by
nearly arbitrary values. The only types of values not acceptable as
keys are values containing lists or dictionaries or other mutable
types that are compared by value rather than by object identity, the
reason being that the efficient implementation of dictionaries
requires a key's hash value to remain constant.
Numeric types used for keys obey the normal rules for numeric
comparison: if two numbers compare equal (e.g., `1` and
`1.0`) then they can be used interchangeably to index the same
dictionary entry.
Dictionaries are mutable; they can be created by the
`{...}` notation (see section 5.2.5 (dict.html#dict), ``Dictionary
Displays'').
The extension modules dbm
gdbm bsddbprovide additional examples of mapping types.
Callable types: These are the types to which the function call
operation (see section 5.3.4 (calls.html#calls), ``Calls'') can be applied:
User-defined functions: A user-defined function object is created by a function definition
(see section 7.5 (function.html#function), ``Function definitions''). It should be
called with an argument
list containing the same number of items as the function's formal
parameter list.
Special attributes: func_doc or __doc__ is the
function's documentation string, or `None` if unavailable;
func_name or __name__ is the function's name;
__module__ is the name of the module the function was defined
in, or `None` if unavailable;
func_defaults is a tuple containing default argument values for
those arguments that have defaults, or `None` if no arguments
have a default value; func_code is the code object representing
the compiled function body; func_globals is (a reference to)
the dictionary that holds the function's global variables -- it
defines the global namespace of the module in which the function was
defined; func_dict or __dict__ contains the
namespace supporting arbitrary function attributes;
func_closure is `None` or a tuple of cells that contain
bindings for the function's free variables.
Of these, func_code, func_defaults,
func_doc/__doc__, and
func_dict/__dict__ may be writable; the
others can never be changed. Additional information about a
function's definition can be retrieved from its code object; see the
description of internal types below.
User-defined methods: A user-defined method object combines a class, a class instance (or
`None`) and any callable object (normally a user-defined
function).
Special read-only attributes: im_self is the class instance
object, im_func is the function object;
im_class is the class of im_self for bound methods
or the class that asked for the method for unbound methods;
__doc__ is the method's documentation (same as
`im_func.__doc__`); __name__ is the method name (same as
`im_func.__name__`); __module__ is the name of the
module the method was defined in, or `None` if unavailable.
Changed in version 2.2:
im_self used to refer to the class that
defined the method.
Methods also support accessing (but not setting) the arbitrary
function attributes on the underlying function object.
User-defined method objects may be created when getting an attribute
of a class (perhaps via an instance of that class), if that attribute
is a user-defined function object, an unbound user-defined method object,
or a class method object.
When the attribute is a user-defined method object, a new
method object is only created if the class from which it is being
retrieved is the same as, or a derived class of, the class stored
in the original method object; otherwise, the original method object
is used as it is.
When a user-defined method object is created by retrieving
a user-defined function object from a class, its im_self
attribute is `None` and the method object is said to be unbound.
When one is created by retrieving a user-defined function object
from a class via one of its instances, its im_self attribute
is the instance, and the method object is said to be bound.
In either case, the new method's im_class attribute
is the class from which the retrieval takes place, and
its im_func attribute is the original function object.
When a user-defined method object is created by retrieving another
method object from a class or instance, the behaviour is the same
as for a function object, except that the im_func attribute
of the new instance is not the original method object but its
im_func attribute.
When a user-defined method object is created by retrieving a
class method object from a class or instance, its im_self
attribute is the class itself (the same as the im_class
attribute), and its im_func attribute is the function
object underlying the class method.
When an unbound user-defined method object is called, the underlying
function (im_func) is called, with the restriction that the
first argument must be an instance of the proper class
(im_class) or of a derived class thereof.
When a bound user-defined method object is called, the underlying
function (im_func) is called, inserting the class instance
(im_self) in front of the argument list. For instance, when
C is a class which contains a definition for a function
f(), and `x` is an instance of C, calling
`x.f(1)` is equivalent to calling `C.f(x, 1)`.
When a user-defined method object is derived from a class method object,
the ``class instance'' stored in im_self will actually be the
class itself, so that calling either `x.f(1)` or `C.f(1)` is
equivalent to calling `f(C,1)` where `f` is the underlying
function.
Note that the transformation from function object to (unbound or
bound) method object happens each time the attribute is retrieved from
the class or instance. In some cases, a fruitful optimization is to
assign the attribute to a local variable and call that local variable.
Also notice that this transformation only happens for user-defined
functions; other callable objects (and all non-callable objects) are
retrieved without transformation. It is also important to note that
user-defined functions which are attributes of a class instance are
not converted to bound methods; this only happens when the
function is an attribute of the class.
Generator functions: A function or method which uses the yield statement (see
section 6.8 (yield.html#yield), ``The yield statement'') is called a
generator function. Such a function, when called, always
returns an iterator object which can be used to execute the body of
the function: calling the iterator's next() method will
cause the function to execute until it provides a value using the
yield statement. When the function executes a
return statement or falls off the end, a
StopIteration exception is raised and the iterator will
have reached the end of the set of values to be returned.
Built-in functions: A built-in function object is a wrapper around a C function. Examples
of built-in functions are len() and math.sin()
(math is a standard built-in module).
The number and type of the arguments are
determined by the C function.
Special read-only attributes: __doc__ is the function's
documentation string, or `None` if unavailable; __name__
is the function's name; __self__ is set to `None` (but see
the next item); __module__ is the name of the module the
function was defined in or `None` if unavailable.
Built-in methods: This is really a different disguise of a built-in function, this time
containing an object passed to the C function as an implicit extra
argument. An example of a built-in method is
`alist .append()`, assuming
alist is a list object.
In this case, the special read-only attribute __self__ is set
to the object denoted by list.
Class Types: Class types, or ``new-style classes,'' are callable. These objects
normally act as factories for new instances of themselves, but
variations are possible for class types that override
__new__(). The arguments of the call are passed to
__new__() and, in the typical case, to __init__() to
initialize the new instance.
Classic Classes: Class objects are described below. When a class object is called,
a new class instance (also described below) is created and
returned. This implies a call to the class's __init__() method
if it has one. Any arguments are passed on to the __init__()
method. If there is no __init__() method, the class must be called
without arguments.
Class instances: Class instances are described below. Class instances are callable
only when the class has a __call__() method; `x(arguments)`
is a shorthand for `x.__call__(arguments)`.
Modules: Modules are imported by the import statement (see
section 6.12 (import.html#import), ``The import statement'').A module object has a namespace implemented by a dictionary object
(this is the dictionary referenced by the func_globals attribute of
functions defined in the module). Attribute references are translated
to lookups in this dictionary, e.g., `m.x` is equivalent to
`m.__dict__["x"]`.
A module object does not contain the code object used to
initialize the module (since it isn't needed once the initialization
is done).
Attribute assignment updates the module's namespace dictionary,
e.g., "m.x = 1" is equivalent to "m.__dict__["x"] = 1".
Special read-only attribute: __dict__ is the module's
namespace as a dictionary object.
Predefined (writable) attributes: __name__
is the module's name; __doc__ is the
module's documentation string, or
`None` if unavailable; __file__ is the pathname of the
file from which the module was loaded, if it was loaded from a file.
The __file__ attribute is not present for C modules that are
statically linked into the interpreter; for extension modules loaded
dynamically from a shared library, it is the pathname of the shared
library file.
Classes: Class objects are created by class definitions (see
section 7.6 (class.html#class), ``Class definitions'').
A class has a namespace implemented by a dictionary object.
Class attribute references are translated to
lookups in this dictionary,
e.g., "C.x" is translated to "C.__dict__["x"]".
When the attribute name is not found
there, the attribute search continues in the base classes. The search
is depth-first, left-to-right in the order of occurrence in the
base class list.
When a class attribute reference (for class C, say)
would yield a user-defined function object or
an unbound user-defined method object whose associated class is either
C or one of its base classes, it is transformed into an unbound
user-defined method object whose im_class attribute is C.
When it would yield a class method object, it is transformed into
a bound user-defined method object whose im_class and
im_self attributes are both C. When it would yield
a static method object, it is transformed into the object wrapped
by the static method object. See section 3.3.2 (descriptors.html#descriptors) for another
way in which attributes retrieved from a class may differ from those
actually contained in its __dict__.
Class attribute assignments update the class's dictionary, never the
dictionary of a base class.
A class object can be called (see above) to yield a class instance (see
below).
Special attributes: __name__ is the class name;
__module__ is the module name in which the class was defined;
__dict__ is the dictionary containing the class's namespace;
__bases__ is a tuple (possibly empty or a singleton)
containing the base classes, in the order of their occurrence in the
base class list; __doc__ is the class's documentation string,
or None if undefined.
Class instances: A class instance is created by calling a class object (see above).
A class instance has a namespace implemented as a dictionary which
is the first place in which
attribute references are searched. When an attribute is not found
there, and the instance's class has an attribute by that name,
the search continues with the class attributes. If a class attribute
is found that is a user-defined function object or an unbound
user-defined method object whose associated class is the class
(call it C) of the instance for which the attribute reference
was initiated or one of its bases,
it is transformed into a bound user-defined method object whose
im_class attribute is C whose im_self attribute
is the instance. Static method and class method objects are also
transformed, as if they had been retrieved from class C;
see above under ``Classes''. See section 3.3.2 (descriptors.html#descriptors) for
another way in which attributes of a class retrieved via its
instances may differ from the objects actually stored in the
class's __dict__.
If no class attribute is found, and the object's class has a
__getattr__() method, that is called to satisfy the lookup.
Attribute assignments and deletions update the instance's dictionary,
never a class's dictionary. If the class has a __setattr__() or
__delattr__() method, this is called instead of updating the
instance dictionary directly.
Class instances can pretend to be numbers, sequences, or mappings if
they have methods with certain special names. See
section 3.3 (specialnames.html#specialnames), ``Special method names.''
Special attributes: __dict__ is the attribute
dictionary; __class__ is the instance's class.
Files: A file object represents an open file. File objects are
created by the open() built-in function,
and also by
os.popen(),
os.fdopen(), and the
makefile()method of socket objects (and perhaps by other functions or methods
provided by extension modules). The objects
`sys.stdin`,
`sys.stdout` and
`sys.stderr` are initialized to file objects
corresponding to the interpreter's standardinput, output
and error streams. See the Python Library
Reference (../lib/lib.html) for complete documentation of file objects.
Internal types: A few types used internally by the interpreter are exposed to the user.
Their definitions may change with future versions of the interpreter,
but they are mentioned here for completeness.
Code objects: Code objects represent byte-compiled executable Python code, or
bytecode.
The difference between a code
object and a function object is that the function object contains an
explicit reference to the function's globals (the module in which it
was defined), while a code object contains no context;
also the default argument values are stored in the function object,
not in the code object (because they represent values calculated at
run-time). Unlike function objects, code objects are immutable and
contain no references (directly or indirectly) to mutable objects.
Special read-only attributes: co_name gives the function
name; co_argcount is the number of positional arguments
(including arguments with default values); co_nlocals is the
number of local variables used by the function (including arguments);
co_varnames is a tuple containing the names of the local
variables (starting with the argument names); co_cellvars is
a tuple containing the names of local variables that are referenced by
nested functions; co_freevars is a tuple containing the names
of free variables; co_code is a string representing the
sequence of bytecode instructions;
co_consts is a tuple containing the literals used by the
bytecode; co_names is a tuple containing the names used by
the bytecode; co_filename is the filename from which the code
was compiled; co_firstlineno is the first line number of the
function; co_lnotab is a string encoding the mapping from
byte code offsets to line numbers (for details see the source code of
the interpreter); co_stacksize is the required stack size
(including local variables); co_flags is an integer encoding
a number of flags for the interpreter.
The following flag bits are defined for co_flags: bit
`0x04` is set if the function uses the "*arguments" syntax
to accept an arbitrary number of positional arguments; bit
`0x08` is set if the function uses the "**keywords" syntax
to accept arbitrary keyword arguments; bit `0x20` is set if the
function is a generator.
Future feature declarations ("from __future__ import division")
also use bits in co_flags to indicate whether a code object
was compiled with a particular feature enabled: bit `0x2000` is
set if the function was compiled with future division enabled; bits
`0x10` and `0x1000` were used in earlier versions of Python.
Other bits in co_flags are reserved for internal use.
Ifa code object represents a function,
the first item in
co_consts is the documentation string of the function, or
`None` if undefined.
Frame objects: Frame objects represent execution frames. They may occur in traceback
objects (see below).
Special read-only attributes: f_back is to the previous
stack frame (towards the caller), or `None` if this is the bottom
stack frame; f_code is the code object being executed in this
frame; f_locals is the dictionary used to look up local
variables; f_globals is used for global variables;
f_builtins is used for built-in (intrinsic) names;
f_restricted is a flag indicating whether the function is
executing in restricted execution mode; f_lasti gives the
precise instruction (this is an index into the bytecode string of
the code object).
Special writable attributes: f_trace, if not `None`, is a
function called at the start of each source code line (this is used by
the debugger); f_exc_type, f_exc_value,
f_exc_traceback represent the most recent exception caught in
this frame; f_lineno is the current line number of the frame
-- writing to this from within a trace function jumps to the given line
(only for the bottom-most frame). A debugger can implement a Jump
command (aka Set Next Statement) by writing to f_lineno.
Traceback objects: Traceback objects represent a stack trace of an exception. A
traceback object is created when an exception occurs. When the search
for an exception handler unwinds the execution stack, at each unwound
level a traceback object is inserted in front of the current
traceback. When an exception handler is entered, the stack trace is
made available to the program.
(See section 7.4 (try.html#try), ``The `try` statement.'')
It is accessible as `sys.exc_traceback`, and also as the third
item of the tuple returned by `sys.exc_info()`. The latter is
the preferred interface, since it works correctly when the program is
using multiple threads.
When the program contains no suitable handler, the stack trace is written
(nicely formatted) to the standard error stream; if the interpreter is
interactive, it is also made available to the user as
`sys.last_traceback`.
Special read-only attributes: tb_next is the next level in the
stack trace (towards the frame where the exception occurred), or
`None` if there is no next level; tb_frame points to the
execution frame of the current level; tb_lineno gives the line
number where the exception occurred; tb_lasti indicates the
precise instruction. The line number and last instruction in the
traceback may differ from the line number of its frame object if the
exception occurred in a try statement with no matching
except clause or with a finally clause.
Slice objects: Slice objects are used to represent slices when extended slice
syntax is used. This is a slice using two colons, or multiple slices
or ellipses separated by commas, e.g., `a[i:j:step]`, `a[i:j,
k:l]`, or `a[..., i:j]`. They are also created by the built-in
slice() function.
Special read-only attributes: start is the lower bound;
stop is the upper bound; step is the step value; each is
`None` if omitted. These attributes can have any type.
Slice objects support one method:
Static method objects: Static method objects provide a way of defeating the transformation
of function objects to method objects described above. A static method
object is a wrapper around any other object, usually a user-defined
method object. When a static method object is retrieved from a class
or a class instance, the object actually returned is the wrapped object,
which is not subject to any further transformation. Static method
objects are not themselves callable, although the objects they
wrap usually are. Static method objects are created by the built-in
staticmethod() constructor.
Class method objects: A class method object, like a static method object, is a wrapper
around another object that alters the way in which that object
is retrieved from classes and class instances. The behaviour of
class method objects upon such retrieval is described above,
under ``User-defined methods''. Class method objects are created
by the built-in classmethod() constructor.


5.5 Unary arithmetic operations

power.html | expressions.html | binary.html | Python Reference Manual | contents.html | genindex.html
Previous:
5.4 The power operator (power.html)
Up:
5. Expressions (expressions.html)
Next:
5.6 Binary arithmetic operations (binary.html)
---
# 5.5 Unary arithmetic operations
All unary arithmetic (and bit-wise) operations have the same priority:
`u_expr` | ::= | `power | "-" u_expr | "+" u_expr | "~" u_expr`
Download entire grammar as text. (grammar.txt)
The unary `-` (minus) operator yields the negation of its
numeric argument.
The unary `+` (plus) operator yields its numeric argument
unchanged.
The unary `~` (invert) operator yields the bit-wise inversion
of its plain or long integer argument. The bit-wise inversion of
`x` is defined as `-(x+1)`. It only applies to integral
numbers.
In all three cases, if the argument does not have the proper type,
a TypeError exception is raised.


7.2 The while statement

if.html | compound.html | for.html | Python Reference Manual | contents.html | genindex.html
Previous:
7.1 The if statement (if.html)
Up:
7. Compound statements (compound.html)
Next:
7.3 The for statement (for.html)
---
# 7.2 The while statement
The while statement is used for repeated execution as long
as an expression is true:
`while_stmt` | ::= | `"while" expression ":" suite`
`["else" ":" suite ]`
Download entire grammar as text. (grammar.txt)
This repeatedly tests the expression and, if it is true, executes the
first suite; if the expression is false (which may be the first time it
is tested) the suite of the else clause, if present, is
executed and the loop terminates.
A break statement executed in the first suite terminates the
loop without executing the else clause's suite. A
continue statement executed in the first suite skips the rest
of the suite and goes back to testing the expression.


2.1.9 Whitespace between tokens

indentation.html | line-structure.html | other-tokens.html | Python Reference Manual | contents.html | genindex.html
Previous:
2.1.8 Indentation (indentation.html)
Up:
2.1 Line structure (line-structure.html)
Next:
2.2 Other tokens (other-tokens.html)
---
## 2.1.9 Whitespace between tokens
Except at the beginning of a logical line or in string literals, the
whitespace characters space, tab and formfeed can be used
interchangeably to separate tokens. Whitespace is needed between two
tokens only if their concatenation could otherwise be interpreted as a
different token (e.g., ab is one token, but a b is two tokens).


6.8 The yield statement

return.html | simple.html | raise.html | Python Reference Manual | contents.html | genindex.html
Previous:
6.7 The return statement (return.html)
Up:
6. Simple statements (simple.html)
Next:
6.9 The raise statement (raise.html)
---
# 6.8 The yield statement
`yield_stmt` | ::= | `"yield" expression_list`
Download entire grammar as text. (grammar.txt)
The yield statement is only used when defining a generator
function, and is only used in the body of the generator function.
Using a yield statement in a function definition is
sufficient to cause that definition to create a generator function
instead of a normal function.
When a generator function is called, it returns an iterator known as a
generator iterator, or more commonly, a generator. The body of the
generator function is executed by calling the generator's
next() method repeatedly until it raises an exception.
When a yield statement is executed, the state of the
generator is frozen and the value of expression_list (exprlists.html#tok-expression_list) is
returned to next()'s caller. By ``frozen'' we mean that all
local state is retained, including the current bindings of local
variables, the instruction pointer, and the internal evaluation stack:
enough information is saved so that the next time next() is
invoked, the function can proceed exactly as if the yield
statement were just another external call.
The yield statement is not allowed in the try
clause of a try ... finally construct. The
difficulty is that there's no guarantee the generator will ever be
resumed, hence no guarantee that the finally block will ever
get executed.
Note:
In Python 2.2, the yield statement is only allowed
when the `generators` feature has been enabled. It will always
be enabled in Python 2.3. This `__future__` import statment can
be used to enable the feature:
```text

from __future__ import generators
```
See Also:


About this document ...

node15.html | tut.html | Python Tutorial | node2.html
Previous:
C. History and License (node15.html)
Up:
Python Tutorial (tut.html)
---
# About this document ...
Python Tutorial,
July 29, 2003, Release 2.3
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, either in the content or the presentation, 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.


Python Tutorial

../index.html | node1.html | Python Tutorial | node2.html
Up:
Python Documentation Index (../index.html)
Next:
Front Matter (node1.html)
---
# Python Tutorial
Guido van Rossum
Fred L. Drake, Jr., editor
PythonLabs
Email: python-docs@python.org
Release 2.3
July 29, 2003


Front Matter

tut.html | tut.html | node2.html | Python Tutorial | node2.html
Previous:
Python Tutorial (tut.html)
Up:
Python Tutorial (tut.html)
Next:
Contents (node2.html)
---
# Front Matter
Copyright © 2001, 2002, 2003 Python Software Foundation.
All rights reserved.
Copyright © 2000 BeOpen.com.
All rights reserved.
Copyright © 1995-2000 Corporation for National Research Initiatives.
All rights reserved.
Copyright © 1991-1995 Stichting Mathematisch Centrum.
All rights reserved.
See the end of this document for complete license and permissions
information.
### Abstract:
Python is an easy to learn, powerful programming language. It has
efficient high-level data structures and a simple but effective
approach to object-oriented programming. Python's elegant syntax and
dynamic typing, together with its interpreted nature, make it an ideal
language for scripting and rapid application development in many areas
on most platforms.
The Python interpreter and the extensive standard library are freely
available in source or binary form for all major platforms from the
Python Web site, http://www.python.org/, and can be freely
distributed. The same site also contains distributions of and
pointers to many free third party Python modules, programs and tools,
and additional documentation.
The Python interpreter is easily extended with new functions and data
types implemented in C or C++ (or other languages callable from C).
Python is also suitable as an extension language for customizable
applications.
This tutorial introduces the reader informally to the basic concepts
and features of the Python language and system. It helps to have a
Python interpreter handy for hands-on experience, but all examples are
self-contained, so the tutorial can be read off-line as well.
For a description of standard objects and modules, see the
Python Library Reference (../lib/lib.html) document. The
Python Reference Manual (../ref/ref.html) gives a more
formal definition of the language. To write extensions in C or
C++, read Extending and Embedding the
Python Interpreter (../ext/ext.html) and Python/C API
Reference (../api/api.html). There are also several books covering Python in depth.
This tutorial does not attempt to be comprehensive and cover every
single feature, or even every commonly used feature. Instead, it
introduces many of Python's most noteworthy features, and will give
you a good idea of the language's flavor and style. After reading it,
you will be able to read and write Python modules and programs, and
you will be ready to learn more about the various Python library
modules described in the Python Library
Reference (../lib/lib.html).


8. Errors and Exceptions

node9.html | tut.html | node11.html | Python Tutorial | node2.html
Previous:
7. Input and Output (node9.html)
Up:
Python Tutorial (tut.html)
Next:
9. Classes (node11.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)
---
# 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 True print 'Hello world'
File "<stdin>", line 1, in ?
while True 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 by zero
>>> 4 + spam*3
Traceback (most recent call last):
File "<stdin>", line 1, in ?
NameError: name 'spam' is not defined
>>> '2' + 2
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: cannot concatenate 'str' and 'int' objects
```
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 True:
... 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.
The except clause may specify a variable after the exception name (or list).
The variable is bound to an exception instance with the arguments stored
in `instance.args`. For convenience, the exception instance
defines __getitem__ and __str__ so the arguments can
be accessed or printed directly without having to reference `.args`.
```text

>>> try:
... raise Exception('spam', 'eggs')
... except Exception, inst:
... print type(inst) # the exception instance
... print inst.args # arguments stored in .args
... print inst # __str__ allows args to printed directly
... x, y = inst # __getitem__ allows args to be unpacked directly
... print 'x =', x
... print 'y =', y
...
<type 'instance'>
('spam', 'eggs')
('spam', 'eggs')
x = spam
y = eggs
```
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 repr(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
Previous:
8. Errors and Exceptions (node10.html)
Up:
Python Tutorial (tut.html)
Next:
10. What Now? (node12.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.8 Exceptions Are Classes Too (node11.html#SECTION0011800000000000000000)
  9.9 Iterators (node11.html#SECTION0011900000000000000000)
  9.10 Generators (node11.html#SECTION00111000000000000000000)
---
# 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
eliminates 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 (#foot1513)
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, there are at least three nested scopes whose
namespaces are directly accessible: the innermost scope, which is searched
first, contains the local names; the namespaces of any enclosing
functions, which are searched starting with the nearest enclosing scope;
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.
If a name is declared global, then all references and assignments go
directly to the middle scope containing the module's global names.
Otherwise, all variables found outside of the innermost scope are read-only.
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 True:
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.
# 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.8 Exceptions Are Classes Too
User-defined exceptions are 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
```
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().
# 9.9 Iterators
By now, you've probably noticed that most container objects can looped over
using a `for` statement:
```text

for element in [1, 2, 3]:
print element
for element in (1, 2, 3):
print element
for key in {'one':1, 'two':2}:
print key
for char in "123":
print char
for line in open("myfile.txt"):
print line
```
This style of access is clear, concise, and convenient. The use of iterators
pervades and unifies Python. Behind the scenes, the `for` statement calls
iter() on the container object. The function returns an iterator
object that defines the method next() which accesses elements in the
container one at a time. When there are no more elements, next()
raises a StopIteration exception which tells the `for` loop
to terminate. This example shows how it all works:
```text

>>> s = 'abc'
>>> it = iter(s)
>>> it
<iterator object at 0x00A1DB50>
>>> it.next()
'a'
>>> it.next()
'b'
>>> it.next()
'c'
>>> it.next()

Traceback (most recent call last):
File "<pyshell#6>", line 1, in -toplevel-
it.next()
StopIteration
```
Having seen the mechanics behind the iterator protocol, it is easy to add
iterator behavior to your classes. Define a __iter__() method
which returns an object with a next() method. If the class defines
next(), then __iter__() can just return `self`:
```text

>>> class Reverse:
"Iterator for looping over a sequence backwards"
def __init__(self, data):
self.data = data
self.index = len(data)
def __iter__(self):
return self
def next(self):
if self.index == 0:
raise StopIteration
self.index = self.index - 1
return self.data[self.index]

>>> for char in Reverse('spam'):
print char

m
a
p
s
```
# 9.10 Generators
Generators are a simple and powerful tool for creating iterators. They are
written like regular functions but use the yield statement whenever
they want to return data. Each time the next() is called, the
generator resumes where it left-off (it remembers all the data values and
which statement was last executed). An example shows that generators can
be trivially easy to create:
```text

>>> def reverse(data):
for index in range(len(data)-1, -1, -1):
yield data[index]

>>> for char in reverse('golf'):
print char

f
l
o
g
```
Anything that can be done with generators can also be done with class based
iterators as described in the previous section. What makes generators so
compact is that the __iter__() and next() methods are
created automatically.
Another key feature is that the local variables and execution state
are automatically saved between calls. This made the function easier to write
and much more clear than an approach using class variables like
`self.index` and `self.data`.
In addition to automatic method creation and saving program state, when
generators terminate, they automatically raise StopIteration.
In combination, these features make it easy to create iterators with no
more effort than writing a regular function.


10. What Now?

node11.html | tut.html | node13.html | Python Tutorial | node2.html
Previous:
9. Classes (node11.html)
Up:
Python Tutorial (tut.html)
Next:
A. Interactive Input Editing (node13.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. Many more user-created Python modules
can be found in a third-party repository at
http://www.vex.net/parnassus.
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 (with peaks
up to several hundred),
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.