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

   April 15, 2001		2.1


File: python-tut.info,  Node: Defining Functions,  Next: More on Defining Functions,  Prev: pass Statements,  Up: More Control Flow Tools

Defining Functions
==================

   We can create a function that writes the Fibonacci series to an
arbitrary boundary:

     >>> def fib(n):    # write Fibonacci series up to n
     ...     "Print a Fibonacci series up to n"
     ...     a, b = 0, 1
     ...     while b < n:
     ...         print b,
     ...         a, b = b, a+b
     ...
     >>> # Now call the function we just defined:
     ... fib(2000)
     1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597

   The keyword `def' introduces a function _definition_.  It must be
followed by the function name and the parenthesized list of formal
parameters.  The statements that form the body of the function start at
the next line, and must be indented.  The first statement of the
function body can optionally be a string literal; this string literal
is the function's documentation string, or "docstring".

   There are tools which use docstrings to automatically produce online
or printed documentation, or to let the user interactively browse
through code; it's good practice to include docstrings in code that you
write, so try to make a habit of it.

   The _execution_ of a function introduces a new symbol table used for
the local variables of the function.  More precisely, all variable
assignments in a function store the value in the local symbol table;
whereas variable references first look in the local symbol table, then
in the global symbol table, and then in the table of built-in names.
Thus,  global variables cannot be directly assigned a value within a
function (unless named in a `global' statement), although they may be
referenced.

   The actual parameters (arguments) to a function call are introduced
in the local symbol table of the called function when it is called;
thus, arguments are passed using _call by value_ (where the _value_ is
always an object _reference_, not the value of the object).(1) When a
function calls another function, a new local symbol table is created
for that call.

   A function definition introduces the function name in the current
symbol table.  The value of the function name has a type that is
recognized by the interpreter as a user-defined function.  This value
can be assigned to another name which can then also be used as a
function.  This serves as a general renaming mechanism:

     >>> fib
     <function object at 10042ed0>
     >>> f = fib
     >>> f(100)
     1 1 2 3 5 8 13 21 34 55 89

   You might object that `fib' is not a function but a procedure.  In
Python, like in C, procedures are just functions that don't return a
value.  In fact, technically speaking, procedures do return a value,
albeit a rather boring one.  This value is called `None' (it's a
built-in name).  Writing the value `None' is normally suppressed by the
interpreter if it would be the only value written.  You can see it if
you really want to:

     >>> print fib(0)
     None

   It is simple to write a function that returns a list of the numbers
of the Fibonacci series, instead of printing it:

     >>> def fib2(n): # return Fibonacci series up to n
     ...     "Return a list containing the Fibonacci series up to n"
     ...     result = []
     ...     a, b = 0, 1
     ...     while b < n:
     ...         result.append(b)    # see below
     ...         a, b = b, a+b
     ...     return result
     ...
     >>> f100 = fib2(100)    # call it
     >>> f100                # write the result
     [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]

   This example, as usual, demonstrates some new Python features:

   * The `return' statement returns with a value from a function.
     `return' without an expression argument returns `None'.  Falling
     off the end of a procedure also returns `None'.

   * The statement `result.append(b)' calls a _method_ of the list
     object `result'.  A method is a function that `belongs' to an
     object and is named `obj.methodname', where `obj' is some object
     (this may be an expression), and `methodname' is the name of a
     method that is defined by the object's type.  Different types
     define different methods.  Methods of different types may have the
     same name without causing ambiguity.  (It is possible to define
     your own object types and methods, using _classes_, as discussed
     later in this tutorial.)  The method `append()' shown in the
     example, is defined for list objects; it adds a new element at the
     end of the list.  In this example it is equivalent to `result =
     result + [b]', but more efficient.


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

   (1)  Actually, _call by object reference_ would be a better
description, since if a mutable object is passed, the caller will see
any changes the callee makes to it (e.g., items inserted into a list).


File: python-tut.info,  Node: More on Defining Functions,  Prev: Defining Functions,  Up: More Control Flow Tools

More on Defining Functions
==========================

   It is also possible to define functions with a variable number of
arguments.  There are three forms, which can be combined.

* Menu:

* Default Argument Values::
* Keyword Arguments::
* Arbitrary Argument Lists::
* Lambda Forms::
* Documentation Strings::


File: python-tut.info,  Node: Default Argument Values,  Next: Keyword Arguments,  Prev: More on Defining Functions,  Up: More on Defining Functions

Default Argument Values
-----------------------

   The most useful form is to specify a default value for one or more
arguments.  This creates a function that can be called with fewer
arguments than it is defined, e.g.

     def ask_ok(prompt, retries=4, complaint='Yes or no, please!'):
         while 1:
             ok = raw_input(prompt)
             if ok in ('y', 'ye', 'yes'): return 1
             if ok in ('n', 'no', 'nop', 'nope'): return 0
             retries = retries - 1
             if retries < 0: raise IOError, 'refusenik user'
             print complaint

   This function can be called either like this: `ask_ok('Do you really
want to quit?')' or like this: `ask_ok('OK to overwrite the file?', 2)'.

   The default values are evaluated at the point of function definition
in the _defining_ scope, so that e.g.

     i = 5
     def f(arg = i): print arg
     i = 6
     f()

   will print `5'.

   *Important warning:*  The default value is evaluated only once.
This makes a difference when the default is a mutable object such as a
list or dictionary.  For example, the following function accumulates
the arguments passed to it on subsequent calls:

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

   This will print

     [1]
     [1, 2]
     [1, 2, 3]

   If you don't want the default to be shared between subsequent calls,
you can write the function like this instead:

     def f(a, l = None):
         if l is None:
             l = []
         l.append(a)
         return l


File: python-tut.info,  Node: Keyword Arguments,  Next: Arbitrary Argument Lists,  Prev: Default Argument Values,  Up: More on Defining Functions

Keyword Arguments
-----------------

   Functions can also be called using keyword arguments of the form
`KEYWORD = VALUE'.  For instance, the following function:

     def parrot(voltage, state='a stiff', action='voom', type='Norwegian Blue'):
         print "-- This parrot wouldn't", action,
         print "if you put", voltage, "Volts through it."
         print "-- Lovely plumage, the", type
         print "-- It's", state, "!"

   could be called in any of the following ways:

     parrot(1000)
     parrot(action = 'VOOOOOM', voltage = 1000000)
     parrot('a thousand', state = 'pushing up the daisies')
     parrot('a million', 'bereft of life', 'jump')

   but the following calls would all be invalid:

     parrot()                     # required argument missing
     parrot(voltage=5.0, 'dead')  # non-keyword argument following keyword
     parrot(110, voltage=220)     # duplicate value for argument
     parrot(actor='John Cleese')  # unknown keyword

   In general, an argument list must have any positional arguments
followed by any keyword arguments, where the keywords must be chosen
from the formal parameter names.  It's not important whether a formal
parameter has a default value or not.  No argument may receive a value
more than once -- formal parameter names corresponding to positional
arguments cannot be used as keywords in the same calls.  Here's an
example that fails due to this restriction:

     >>> def function(a):
     ...     pass
     ...
     >>> function(0, a=0)
     Traceback (most recent call last):
       File "<stdin>", line 1, in ?
     TypeError: keyword parameter redefined

   When a final formal parameter of the form `**NAME' is present, it
receives a dictionary containing all keyword arguments whose keyword
doesn't correspond to a formal parameter.  This may be combined with a
formal parameter of the form `*NAME' (described in the next subsection)
which receives a tuple containing the positional arguments beyond the
formal parameter list.  (`*NAME' must occur before `**NAME'.)  For
example, if we define a function like this:

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

   It could be called like this:

     cheeseshop('Limburger', "It's very runny, sir.",
                "It's really very, VERY runny, sir.",
                client='John Cleese',
                shopkeeper='Michael Palin',
                sketch='Cheese Shop Sketch')

   and of course it would print:

     -- Do you have any Limburger ?
     -- I'm sorry, we're all out of Limburger
     It's very runny, sir.
     It's really very, VERY runny, sir.
     ----------------------------------------
     client : John Cleese
     shopkeeper : Michael Palin
     sketch : Cheese Shop Sketch


File: python-tut.info,  Node: Arbitrary Argument Lists,  Next: Lambda Forms,  Prev: Keyword Arguments,  Up: More on Defining Functions

Arbitrary Argument Lists
------------------------

   Finally, the least frequently used option is to specify that a
function can be called with an arbitrary number of arguments.  These
arguments will be wrapped up in a tuple.  Before the variable number of
arguments, zero or more normal arguments may occur.

     def fprintf(file, format, *args):
         file.write(format % args)


File: python-tut.info,  Node: Lambda Forms,  Next: Documentation Strings,  Prev: Arbitrary Argument Lists,  Up: More on Defining Functions

Lambda Forms
------------

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

     >>> def make_incrementor(n):
     ...     return lambda x, incr=n: x+incr
     ...
     >>> f = make_incrementor(42)
     >>> f(0)
     42
     >>> f(1)
     43
     >>>


File: python-tut.info,  Node: Documentation Strings,  Prev: Lambda Forms,  Up: More on Defining Functions

Documentation Strings
---------------------

   There are emerging conventions about the content and formatting of
documentation strings.

   The first line should always be a short, concise summary of the
object's purpose.  For brevity, it should not explicitly state the
object's name or type, since these are available by other means (except
if the name happens to be a verb describing a function's operation).
This line should begin with a capital letter and end with a period.

   If there are more lines in the documentation string, the second line
should be blank, visually separating the summary from the rest of the
description.  The following lines should be one or more paragraphs
describing the object's calling conventions, its side effects, etc.

   The Python parser does not strip indentation from multi-line string
literals in Python, so tools that process documentation have to strip
indentation if desired.  This is done using the following convention.
The first non-blank line _after_ the first line of the string
determines the amount of indentation for the entire documentation
string.  (We can't use the first line since it is generally adjacent to
the string's opening quotes so its indentation is not apparent in the
string literal.)  Whitespace "equivalent" to this indentation is then
stripped from the start of all lines of the string.  Lines that are
indented less should not occur, but if they occur all their leading
whitespace should be stripped.  Equivalence of whitespace should be
tested after expansion of tabs (to 8 spaces, normally).

   Here is an example of a multi-line docstring:

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


File: python-tut.info,  Node: Data Structures,  Next: Modules,  Prev: More Control Flow Tools,  Up: Top

Data Structures
***************

   This chapter describes some things you've learned about already in
more detail, and adds some new things as well.

* Menu:

* More on Lists::
* del statement::
* Tuples and Sequences::
* Dictionaries::
* More on Conditions::
* Comparing Sequences and Other Types::


File: python-tut.info,  Node: More on Lists,  Next: del statement,  Prev: Data Structures,  Up: Data Structures

More on Lists
=============

   The list data type has some more methods.  Here are all of the
methods of list objects:

``append(x)''
     Add an item to the end of the list; equivalent to `a[len(a):] =
     [x]'.

``extend(L)''
     Extend the list by appending all the items in the given list;
     equivalent to `a[len(a):] = L'.

``insert(i, x)''
     Insert an item at a given position.  The first argument is the
     index of the element before which to insert, so `a.insert(0, x)'
     inserts at the front of the list, and `a.insert(len(a), x)' is
     equivalent to `a.append(x)'.

``remove(x)''
     Remove the first item from the list whose value is `x'.  It is an
     error if there is no such item.

``pop([i])''
     Remove the item at the given position in the list, and return it.
     If no index is specified, `a.pop()' returns the last item in the
     list.  The item is also removed from the list.

``index(x)''
     Return the index in the list of the first item whose value is `x'.
     It is an error if there is no such item.

``count(x)''
     Return the number of times `x' appears in the list.

``sort()''
     Sort the items of the list, in place.

``reverse()''
     Reverse the elements of the list, in place.

   An example that uses most of the list methods:

     >>> a = [66.6, 333, 333, 1, 1234.5]
     >>> print a.count(333), a.count(66.6), a.count('x')
     2 1 0
     >>> a.insert(2, -1)
     >>> a.append(333)
     >>> a
     [66.6, 333, -1, 333, 1, 1234.5, 333]
     >>> a.index(333)
     1
     >>> a.remove(333)
     >>> a
     [66.6, -1, 333, 1, 1234.5, 333]
     >>> a.reverse()
     >>> a
     [333, 1234.5, 1, 333, -1, 66.6]
     >>> a.sort()
     >>> a
     [-1, 1, 66.6, 333, 333, 1234.5]

* Menu:

* Using Lists as Stacks::
* Using Lists as Queues::
* Functional Programming Tools::
* List Comprehensions::


File: python-tut.info,  Node: Using Lists as Stacks,  Next: Using Lists as Queues,  Prev: More on Lists,  Up: More on Lists

Using Lists as Stacks
---------------------

   This section was written by Ka-Ping Yee <ping@lfw.org>.
The list methods make it very easy to use a list as a stack, where the
last element added is the first element retrieved ("last-in,
first-out").  To add an item to the top of the stack, use `append()'.
To retrieve an item from the top of the stack, use `pop()' without an
explicit index.  For example:

     >>> stack = [3, 4, 5]
     >>> stack.append(6)
     >>> stack.append(7)
     >>> stack
     [3, 4, 5, 6, 7]
     >>> stack.pop()
     7
     >>> stack
     [3, 4, 5, 6]
     >>> stack.pop()
     6
     >>> stack.pop()
     5
     >>> stack
     [3, 4]


File: python-tut.info,  Node: Using Lists as Queues,  Next: Functional Programming Tools,  Prev: Using Lists as Stacks,  Up: More on Lists

Using Lists as Queues
---------------------

   This section was written by Ka-Ping Yee <ping@lfw.org>.
You can also use a list conveniently as a queue, where the first
element added is the first element retrieved ("first-in, first-out").
To add an item to the back of the queue, use `append()'.  To retrieve
an item from the front of the queue, use `pop()' with `0' as the index.
For example:

     >>> queue = ["Eric", "John", "Michael"]
     >>> queue.append("Terry")           # Terry arrives
     >>> queue.append("Graham")          # Graham arrives
     >>> queue.pop(0)
     'Eric'
     >>> queue.pop(0)
     'John'
     >>> queue
     ['Michael', 'Terry', 'Graham']


File: python-tut.info,  Node: Functional Programming Tools,  Next: List Comprehensions,  Prev: Using Lists as Queues,  Up: More on Lists

Functional Programming Tools
----------------------------

   There are three built-in functions that are very useful when used
with lists: `filter()', `map()', and `reduce()'.

   `filter(FUNCTION, SEQUENCE)' returns a sequence (of the same type,
if possible) consisting of those items from the sequence for which
`FUNCTION(ITEM)' is true.  For example, to compute some primes:

     >>> def f(x): return x % 2 != 0 and x % 3 != 0
     ...
     >>> filter(f, range(2, 25))
     [5, 7, 11, 13, 17, 19, 23]

   `map(FUNCTION, SEQUENCE)' calls `FUNCTION(ITEM)' for each of the
sequence's items and returns a list of the return values.  For example,
to compute some cubes:

     >>> def cube(x): return x*x*x
     ...
     >>> map(cube, range(1, 11))
     [1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]

   More than one sequence may be passed; the function must then have as
many arguments as there are sequences and is called with the
corresponding item from each sequence (or `None' if some sequence is
shorter than another).  If `None' is passed for the function, a
function returning its argument(s) is substituted.

   Combining these two special cases, we see that `map(None, LIST1,
LIST2)' is a convenient way of turning a pair of lists into a list of
pairs.  For example:

     >>> seq = range(8)
     >>> def square(x): return x*x
     ...
     >>> map(None, seq, map(square, seq))
     [(0, 0), (1, 1), (2, 4), (3, 9), (4, 16), (5, 25), (6, 36), (7, 49)]

   `reduce(FUNC, SEQUENCE)' returns a single value constructed by
calling the binary function FUNC on the first two items of the
sequence, then on the result and the next item, and so on.  For
example, to compute the sum of the numbers 1 through 10:

     >>> def add(x,y): return x+y
     ...
     >>> reduce(add, range(1, 11))
     55

   If there's only one item in the sequence, its value is returned; if
the sequence is empty, an exception is raised.

   A third argument can be passed to indicate the starting value.  In
this case the starting value is returned for an empty sequence, and the
function is first applied to the starting value and the first sequence
item, then to the result and the next item, and so on.  For example,

     >>> def sum(seq):
     ...     def add(x,y): return x+y
     ...     return reduce(add, seq, 0)
     ...
     >>> sum(range(1, 11))
     55
     >>> sum([])
     0


File: python-tut.info,  Node: List Comprehensions,  Prev: Functional Programming Tools,  Up: More on Lists

List Comprehensions
-------------------

   List comprehensions provide a concise way to create lists without
resorting to use of `map()', `filter()' and/or `lambda'.  The resulting
list definition tends often to be clearer than lists built using those
constructs.  Each list comprehension consists of an expression
following by a `for' clause, then zero or more `for' or `if' clauses.
The result will be a list resulting from evaluating the expression in
the context of the `for' and `if' clauses which follow it.  If the
expression would evaluate to a tuple, it must be parenthesized.

     >>> freshfruit = ['  banana', '  loganberry ', 'passion fruit  ']
     >>> [weapon.strip() for weapon in freshfruit]
     ['banana', 'loganberry', 'passion fruit']
     >>> vec = [2, 4, 6]
     >>> [3*x for x in vec]
     [6, 12, 18]
     >>> [3*x for x in vec if x > 3]
     [12, 18]
     >>> [3*x for x in vec if x < 2]
     []
     >>> [{x: x**2} for x in vec]
     [{2: 4}, {4: 16}, {6: 36}]
     >>> [[x,x**2] for x in vec]
     [[2, 4], [4, 16], [6, 36]]
     >>> [x, x**2 for x in vec]	# error - parens required for tuples
       File "<stdin>", line 1
         [x, x**2 for x in vec]
                    ^
     SyntaxError: invalid syntax
     >>> [(x, x**2) for x in vec]
     [(2, 4), (4, 16), (6, 36)]
     >>> vec1 = [2, 4, 6]
     >>> vec2 = [4, 3, -9]
     >>> [x*y for x in vec1 for y in vec2]
     [8, 6, -18, 16, 12, -36, 24, 18, -54]
     >>> [x+y for x in vec1 for y in vec2]
     [6, 5, -7, 8, 7, -5, 10, 9, -3]


File: python-tut.info,  Node: del statement,  Next: Tuples and Sequences,  Prev: More on Lists,  Up: Data Structures

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

   There is a way to remove an item from a list given its index instead
of its value: the `del' statement.  This can also be used to remove
slices from a list (which we did earlier by assignment of an empty list
to the slice).  For example:

     >>> a
     [-1, 1, 66.6, 333, 333, 1234.5]
     >>> del a[0]
     >>> a
     [1, 66.6, 333, 333, 1234.5]
     >>> del a[2:4]
     >>> a
     [1, 66.6, 1234.5]

   `del' can also be used to delete entire variables:

     >>> del a

   Referencing the name `a' hereafter is an error (at least until
another value is assigned to it).  We'll find other uses for `del'
later.


File: python-tut.info,  Node: Tuples and Sequences,  Next: Dictionaries,  Prev: del statement,  Up: Data Structures

Tuples and Sequences
====================

   We saw that lists and strings have many common properties, e.g.,
indexing and slicing operations.  They are two examples of _sequence_
data types.  Since Python is an evolving language, other sequence data
types may be added.  There is also another standard sequence data type:
the _tuple_.

   A tuple consists of a number of values separated by commas, for
instance:

     >>> t = 12345, 54321, 'hello!'
     >>> t[0]
     12345
     >>> t
     (12345, 54321, 'hello!')
     >>> # Tuples may be nested:
     ... u = t, (1, 2, 3, 4, 5)
     >>> u
     ((12345, 54321, 'hello!'), (1, 2, 3, 4, 5))

   As you see, on output tuples are alway enclosed in parentheses, so
that nested tuples are interpreted correctly; they may be input with or
without surrounding parentheses, although often parentheses are
necessary anyway (if the tuple is part of a larger expression).

   Tuples have many uses, e.g., (x, y) coordinate pairs, employee
records from a database, etc.  Tuples, like strings, are immutable: it
is not possible to assign to the individual items of a tuple (you can
simulate much of the same effect with slicing and concatenation,
though).  It is also possible to create tuples which contain mutable
objects, such as lists.

   A special problem is the construction of tuples containing 0 or 1
items: the syntax has some extra quirks to accommodate these.  Empty
tuples are constructed by an empty pair of parentheses; a tuple with
one item is constructed by following a value with a comma (it is not
sufficient to enclose a single value in parentheses).  Ugly, but
effective.  For example:

     >>> empty = ()
     >>> singleton = 'hello',    # <-- note trailing comma
     >>> len(empty)
     0
     >>> len(singleton)
     1
     >>> singleton
     ('hello',)

   The statement `t = 12345, 54321, 'hello!'' is an example of _tuple
packing_: the values `12345', `54321' and `'hello!'' are packed
together in a tuple.  The reverse operation is also possible, e.g.:

     >>> x, y, z = t

   This is called, appropriately enough, _sequence unpacking_.
Sequence unpacking requires that the list of variables on the left have
the same number of elements as the length of the sequence.  Note that
multiple assignment is really just a combination of tuple packing and
sequence unpacking!

   There is a small bit of asymmetry here:  packing multiple values
always creates a tuple, and unpacking works for any sequence.


File: python-tut.info,  Node: Dictionaries,  Next: More on Conditions,  Prev: Tuples and Sequences,  Up: Data Structures

Dictionaries
============

   Another useful data type built into Python is the _dictionary_.
Dictionaries are sometimes found in other languages as "associative
memories" or "associative arrays".  Unlike sequences, which are indexed
by a range of numbers, dictionaries are indexed by _keys_, which can be
any immutable type; strings and numbers can always be keys.  Tuples can
be used as keys if they contain only strings, numbers, or tuples; if a
tuple contains any mutable object either directly or indirectly, it
cannot be used as a key.  You can't use lists as keys, since lists can
be modified in place using their `append()' and `extend()' methods, as
well as slice and indexed assignments.

   It is best to think of a dictionary as an unordered set of _key:
value_ pairs, with the requirement that the keys are unique (within one
dictionary).  A pair of braces creates an empty dictionary: `{}'.
Placing a comma-separated list of key:value pairs within the braces
adds initial key:value pairs to the dictionary; this is also the way
dictionaries are written on output.

   The main operations on a dictionary are storing a value with some key
and extracting the value given the key.  It is also possible to delete
a key:value pair with `del'.  If you store using a key that is already
in use, the old value associated with that key is forgotten.  It is an
error to extract a value using a non-existent key.

   The `keys()' method of a dictionary object returns a list of all the
keys used in the dictionary, in random order (if you want it sorted,
just apply the `sort()' method to the list of keys).  To check whether
a single key is in the dictionary, use the `has_key()' method of the
dictionary.

   Here is a small example using a dictionary:

     >>> tel = {'jack': 4098, 'sape': 4139}
     >>> tel['guido'] = 4127
     >>> tel
     {'sape': 4139, 'guido': 4127, 'jack': 4098}
     >>> tel['jack']
     4098
     >>> del tel['sape']
     >>> tel['irv'] = 4127
     >>> tel
     {'guido': 4127, 'irv': 4127, 'jack': 4098}
     >>> tel.keys()
     ['guido', 'irv', 'jack']
     >>> tel.has_key('guido')
     1


File: python-tut.info,  Node: More on Conditions,  Next: Comparing Sequences and Other Types,  Prev: Dictionaries,  Up: Data Structures

More on Conditions
==================

   The conditions used in `while' and `if' statements above can contain
other operators besides comparisons.

   The comparison operators `in' and `not in' check whether a value
occurs (does not occur) in a sequence.  The operators `is' and `is not'
compare whether two objects are really the same object; this only
matters for mutable objects like lists.  All comparison operators have
the same priority, which is lower than that of all numerical operators.

   Comparisons can be chained: e.g., `a < b == c' tests whether `a' is
less than `b' and moreover `b' equals `c'.

   Comparisons may be combined by the Boolean operators `and' and `or',
and the outcome of a comparison (or of any other Boolean expression)
may be negated with `not'.  These all have lower priorities than
comparison operators again; between them, `not' has the highest
priority, and `or' the lowest, so that `A and not B or C' is equivalent
to `(A and (not B)) or C'.  Of course, parentheses can be used to
express the desired composition.

   The Boolean operators `and' and `or' are so-called _shortcut_
operators: their arguments are evaluated from left to right, and
evaluation stops as soon as the outcome is determined.  E.g., if `A'
and `C' are true but `B' is false, `A and B and C' does not evaluate
the expression C.  In general, the return value of a shortcut operator,
when used as a general value and not as a Boolean, is the last
evaluated argument.

   It is possible to assign the result of a comparison or other Boolean
expression to a variable.  For example,

     >>> string1, string2, string3 = '', 'Trondheim', 'Hammer Dance'
     >>> non_null = string1 or string2 or string3
     >>> non_null
     'Trondheim'

   Note that in Python, unlike C, assignment cannot occur inside
expressions.  C programmers may grumble about this, but it avoids a
common class of problems encountered in C programs: typing `=' in an
expression when `==' was intended.


File: python-tut.info,  Node: Comparing Sequences and Other Types,  Prev: More on Conditions,  Up: Data Structures

Comparing Sequences and Other Types
===================================

   Sequence objects may be compared to other objects with the same
sequence type.  The comparison uses _lexicographical_ ordering: first
the first two items are compared, and if they differ this determines
the outcome of the comparison; if they are equal, the next two items
are compared, and so on, until either sequence is exhausted.  If two
items to be compared are themselves sequences of the same type, the
lexicographical comparison is carried out recursively.  If all items of
two sequences compare equal, the sequences are considered equal.  If
one sequence is an initial sub-sequence of the other, the shorter
sequence is the smaller one.  Lexicographical ordering for strings uses
the ASCII ordering for individual characters.  Some examples of
comparisons between sequences with the same types:

     (1, 2, 3)              < (1, 2, 4)
     [1, 2, 3]              < [1, 2, 4]
     'ABC' < 'C' < 'Pascal' < 'Python'
     (1, 2, 3, 4)           < (1, 2, 4)
     (1, 2)                 < (1, 2, -1)
     (1, 2, 3)             == (1.0, 2.0, 3.0)
     (1, 2, ('aa', 'ab'))   < (1, 2, ('abc', 'a'), 4)

   Note that comparing objects of different types is legal.  The outcome
is deterministic but arbitrary: the types are ordered by their name.
Thus, a list is always smaller than a string, a string is always
smaller than a tuple, etc.  Mixed numeric types are compared according
to their numeric value, so 0 equals 0.0, etc.(1)

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

   (1)  The rules for comparing objects of different types should not
be relied upon; they may change in a future version of the language.


File: python-tut.info,  Node: Modules,  Next: Input and Output,  Prev: Data Structures,  Up: Top

Modules
*******

   If you quit from the Python interpreter and enter it again, the
definitions you have made (functions and variables) are lost.
Therefore, if you want to write a somewhat longer program, you are
better off using a text editor to prepare the input for the interpreter
and running it with that file as input instead.  This is known as
creating a _script_.  As your program gets longer, you may want to
split it into several files for easier maintenance.  You may also want
to use a handy function that you've written in several programs without
copying its definition into each program.

   To support this, Python has a way to put definitions in a file and
use them in a script or in an interactive instance of the interpreter.
Such a file is called a _module_; definitions from a module can be
_imported_ into other modules or into the _main_ module (the collection
of variables that you have access to in a script executed at the top
level and in calculator mode).

   A module is a file containing Python definitions and statements.  The
file name is the module name with the suffix `.py' appended.  Within a
module, the module's name (as a string) is available as the value of
the global variable `__name__'.  For instance, use your favorite text
editor to create a file called `fibo.py' in the current directory with
the following contents:

     # Fibonacci numbers module
     
     def fib(n):    # write Fibonacci series up to n
         a, b = 0, 1
         while b < n:
             print b,
             a, b = b, a+b
     
     def fib2(n): # return Fibonacci series up to n
         result = []
         a, b = 0, 1
         while b < n:
             result.append(b)
             a, b = b, a+b
         return result

   Now enter the Python interpreter and import this module with the
following command:

     >>> import fibo

   This does not enter the names of the functions defined in `fibo'
directly in the current symbol table; it only enters the module name
`fibo' there.  Using the module name you can access the functions:

     >>> fibo.fib(1000)
     1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987
     >>> fibo.fib2(100)
     [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
     >>> fibo.__name__
     'fibo'

   If you intend to use a function often you can assign it to a local
name:

     >>> fib = fibo.fib
     >>> fib(500)
     1 1 2 3 5 8 13 21 34 55 89 144 233 377

* Menu:

* More on Modules::
* Standard Modules::
* dir Function::
* Packages::


File: python-tut.info,  Node: More on Modules,  Next: Standard Modules,  Prev: Modules,  Up: Modules

More on Modules
===============

   A module can contain executable statements as well as function
definitions.  These statements are intended to initialize the module.
They are executed only the _first_ time the module is imported
somewhere.(1)

   Each module has its own private symbol table, which is used as the
global symbol table by all functions defined in the module.  Thus, the
author of a module can use global variables in the module without
worrying about accidental clashes with a user's global variables.  On
the other hand, if you know what you are doing you can touch a module's
global variables with the same notation used to refer to its functions,
`modname.itemname'.

   Modules can import other modules.  It is customary but not required
to place all `import' statements at the beginning of a module (or
script, for that matter).  The imported module names are placed in the
importing module's global symbol table.

   There is a variant of the `import' statement that imports names from
a module directly into the importing module's symbol table.  For
example:

     >>> from fibo import fib, fib2
     >>> fib(500)
     1 1 2 3 5 8 13 21 34 55 89 144 233 377

   This does not introduce the module name from which the imports are
taken in the local symbol table (so in the example, `fibo' is not
defined).

   There is even a variant to import all names that a module defines:

     >>> from fibo import *
     >>> fib(500)
     1 1 2 3 5 8 13 21 34 55 89 144 233 377

   This imports all names except those beginning with an underscore
(`_').

* Menu:

* Module Search Path::
* Compiled Python files::

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

   (1)  In fact function definitions are also `statements' that are
`executed'; the execution enters the function name in the module's
global symbol table.


File: python-tut.info,  Node: Module Search Path,  Next: Compiled Python files,  Prev: More on Modules,  Up: More on Modules

The Module Search Path
----------------------

   When a module named `spam' is imported, the interpreter searches for
a file named `spam.py' in the current directory, and then in the list
of directories specified by the environment variable `PYTHONPATH'.
This has the same syntax as the shell variable `PATH', i.e., a list of
directory names.  When `PYTHONPATH' is not set, or when the file is not
found there, the search continues in an installation-dependent default
path; on UNIX, this is usually `.:/usr/local/lib/python'.

   Actually, modules are searched in the list of directories given by
the variable `sys.path' which is initialized from the directory
containing the input script (or the current directory), `PYTHONPATH'
and the installation-dependent default.  This allows Python programs
that know what they're doing to modify or replace the module search
path.  See the section on Standard Modules later.


File: python-tut.info,  Node: Compiled Python files,  Prev: Module Search Path,  Up: More on Modules

"Compiled" Python files
-----------------------

   As an important speed-up of the start-up time for short programs that
use a lot of standard modules, if a file called `spam.pyc' exists in
the directory where `spam.py' is found, this is assumed to contain an
already-"byte-compiled" version of the module `spam'.  The modification
time of the version of `spam.py' used to create `spam.pyc' is recorded
in `spam.pyc', and the `.pyc' file is ignored if these don't match.

   Normally, you don't need to do anything to create the `spam.pyc'
file.  Whenever `spam.py' is successfully compiled, an attempt is made
to write the compiled version to `spam.pyc'.  It is not an error if
this attempt fails; if for any reason the file is not written
completely, the resulting `spam.pyc' file will be recognized as invalid
and thus ignored later.  The contents of the `spam.pyc' file are
platform independent, so a Python module directory can be shared by
machines of different architectures.

   Some tips for experts:

   * When the Python interpreter is invoked with the `-O' flag,
     optimized code is generated and stored in `.pyo' files.  The
     optimizer currently doesn't help much; it only removes `assert'
     statements and `SET_LINENO' instructions.  When `-O' is used,
     _all_ bytecode is optimized; `.pyc' files are ignored and `.py'
     files are compiled to optimized bytecode.

   * Passing two `-O' flags to the Python interpreter (`-OO') will
     cause the bytecode compiler to perform optimizations that could in
     some rare cases result in malfunctioning programs.  Currently only
     `__doc__' strings are removed from the bytecode, resulting in more
     compact `.pyo' files.  Since some programs may rely on having
     these available, you should only use this option if you know what
     you're doing.

   * A program doesn't run any faster when it is read from a `.pyc' or
     `.pyo' file than when it is read from a `.py' file; the only thing
     that's faster about `.pyc' or `.pyo' files is the speed with which
     they are loaded.

   * When a script is run by giving its name on the command line, the
     bytecode for the script is never written to a `.pyc' or `.pyo'
     file.  Thus, the startup time of a script may be reduced by moving
     most of its code to a module and having a small bootstrap script
     that imports that module.  It is also possible to name a `.pyc' or
     `.pyo' file directly on the command line.

   * It is possible to have a file called `spam.pyc' (or `spam.pyo'
     when `-O' is used) without a file `spam.py' for the same module.
     This can be used to distribute a library of Python code in a form
     that is moderately hard to reverse engineer.

   * The module `compileall' can create `.pyc' files (or `.pyo' files
     when `-O' is used) for all modules in a directory.



File: python-tut.info,  Node: Standard Modules,  Next: dir Function,  Prev: More on Modules,  Up: Modules

Standard Modules
================

   Python comes with a library of standard modules, described in a
separate document, the ("Library Reference" hereafter).  Some modules
are built into the interpreter; these provide access to operations that
are not part of the core of the language but are nevertheless built in,
either for efficiency or to provide access to operating system
primitives such as system calls. The set of such modules is a
configuration option; e.g., the `amoeba' module is only provided on
systems that somehow support Amoeba primitives.  One particular module
deserves some attention: `sys', which is built into every Python
interpreter.  The variables `sys.ps1' and `sys.ps2' define the strings
used as primary and secondary prompts:

     >>> import sys
     >>> sys.ps1
     '>>> '
     >>> sys.ps2
     '... '
     >>> sys.ps1 = 'C> '
     C> print 'Yuck!'
     Yuck!
     C>

   These two variables are only defined if the interpreter is in
interactive mode.

   The variable `sys.path' is a list of strings that determine the
interpreter's search path for modules. It is initialized to a default
path taken from the environment variable `PYTHONPATH', or from a
built-in default if `PYTHONPATH' is not set.  You can modify it using
standard list operations, e.g.:

     >>> import sys
     >>> sys.path.append('/ufs/guido/lib/python')


File: python-tut.info,  Node: dir Function,  Next: Packages,  Prev: Standard Modules,  Up: Modules

The `dir()' Function
====================

   The built-in function `dir()' is used to find out which names a
module defines.  It returns a sorted list of strings:

     >>> import fibo, sys
     >>> dir(fibo)
     ['__name__', 'fib', 'fib2']
     >>> dir(sys)
     ['__name__', 'argv', 'builtin_module_names', 'copyright', 'exit',
     'maxint', 'modules', 'path', 'ps1', 'ps2', 'setprofile', 'settrace',
     'stderr', 'stdin', 'stdout', 'version']

   Without arguments, `dir()' lists the names you have defined
currently:

     >>> a = [1, 2, 3, 4, 5]
     >>> import fibo, sys
     >>> fib = fibo.fib
     >>> dir()
     ['__name__', 'a', 'fib', 'fibo', 'sys']

   Note that it lists all types of names: variables, modules,
functions, etc.

   `dir()' does not list the names of built-in functions and variables.
If you want a list of those, they are defined in the standard module
`__builtin__':

     >>> import __builtin__
     >>> dir(__builtin__)
     ['AccessError', 'AttributeError', 'ConflictError', 'EOFError', 'IOError',
     'ImportError', 'IndexError', 'KeyError', 'KeyboardInterrupt',
     'MemoryError', 'NameError', 'None', 'OverflowError', 'RuntimeError',
     'SyntaxError', 'SystemError', 'SystemExit', 'TypeError', 'ValueError',
     'ZeroDivisionError', '__name__', 'abs', 'apply', 'chr', 'cmp', 'coerce',
     'compile', 'dir', 'divmod', 'eval', 'execfile', 'filter', 'float',
     'getattr', 'hasattr', 'hash', 'hex', 'id', 'input', 'int', 'len', 'long',
     'map', 'max', 'min', 'oct', 'open', 'ord', 'pow', 'range', 'raw_input',
     'reduce', 'reload', 'repr', 'round', 'setattr', 'str', 'type', 'xrange']


File: python-tut.info,  Node: Packages,  Prev: dir Function,  Up: Modules

Packages
========

   Packages are a way of structuring Python's module namespace by using
"dotted module names".  For example, the module name `A.B' designates a
submodule named `B' in a package named `A'.  Just like the use of
modules saves the authors of different modules from having to worry
about each other's global variable names, the use of dotted module
names saves the authors of multi-module packages like NumPy or the
Python Imaging Library from having to worry about each other's module
names.

   Suppose you want to design a collection of modules (a "package") for
the uniform handling of sound files and sound data.  There are many
different sound file formats (usually recognized by their extension,
e.g. `.wav', `.aiff', `.au'), so you may need to create and maintain a
growing collection of modules for the conversion between the various
file formats.  There are also many different operations you might want
to perform on sound data (e.g. mixing, adding echo, applying an
equalizer function, creating an artificial stereo effect), so in
addition you will be writing a never-ending stream of modules to
perform these operations.  Here's a possible structure for your package
(expressed in terms of a hierarchical filesystem):

     Sound/                          Top-level package
           __init__.py               Initialize the sound package
           Formats/                  Subpackage for file format conversions
                   __init__.py
                   wavread.py
                   wavwrite.py
                   aiffread.py
                   aiffwrite.py
                   auread.py
                   auwrite.py
                   ...
           Effects/                  Subpackage for sound effects
                   __init__.py
                   echo.py
                   surround.py
                   reverse.py
                   ...
           Filters/                  Subpackage for filters
                   __init__.py
                   equalizer.py
                   vocoder.py
                   karaoke.py
                   ...

   The `__init__.py' files are required to make Python treat the
directories as containing packages; this is done to prevent directories
with a common name, such as `string', from unintentionally hiding valid
modules that occur later on the module search path. In the simplest
case, `__init__.py' can just be an empty file, but it can also execute
initialization code for the package or set the `__all__' variable,
described later.

   Users of the package can import individual modules from the package,
for example:

     import Sound.Effects.echo

   This loads the submodule `Sound.Effects.echo'.  It must be referenced
with its full name, e.g.

     Sound.Effects.echo.echofilter(input, output, delay=0.7, atten=4)

   An alternative way of importing the submodule is:

     from Sound.Effects import echo

   This also loads the submodule `echo', and makes it available without
its package prefix, so it can be used as follows:

     echo.echofilter(input, output, delay=0.7, atten=4)

   Yet another variation is to import the desired function or variable
directly:

     from Sound.Effects.echo import echofilter

   Again, this loads the submodule `echo', but this makes its function
`echofilter()' directly available:

     echofilter(input, output, delay=0.7, atten=4)

   Note that when using `from PACKAGE import ITEM', the item can be
either a submodule (or subpackage) of the package, or some other name
defined in the package, like a function, class or variable.  The
`import' statement first tests whether the item is defined in the
package; if not, it assumes it is a module and attempts to load it.  If
it fails to find it, an `ImportError' exception is raised.

   Contrarily, when using syntax like `import ITEM.SUBITEM.SUBSUBITEM',
each item except for the last must be a package; the last item can be a
module or a package but can't be a class or function or variable
defined in the previous item.

* Menu:

* Importing * From a Package::
* Intra-package References::

