This is /home/pdm/install/Python-2.1/Doc/ref/python-ref.info, produced
by makeinfo version 4.0 from ref.texi.

   April 15, 2001		2.1


File: python-ref.info,  Node: Summary,  Prev: Expression lists,  Up: Expressions

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).

Operator                             Description
------                               -----
`lambda'                             Lambda expression
`or'                                 Boolean OR
`and'                                Boolean AND
`not' X                              Boolean NOT
`in', `not' `in'                     Membership tests
`is', `is not'                       Identity tests
`<', `<=', `>', `>=', `<>', `!=',    Comparisons
`=='                                 
`|'                                  Bitwise OR
`^'                                  Bitwise XOR
`&'                                  Bitwise AND
`<'`<', `>'`>'                       Shifts
`+', `-'                             Addition and subtraction
`*', `/', `%'                        Multiplication, division, remainder
`**'                                 Exponentiation
`+X', `-X'                           Positive, negative
`~X'                                 Bitwise not
`X.ATTRIBUTE'                        Attribute reference
`X[INDEX]'                           Subscription
`X[INDEX:INDEX]'                     Slicing
`F(ARGUMENTS...)'                    Function call
`(EXPRESSIONS...)'                   Binding or tuple display
`[EXPRESSIONS...]'                   List display
`{KEY:DATUM...}'                     Dictionary display
``EXPRESSIONS...`'                   String conversion


File: python-ref.info,  Node: Simple statements,  Next: Compound statements,  Prev: Expressions,  Up: Top

Simple statements
*****************

   Simple statements are comprised within a single logical line.
Several simple statements may occur on a single line separated by
semicolons.  The syntax for simple statements is:

     simple_stmt:    expression_stmt
                   | assert_stmt
                   | assignment_stmt
                   | augmented_assignment_stmt
                   | pass_stmt
                   | del_stmt
                   | print_stmt
                   | return_stmt
                   | raise_stmt
                   | break_stmt
                   | continue_stmt
                   | import_stmt
                   | global_stmt
                   | exec_stmt

* Menu:

* Expression statements::
* Assert statements::
* Assignment statements::
* pass statement::
* del statement::
* print statement::
* return statement::
* raise statement::
* break statement::
* continue statement::
* import statement::
* global statement::
* exec statement::


File: python-ref.info,  Node: Expression statements,  Next: Assert statements,  Prev: Simple statements,  Up: Simple statements

Expression statements
=====================

   Expression statements are used (mostly interactively) to compute and
write a value, or (usually) to call a procedure (a function that
returns no meaningful result; in Python, procedures return the value
`None').  Other uses of expression statements are allowed and
occasionally useful.  The syntax for an expression statement is:

     expression_stmt: expression_list

   An expression statement evaluates the expression list (which may be a
single expression).

   In interactive mode, if the value is not `None', it is converted to
a string using the built-in `repr()'function and the resulting string
is written to standard output (see section *Note print statement::) on
a line by itself.  (Expression statements yielding None are not
written, so that procedure calls do not cause any output.)


File: python-ref.info,  Node: Assert statements,  Next: Assignment statements,  Prev: Expression statements,  Up: Simple statements

Assert statements
=================

   Assert statements are a convenient way to insert debugging
assertions into a program:

     assert_statement: "assert" expression ["," expression]

   The simple form, `assert expression', is equivalent to

     if __debug__:
        if not expression: raise AssertionError

   The extended form, `assert expression1, expression2', is equivalent
to

     if __debug__:
        if not expression1: raise AssertionError, expression2

   These equivalences assume that `__debug__' and `AssertionError'
refer to the built-in variables with those names.  In the current
implementation, the built-in variable `__debug__' is 1 under normal
circumstances, 0 when optimization is requested (command line option
-O).  The current code generator emits no code for an assert statement
when optimization is requested at compile time.  Note that it is
unnecessary to include the source code for the expression that failed
in the error message; it will be displayed as part of the stack trace.

   Assignments to `__debug__' are illegal.  The value for the built-in
variable is determined when the interpreter starts.


File: python-ref.info,  Node: Assignment statements,  Next: pass statement,  Prev: Assert statements,  Up: Simple statements

Assignment statements
=====================

   Assignment statements are used to (re)bind names to values and to
modify attributes or items of mutable objects:

     assignment_stmt: (target_list "=")+ expression_list
     target_list:     target ("," target)* [","]
     target:          identifier | "(" target_list ")" | "[" target_list "]"
                    | attributeref | subscription | slicing

   (See section *Note Primaries:: for the syntax definitions for the
last three symbols.)

   An assignment statement evaluates the expression list (remember that
this can be a single expression or a comma-separated list, the latter
yielding a tuple) and assigns the single resulting object to each of
the target lists, from left to right.

   Assignment is defined recursively depending on the form of the target
(list).  When a target is part of a mutable object (an attribute
reference, subscription or slicing), the mutable object must ultimately
perform the assignment and decide about its validity, and may raise an
exception if the assignment is unacceptable.  The rules observed by
various types and the exceptions raised are given with the definition
of the object types (see section *Note standard type hierarchy::).

   Assignment of an object to a target list is recursively defined as
follows.

   * If the target list is a single target: The object is assigned to
     that target.

   * If the target list is a comma-separated list of targets: The object
     must be a sequence with the same number of items as the there are
     targets in the target list, and the items are assigned, from left
     to right, to the corresponding targets.  (This rule is relaxed as
     of Python 1.5; in earlier versions, the object had to be a tuple.
     Since strings are sequences, an assignment like `a, b = "xy"' is
     now legal as long as the string has the right length.)


   Assignment of an object to a single target is recursively defined as
follows.

   * If the target is an identifier (name):

        * If the name does not occur in a `global' statement in the
          current code block: the name is bound to the object in the
          current local namespace.

        * Otherwise: the name is bound to the object in the current
          global namespace.


     The name is rebound if it was already bound.  This may cause the
     reference count for the object previously bound to the name to
     reach zero, causing the object to be deallocated and its
     destructor (if it has one) to be called.

   * If the target is a target list enclosed in parentheses or in square
     brackets: The object must be a sequence with the same number of
     items as there are targets in the target list, and its items are
     assigned, from left to right, to the corresponding targets.

   * If the target is an attribute reference: The primary expression in
     the reference is evaluated.  It should yield an object with
     assignable attributes; if this is not the case, `TypeError' is
     raised.  That object is then asked to assign the assigned object
     to the given attribute; if it cannot perform the assignment, it
     raises an exception (usually but not necessarily `AttributeError').

   * If the target is a subscription: The primary expression in the
     reference is evaluated.  It should yield either a mutable sequence
     object (e.g., a list) or a mapping object (e.g., a dictionary).
     Next, the subscript expression is evaluated.

     If the primary is a mutable sequence object (e.g., a list), the
     subscript must yield a plain integer.  If it is negative, the
     sequence's length is added to it.  The resulting value must be a
     nonnegative integer less than the sequence's length, and the
     sequence is asked to assign the assigned object to its item with
     that index.  If the index is out of range, `IndexError' is raised
     (assignment to a subscripted sequence cannot add new items to a
     list).

     If the primary is a mapping object (e.g., a dictionary), the
     subscript must have a type compatible with the mapping's key type,
     and the mapping is then asked to create a key/datum pair which
     maps the subscript to the assigned object.  This can either
     replace an existing key/value pair with the same key value, or
     insert a new key/value pair (if no key with the same value
     existed).

   * If the target is a slicing: The primary expression in the
     reference is evaluated.  It should yield a mutable sequence object
     (e.g., a list).  The assigned object should be a sequence object
     of the same type.  Next, the lower and upper bound expressions are
     evaluated, insofar they are present; defaults are zero and the
     sequence's length.  The bounds should evaluate to (small)
     integers.  If either bound is negative, the sequence's length is
     added to it.  The resulting bounds are clipped to lie between zero
     and the sequence's length, inclusive.  Finally, the sequence
     object is asked to replace the slice with the items of the
     assigned sequence.  The length of the slice may be different from
     the length of the assigned sequence, thus changing the length of
     the target sequence, if the object allows it.


   (In the current implementation, the syntax for targets is taken to
be the same as for expressions, and invalid syntax is rejected during
the code generation phase, causing less detailed error messages.)

   WARNING: Although the definition of assignment implies that overlaps
between the left-hand side and the right-hand side are `safe' (e.g.,
`a, b = b, a' swaps two variables), overlaps _within_ the collection of
assigned-to variables are not safe!  For instance, the following
program prints `[0, 2]':

     x = [0, 1]
     i = 0
     i, x[i] = 1, 2
     print x

* Menu:

* Augmented Assignment statements::


File: python-ref.info,  Node: Augmented Assignment statements,  Prev: Assignment statements,  Up: Assignment statements

Augmented Assignment statements
-------------------------------

   Augmented assignment is the combination, in a single statement, of a
binary operation and an assignment statement:

     augmented_assignment_stmt: target augop expression_list
     augop:           "+=" | "-=" | "*=" | "/=" | "%=" | "**="
                    | ">>=" | "<<=" | "&=" | "^=" | "|="
     target:          identifier | "(" target_list ")" | "[" target_list "]"
                    | attributeref | subscription | slicing

   (See section *Note Primaries:: for the syntax definitions for the
last three symbols.)

   An augmented assignment evaluates the target (which, unlike normal
assignment statements, cannot be an unpacking) and the expression list,
performs the binary operation specific to the type of assignment on the
two operands, and assigns the result to the original target.  The
target is only evaluated once.

   An augmented assignment expression like `x += 1' can be rewritten as
`x = x + 1' to achieve a similar, but not exactly equal effect. In the
augmented version, `x' is only evaluated once. Also, when possible, the
actual operation is performed _in-place_, meaning that rather than
creating a new object and assigning that to the target, the old object
is modified instead.

   With the exception of assigning to tuples and multiple targets in a
single statement, the assignment done by augmented assignment
statements is handled the same way as normal assignments. Similarly,
with the exception of the possible _in-place_ behaviour, the binary
operation performed by augmented assignment is the same as the normal
binary operations.


File: python-ref.info,  Node: pass statement,  Next: del statement,  Prev: Assignment statements,  Up: Simple statements

The `pass' statement
====================

     pass_stmt:      "pass"

   `pass' is a null operation -- when it is executed, nothing happens.
It is useful as a placeholder when a statement is required
syntactically, but no code needs to be executed, for example:

     def f(arg): pass    # a function that does nothing (yet)
     
     class C: pass       # a class with no methods (yet)


File: python-ref.info,  Node: del statement,  Next: print statement,  Prev: pass statement,  Up: Simple statements

The `del' statement
===================

     del_stmt:       "del" target_list

   Deletion is recursively defined very similar to the way assignment is
defined. Rather that spelling it out in full details, here are some
hints.

   Deletion of a target list recursively deletes each target, from left
to right.

   Deletion of a name removes the binding of that name (which must
exist) from the local or global namespace, depending on whether the name
occurs in a `global' statement in the same code block.

   Deletion of attribute references, subscriptions and slicings is
passed to the primary object involved; deletion of a slicing is in
general equivalent to assignment of an empty slice of the right type
(but even this is determined by the sliced object).


File: python-ref.info,  Node: print statement,  Next: return statement,  Prev: del statement,  Up: Simple statements

The `print' statement
=====================

     print_stmt:     "print" [ expression ("," expression)* [","] ]

   `print' evaluates each expression in turn and writes the resulting
object to standard output (see below).  If an object is not a string,
it is first converted to a string using the rules for string
conversions.  The (resulting or original) string is then written.  A
space is written before each object is (converted and) written, unless
the output system believes it is positioned at the beginning of a line.
This is the case (1) when no characters have yet been written to
standard output, (2) when the last character written to standard output
is `\n', or (3) when the last write operation on standard output was
not a `print' statement.  (In some cases it may be functional to write
an empty string to standard output for this reason.)

   A `\n' character is written at the end, unless the `print' statement
ends with a comma.  This is the only action if the statement contains
just the keyword `print'.

   Standard output is defined as the file object named `stdout' in the
built-in module `sys'.  If no such object exists, or if it does not
have a `write()' method, a `RuntimeError' exception is raised.

   `print' also has an extended form, defined as

     print_stmt: "print" ">>" expression [ ("," expression)+ [","] ]

   In this form, the first expression after the `>'`>' must evaluate to
a "file-like" object, specifically an object that has a `write()'
method as described above.  With this extended form, the subsequent
expressions are printed to this file object.  If the first expression
evaluates to `None', then `sys.stdout' is used as the file for output.


File: python-ref.info,  Node: return statement,  Next: raise statement,  Prev: print statement,  Up: Simple statements

The `return' statement
======================

     return_stmt:    "return" [expression_list]

   `return' may only occur syntactically nested in a function
definition, not within a nested class definition.

   If an expression list is present, it is evaluated, else `None' is
substituted.

   `return' leaves the current function call with the expression list
(or `None') as return value.

   When `return' passes control out of a `try' statement with a
`finally' clause, that `finally' clause is executed before really
leaving the function.


File: python-ref.info,  Node: raise statement,  Next: break statement,  Prev: return statement,  Up: Simple statements

The `raise' statement
=====================

     raise_stmt:     "raise" [expression ["," expression ["," expression]]]

   If no expressions are present, `raise' re-raises the last expression
that was raised in the current scope.

   Otherwise, `raise' evaluates its first expression, which must yield
a string, class, or instance object.  If there is a second expression,
this is evaluated, else `None' is substituted.  If the first expression
is a class object, then the second expression may be an instance of
that class or one of its derivatives, and then that instance is raised.
If the second expression is not such an instance, the given class is
instantiated.  The argument list for the instantiation is determined as
follows: if the second expression is a tuple, it is used as the
argument list; if it is `None', the argument list is empty; otherwise,
the argument list consists of a single argument which is the second
expression.  If the first expression is an instance object, the second
expression must be `None'.

   If the first object is a string, it then raises the exception
identified by the first object, with the second one (or `None') as its
parameter.  If the first object is a class or instance, it raises the
exception identified by the class of the instance determined in the
previous step, with the instance as its parameter.

   If a third object is present, and it is not `None', it should be a
traceback object (see section *Note standard type hierarchy::), and it
is substituted instead of the current location as the place where the
exception occurred.  This is useful to re-raise an exception
transparently in an except clause.


File: python-ref.info,  Node: break statement,  Next: continue statement,  Prev: raise statement,  Up: Simple statements

The `break' statement
=====================

     break_stmt:     "break"

   `break' may only occur syntactically nested in a `for' or `while'
loop, but not nested in a function or class definition within that loop.

   It terminates the nearest enclosing loop, skipping the optional
`else' clause if the loop has one.

   If a `for' loop is terminated by `break', the loop control target
keeps its current value.

   When `break' passes control out of a `try' statement with a
`finally' clause, that `finally' clause is executed before really
leaving the loop.


File: python-ref.info,  Node: continue statement,  Next: import statement,  Prev: break statement,  Up: Simple statements

The `continue' statement
========================

     continue_stmt:  "continue"

   `continue' may only occur syntactically nested in a `for' or `while'
loop, but not nested in a function or class definition or `try'
statement within that loop.(1) It continues with the next cycle of the
nearest enclosing loop.

   ---------- Footnotes ----------

   (1) It may occur within an `except' or `else' clause.  The
restriction on occurring in the `try' clause is implementor's laziness
and will eventually be lifted.


File: python-ref.info,  Node: import statement,  Next: global statement,  Prev: continue statement,  Up: Simple statements

The `import' statement
======================

     import_stmt:    "import" module ["as" name] ("," module ["as" name] )*
                   | "from" module "import" identifier ["as" name]
                     ("," identifier ["as" name] )*
                   | "from" module "import" "*"
     module:         (identifier ".")* identifier

   Import statements are executed in two steps: (1) find a module, and
initialize it if necessary; (2) define a name or names in the local
namespace (of the scope where the `import' statement occurs).  The
first form (without `from') repeats these steps for each identifier in
the list.  The form with `from' performs step (1) once, and then
performs step (2) repeatedly.

   The system maintains a table of modules that have been initialized,
indexed by module name.  This table is accessible as `sys.modules'.
When a module name is found in this table, step (1) is finished.  If
not, a search for a module definition is started.  When a module is
found, it is loaded.  Details of the module searching and loading
process are implementation and platform specific.  It generally
involves searching for a "built-in" module with the given name and then
searching a list of locations given as `sys.path'.

   If a built-in module is found, its built-in initialization code is
executed and step (1) is finished.  If no matching file is found,
`ImportError' is raised.  If a file is found, it is parsed, yielding an
executable code block.  If a syntax error occurs, `SyntaxError' is
raised.  Otherwise, an empty module of the given name is created and
inserted in the module table, and then the code block is executed in
the context of this module.  Exceptions during this execution terminate
step (1).

   When step (1) finishes without raising an exception, step (2) can
begin.

   The first form of `import' statement binds the module name in the
local namespace to the module object, and then goes on to import the
next identifier, if any.  If the module name is followed by `as', the
name following `as' is used as the local name for the module. To avoid
confusion, you cannot import modules with dotted names `as' a different
local name. So `import module as m' is legal, but `import module.submod
as s' is not.  The latter should be written as `from module import
submod as s'; see below.

   The `from' form does not bind the module name: it goes through the
list of identifiers, looks each one of them up in the module found in
step (1), and binds the name in the local namespace to the object thus
found.  As with the first form of `import', an alternate local name can
be supplied by specifying "`as' localname".  If a name is not found,
`ImportError' is raised.  If the list of identifiers is replaced by a
star (`*'), all names defined in the module are bound, except those
beginning with an underscore (`_').

   Names bound by `import' statements may not occur in `global'
statements in the same scope.

   The `from' form with `*' may only occur in a module scope.

   *Hierarchical module names:*when the module names contains one or
more dots, the module search path is carried out differently.  The
sequence of identifiers up to the last dot is used to find a "package";
the final identifier is then searched inside the package.  A package is
generally a subdirectory of a directory on `sys.path' that has a file
`__init__.py'.[XXX Can't be bothered to spell this out right now; see
the URL <http://www.python.org/doc/essays/packages.html> for more
details, also about how the module search works from inside a package.]

   [XXX Also should mention __import__().]


File: python-ref.info,  Node: global statement,  Next: exec statement,  Prev: import statement,  Up: Simple statements

The `global' statement
======================

     global_stmt:    "global" identifier ("," identifier)*

   The `global' statement is a declaration which holds for the entire
current code block.  It means that the listed identifiers are to be
interpreted as globals.  While _using_ global names is automatic if
they are not defined in the local scope, _assigning_ to global names
would be impossible without `global'.

   Names listed in a `global' statement must not be used in the same
code block textually preceding that `global' statement.

   Names listed in a `global' statement must not be defined as formal
parameters or in a `for' loop control target, `class' definition,
function definition, or `import' statement.

   (The current implementation does not enforce the latter two
restrictions, but programs should not abuse this freedom, as future
implementations may enforce them or silently change the meaning of the
program.)

   *Programmer's note:* the `global' is a directive to the parser.  It
applies only to code parsed at the same time as the `global' statement.
In particular, a `global' statement contained in an `exec' statement
does not affect the code block _containing_ the `exec' statement, and
code contained in an `exec' statement is unaffected by `global'
statements in the code containing the `exec' statement.  The same
applies to the `eval()', `execfile()' and `compile()' functions.


File: python-ref.info,  Node: exec statement,  Prev: global statement,  Up: Simple statements

The `exec' statement
====================

     exec_stmt:    "exec" expression ["in" expression ["," expression]]

   This statement supports dynamic execution of Python code.  The first
expression should evaluate to either a string, an open file object, or
a code object.  If it is a string, the string is parsed as a suite of
Python statements which is then executed (unless a syntax error
occurs).  If it is an open file, the file is parsed until EOF and
executed.  If it is a code object, it is simply executed.

   In all cases, if the optional parts are omitted, the code is executed
in the current scope.  If only the first expression after `in' is
specified, it should be a dictionary, which will be used for both the
global and the local variables.  If two expressions are given, both
must be dictionaries and they are used for the global and local
variables, respectively.

   As a side effect, an implementation may insert additional keys into
the dictionaries given besides those corresponding to variable names
set by the executed code.  For example, the current implementation may
add a reference to the dictionary of the built-in module `__builtin__'
under the key `__builtins__' (!).

   *Programmer's hints:* dynamic evaluation of expressions is supported
by the built-in function `eval()'.  The built-in functions `globals()'
and `locals()' return the current global and local dictionary,
respectively, which may be useful to pass around for use by `exec'.

   Also, in the current implementation, multi-line compound statements
must end with a newline: `exec "for v in seq:\n\tprint v\n"' works, but
`exec "for v in seq:\n\tprint v"' fails with `SyntaxError'.


File: python-ref.info,  Node: Compound statements,  Next: Top-level components,  Prev: Simple statements,  Up: Top

Compound statements
*******************

   Compound statements contain (groups of) other statements; they affect
or control the execution of those other statements in some way.  In
general, compound statements span multiple lines, although in simple
incarnations a whole compound statement may be contained in one line.

   The `if', `while' and `for' statements implement traditional control
flow constructs.  `try' specifies exception handlers and/or cleanup
code for a group of statements.  Function and class definitions are
also syntactically compound statements.

   Compound statements consist of one or more `clauses.'  A clause
consists of a header and a `suite.'  The clause headers of a particular
compound statement are all at the same indentation level.  Each clause
header begins with a uniquely identifying keyword and ends with a
colon.  A suite is a group of statements controlled by a clause.  A
suite can be one or more semicolon-separated simple statements on the
same line as the header, following the header's colon, or it can be one
or more indented statements on subsequent lines.  Only the latter form
of suite can contain nested compound statements; the following is
illegal, mostly because it wouldn't be clear to which `if' clause a
following `else' clause would belong:

     if test1: if test2: print x

   Also note that the semicolon binds tighter than the colon in this
context, so that in the following example, either all or none of the
`print' statements are executed:

     if x < y < z: print x; print y; print z

   Summarizing:

     compound_stmt:  if_stmt | while_stmt | for_stmt
                   | try_stmt | funcdef | classdef
     suite:          stmt_list NEWLINE | NEWLINE INDENT statement+ DEDENT
     statement:      stmt_list NEWLINE | compound_stmt
     stmt_list:      simple_stmt (";" simple_stmt)* [";"]

   Note that statements always end in a `NEWLINE' possibly followed by a
`DEDENT'. Also note that optional continuation clauses always begin
with a keyword that cannot start a statement, thus there are no
ambiguities (the `dangling `else'' problem is solved in Python by
requiring nested `if' statements to be indented).

   The formatting of the grammar rules in the following sections places
each clause on a separate line for clarity.

* Menu:

* if statement::
* while statement::
* for statement::
* try statement::
* Function definitions::
* Class definitions::


File: python-ref.info,  Node: if statement,  Next: while statement,  Prev: Compound statements,  Up: Compound statements

The `if' statement
==================

   The `if' statement is used for conditional execution:

     if_stmt:        "if" expression ":" suite
                    ("elif" expression ":" suite)*
                    ["else" ":" suite]

   It selects exactly one of the suites by evaluating the expressions
one by one until one is found to be true (see section *Note Boolean
operations:: for the definition of true and false); then that suite is
executed (and no other part of the `if' statement is executed or
evaluated).  If all expressions are false, the suite of the `else'
clause, if present, is executed.


File: python-ref.info,  Node: while statement,  Next: for statement,  Prev: if statement,  Up: Compound statements

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]

   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.


File: python-ref.info,  Node: for statement,  Next: try statement,  Prev: while statement,  Up: Compound statements

The `for' statement
===================

   The `for' statement is used to iterate over the elements of a
sequence (string, tuple or list):

     for_stmt:       "for" target_list "in" expression_list ":" suite
                    ["else" ":" suite]

   The expression list is evaluated once; it should yield a sequence.
The suite is then executed once for each item in the sequence, in the
order of ascending indices.  Each item in turn is assigned to the
target list using the standard rules for assignments, and then the
suite is executed.  When the items are exhausted (which is immediately
when the sequence is empty), the suite in 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 continues
with the next item, or with the `else' clause if there was no next item.

   The suite may assign to the variable(s) in the target list; this does
not affect the next item assigned to it.

   The target list is not deleted when the loop is finished, but if the
sequence is empty, it will not have been assigned to at all by the
loop.  Hint: the built-in function `range()' returns a sequence of
integers suitable to emulate the effect of Pascal's `for i := a to b
do'; e.g., `range(3)' returns the list `[0, 1, 2]'.

   *Warning:* There is a subtlety when the sequence is being modified
by the loop (this can only occur for mutable sequences, i.e. lists).
An internal counter is used to keep track of which item is used next,
and this is incremented on each iteration.  When this counter has
reached the length of the sequence the loop terminates.  This means that
if the suite deletes the current (or a previous) item from the
sequence, the next item will be skipped (since it gets the index of the
current item which has already been treated).  Likewise, if the suite
inserts an item in the sequence before the current item, the current
item will be treated again the next time through the loop.  This can
lead to nasty bugs that can be avoided by making a temporary copy using
a slice of the whole sequence, e.g.,

     for x in a[:]:
         if x < 0: a.remove(x)


File: python-ref.info,  Node: try statement,  Next: Function definitions,  Prev: for statement,  Up: Compound statements

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

   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 `sys' module:
`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 *Note standard type
hierarchy::) 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.(1) 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 -
thsi 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).

   ---------- Footnotes ----------

   (1)  Currently, control "flows off the end" except in the case of an
exception or the execution of a `return', `continue', or `break'
statement.


File: python-ref.info,  Node: Function definitions,  Next: Class definitions,  Prev: try statement,  Up: Compound statements

Function definitions
====================

   A function definition defines a user-defined function object (see
section *Note standard type hierarchy::):

     funcdef:        "def" funcname "(" [parameter_list] ")" ":" suite
     parameter_list: (defparameter ",")* ("*" identifier [, "**" identifier]
                                         | "**" identifier
                                         | defparameter [","])
     defparameter:   parameter ["=" expression]
     sublist:        parameter ("," parameter)* [","]
     parameter:      identifier | "(" sublist ")"
     funcname:       identifier

   A function definition is an executable statement.  Its execution
binds the function name in the current local namespace to a function
object (a wrapper around the executable code for the function).  This
function object contains a reference to the current global namespace as
the global namespace to be used when the function is called.

   The function definition does not execute the function body; this gets
executed only when the function is called.

   When one or more top-level parameters have the form PARAMETER `='
EXPRESSION, the function is said to have "default parameter values."
For a parameter with a default value, the corresponding argument may be
omitted from a call, in which case the parameter's default value is
substituted.  If a parameter has a default value, all following
parameters must also have a default value -- this is a syntactic
restriction that is not expressed by the grammar.

   *Default parameter values are evaluated when the function definition
is executed.*  This means that the expression is evaluated once, when
the function is defined, and that that same "pre-computed" value is
used for each call.  This is especially important to understand when a
default parameter is a mutable object, such as a list or a dictionary:
if the function modifies the object (e.g. by appending an item to a
list), the default value is in effect modified.  This is generally not
what was intended.  A way around this is to use `None' as the default,
and explicitly test for it in the body of the function, e.g.:

     def whats_on_the_telly(penguin=None):
         if penguin is None:
             penguin = []
         penguin.append("property of the zoo")
         return penguin

   Function call semantics are described in more detail in section
*Note Calls::.  A function call always assigns values to all parameters
mentioned in the parameter list, either from position arguments, from
keyword arguments, or from default values.  If the form "`*identifier'"
is present, it is initialized to a tuple receiving any excess
positional parameters, defaulting to the empty tuple.  If the form
"`**identifier'" is present, it is initialized to a new dictionary
receiving any excess keyword arguments, defaulting to a new empty
dictionary.

   It is also possible to create anonymous functions (functions not
bound to a name), for immediate use in expressions.  This uses lambda
forms, described in section *Note Boolean operations::.  Note that the
lambda form is merely a shorthand for a simplified function definition;
a function defined in a "`def'" statement can be passed around or
assigned to another name just like a function defined by a lambda form.
The "`def'" form is actually more powerful since it allows the
execution of multiple statements.

   *Programmer's note:* a "`def'" form executed inside a function
definition defines a local function that can be returned or passed
around.  The semantics of name resolution in the nested function will
change in Python 2.2.  See the appendix for a description of the new
semantics.


File: python-ref.info,  Node: Class definitions,  Prev: Function definitions,  Up: Compound statements

Class definitions
=================

   A class definition defines a class object (see section *Note
standard type hierarchy::):

     classdef:       "class" classname [inheritance] ":" suite
     inheritance:    "(" [expression_list] ")"
     classname:      identifier

   A class definition is an executable statement.  It first evaluates
the inheritance list, if present.  Each item in the inheritance list
should evaluate to a class object.  The class's suite is then executed
in a new execution frame (see section *Note Code blocks::), using a
newly created local namespace and the original global namespace.
(Usually, the suite contains only function definitions.)  When the
class's suite finishes execution, its execution frame is discarded but
its local namespace is saved.  A class object is then created using the
inheritance list for the base classes and the saved local namespace for
the attribute dictionary.  The class name is bound to this class object
in the original local namespace.

   *Programmer's note:* variables defined in the class definition are
class variables; they are shared by all instances.  To define instance
variables, they must be given a value in the the `__init__()' method or
in another method.  Both class and instance variables are accessible
through the notation "`code{self.name}", and an instance variable hides
a class variable with the same name when accessed in this way.  Class
variables with immutable values can be used as defaults for instance
variables.


File: python-ref.info,  Node: Top-level components,  Next: Future statements and nested scopes,  Prev: Compound statements,  Up: Top

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.

* Menu:

* Complete Python programs::
* File input::
* Interactive input::
* Expression input::


File: python-ref.info,  Node: Complete Python programs,  Next: File input,  Prev: Top-level components,  Up: Top-level components

Complete Python programs
========================

   While a language specification need not prescribe how the language
interpreter is invoked, it is useful to have a notion of a complete
Python program.  A complete Python program is executed in a minimally
initialized environment: all built-in and standard modules are
available, but none have been initialized, except for `sys' (various
system services), `__builtin__' (built-in functions, exceptions and
`None') and `__main__'.  The latter is used to provide the local and
global namespace for execution of the complete program.

   The syntax for a complete Python program is that for file input,
described in the next section.

   The interpreter may also be invoked in interactive mode; in this
case, it does not read and execute a complete program but reads and
executes one statement (possibly compound) at a time.  The initial
environment is identical to that of a complete program; each statement
is executed in the namespace of `__main__'.

   Under {UNIX}, a complete program can be passed to the interpreter in
three forms: with the `-c' STRING command line option, as a file passed
as the first command line argument, or as standard input.  If the file
or standard input is a tty device, the interpreter enters interactive
mode; otherwise, it executes the file as a complete program.


File: python-ref.info,  Node: File input,  Next: Interactive input,  Prev: Complete Python programs,  Up: Top-level components

File input
==========

   All input read from non-interactive files has the same form:

     file_input:     (NEWLINE | statement)*

   This syntax is used in the following situations:

   * when parsing a complete Python program (from a file or from a
     string);

   * when parsing a module;

   * when parsing a string passed to the `exec' statement;



File: python-ref.info,  Node: Interactive input,  Next: Expression input,  Prev: File input,  Up: Top-level components

Interactive input
=================

   Input in interactive mode is parsed using the following grammar:

     interactive_input: [stmt_list] NEWLINE | compound_stmt NEWLINE

   Note that a (top-level) compound statement must be followed by a
blank line in interactive mode; this is needed to help the parser
detect the end of the input.


File: python-ref.info,  Node: Expression input,  Prev: Interactive input,  Up: Top-level components

Expression input
================

   There are two forms of expression input.  Both ignore leading
whitespace.  The string argument to `eval()' must have the following
form:

     eval_input:     expression_list NEWLINE*

   The input line read by `input()' must have the following form:

     input_input:    expression_list NEWLINE

   Note: to read `raw' input line without interpretation, you can use
the built-in function `raw_input()' or the `readline()' method of file
objects.


File: python-ref.info,  Node: Future statements and nested scopes,  Next: Module Index,  Prev: Top-level components,  Up: Top

Future statements and nested scopes
***********************************

   This section was written by Jeremy Hylton <jeremy@alum.mit.edu>.
The semantics of Python's static scoping will change in version 2.2 to
support resolution of unbound local names in enclosing functions'
namespaces.  The new semantics will be available in Python 2.1 through
the use of a future statement.  This appendix documents these two
features for Python 2.1; it will be removed in Python 2.2 and the
features will be documented in the main sections of this manual.

* Menu:

* Future statements::
* __future__::
* Nested scopes::

