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

   April 15, 2001		2.1


File: python-lib.info,  Node: gc,  Next: weakref,  Prev: sys,  Up: Python Runtime Services

Garbage Collector interface
===========================

   Interface to the cycle-detecting garbage collector.  This module was
documented by Neil Schemenauer <nas@arctrix.com>.
This section was written by Neil Schemenauer <nas@arctrix.com>.
The `gc' module is only available if the interpreter was built with the
optional cyclic garbage detector (enabled by default).  If this was not
enabled, an `ImportError' is raised by attempts to import this module.

   This module provides an interface to the optional garbage collector.
It provides the ability to disable the collector, tune the collection
frequency, and set debugging options.  It also provides access to
unreachable objects that the collector found but cannot free.  Since the
collector supplements the reference counting already used in Python, you
can disable the collector if you are sure your program does not create
reference cycles.  Automatic collection can be disabled by calling
`gc.disable()'.  To debug a leaking program call
`gc.set_debug(gc.DEBUG_LEAK)'.

   The `gc' module provides the following functions:

`enable()'
     Enable automatic garbage collection.

`disable()'
     Disable automatic garbage collection.

`isenabled()'
     Returns true if automatic collection is enabled.

`collect()'
     Run a full collection.  All generations are examined and the
     number of unreachable objects found is returned.

`set_debug(flags)'
     Set the garbage collection debugging flags.  Debugging information
     will be written to `sys.stderr'.  See below for a list of
     debugging flags which can be combined using bit operations to
     control debugging.

`get_debug()'
     Return the debugging flags currently set.

`set_threshold(threshold0[, threshold1[, threshold2]])'
     Set the garbage collection thresholds (the collection frequency).
     Setting THRESHOLD0 to zero disables collection.

     The GC classifies objects into three generations depending on how
     many collection sweeps they have survived.  New objects are placed
     in the youngest generation (generation `0').  If an object
     survives a collection it is moved into the next older generation.
     Since generation `2' is the oldest generation, objects in that
     generation remain there after a collection.  In order to decide
     when to run, the collector keeps track of the number object
     allocations and deallocations since the last collection.  When the
     number of allocations minus the number of deallocations exceeds
     THRESHOLD0, collection starts.  Initially only generation `0' is
     examined.  If generation `0' has been examined more than
     THRESHOLD1 times since generation `1' has been examined, then
     generation `1' is examined as well.  Similarly, THRESHOLD2
     controls the number of collections of generation `1' before
     collecting generation `2'.

`get_threshold()'
     Return the current collection thresholds as a tuple of
     `(THRESHOLD0, THRESHOLD1, THRESHOLD2)'.

   The following variable is provided for read-only access:

`garbage'
     A list of objects which the collector found to be unreachable but
     could not be freed (uncollectable objects).  Objects that have
     `__del__()' methods and create part of a reference cycle cause the
     entire reference cycle to be uncollectable.  If `DEBUG_SAVEALL' is
     set, then all unreachable objects will be added to this list
     rather than freed.

   The following constants are provided for use with `set_debug()':

`DEBUG_STATS'
     Print statistics during collection.  This information can be
     useful when tuning the collection frequency.

`DEBUG_COLLECTABLE'
     Print information on collectable objects found.

`DEBUG_UNCOLLECTABLE'
     Print information of uncollectable objects found (objects which are
     not reachable but cannot be freed by the collector).  These objects
     will be added to the `garbage' list.

`DEBUG_INSTANCES'
     When `DEBUG_COLLECTABLE' or `DEBUG_UNCOLLECTABLE' is set, print
     information about instance objects found.

`DEBUG_OBJECTS'
     When `DEBUG_COLLECTABLE' or `DEBUG_UNCOLLECTABLE' is set, print
     information about objects other than instance objects found.

`DEBUG_SAVEALL'
     When set, all unreachable objects found will be appended to
     GARBAGE rather than being freed.  This can be useful for debugging
     a leaking program.

`DEBUG_LEAK'
     The debugging flags necessary for the collector to print
     information about a leaking program (equal to `DEBUG_COLLECTABLE |
     DEBUG_UNCOLLECTABLE | DEBUG_INSTANCES | DEBUG_OBJECTS |
     DEBUG_SAVEALL').


File: python-lib.info,  Node: weakref,  Next: fpectl,  Prev: gc,  Up: Python Runtime Services

Weak references
===============

   Support for weak references and weak dictionaries.  This module was
documented by Fred L. Drake, Jr. <fdrake@acm.org>.
This module was documented by Neil Schemenauer <nas@arctrix.com>.
This module was documented by Martin von L"owis
<martin@loewis.home.cs.tu-berlin.de>.
This section was written by Fred L. Drake, Jr. <fdrake@acm.org>.
_Added in Python version 2.1_

   The `weakref' module allows the Python programmer to create "weak
references" to objects.

   XXX -- need to say more here!

   Not all objects can be weakly referenced; those objects which do
include class instances, functions written in Python (but not in C),
and methods (both bound and unbound).  Extension types can easily be
made to support weak references; see section *Note fpectl::, "Weak
References in Extension Types," for more information.

`ref(object[, callback])'
     Return a weak reference to OBJECT.  If CALLBACK is provided, it
     will be called when the object is about to be finalized; the weak
     reference object will be passed as the only parameter to the
     callback; the referent will no longer be available.  The original
     object can be retrieved by calling the reference object, if the
     referent is still alive.

     It is allowable for many weak references to be constructed for the
     same object.  Callbacks registered for each weak reference will be
     called from the most recently registered callback to the oldest
     registered callback.

     Exceptions raised by the callback will be noted on the standard
     error output, but cannot be propagated; they are handled in exactly
     the same way as exceptions raised from an object's `__del__()'
     method.

     Weak references are hashable if the OBJECT is hashable.  They will
     maintain their hash value even after the OBJECT was deleted.  If
     `hash()' is called the first time only after the OBJECT was
     deleted, the call will raise `TypeError'.

     Weak references support test for equality, but not ordering.  If
     the OBJECT is still alive, to references are equal if the objects
     are equal (regardless of the CALLBACK).  If the OBJECT has been
     deleted, they are equal iff they are identical.

`proxy(object[, callback])'
     Return a proxy to OBJECT which uses a weak reference.  This
     supports use of the proxy in most contexts instead of requiring the
     explicit dereferencing used with weak reference objects.  The
     returned object will have a type of either `ProxyType' or
     `CallableProxyType', depending on whether OBJECT is callable.
     Proxy objects are not hashable regardless of the referent; this
     avoids a number of problems related to their fundamentally mutable
     nature, and prevent their use as dictionary keys.  CALLABLE is the
     same as the parameter of the same name to the `ref()' function.

`getweakrefcount(object)'
     Return the number of weak references and proxies which refer to
     OBJECT.

`getweakrefs(object)'
     Return a list of all weak reference and proxy objects which refer
     to OBJECT.

`WeakKeyDictionary([dict])'
     Mapping class that references keys weakly.  Entries in the
     dictionary will be discarded when there is no longer a strong
     reference to the key.  This can be used to associate additional
     data with an object owned by other parts of an application without
     adding attributes to those objects.  This can be especially useful
     with objects that override attribute accesses.

`WeakValueDictionary([dict])'
     Mapping class that references values weakly.  Entries in the
     dictionary will be discarded when no strong reference to the value
     exists anymore.

`ReferenceType'
     The type object for weak references objects.

`ProxyType'
     The type object for proxies of objects which are not callable.

`CallableProxyType'
     The type object for proxies of callable objects.

`ProxyTypes'
     Sequence containing all the type objects for proxies.  This can
     make it simpler to test if an object is a proxy without being
     dependent on naming both proxy types.

`ReferenceError'
     Exception raised when a proxy object is used but the underlying
     object has been collected.

   See also:

*PEP0205 Weak References*
     The proposal and rationale for this feature, including links to
     earlier implementations and information about similar features in
     other languages.

* Menu:

* Weak Reference Objects::
* Example::
* Weak References in Extension Types::


File: python-lib.info,  Node: Weak Reference Objects,  Next: Example,  Prev: weakref,  Up: weakref

Weak Reference Objects
----------------------

   Weak reference objects have no attributes or methods, but do allow
the referent to be obtained, if it still exists, by calling it:

     >>> import weakref
     >>> class Object:
     ...     pass
     ...
     >>> o = Object()
     >>> r = weakref.ref(o)
     >>> o2 = r()
     >>> o is o2
     1

   If the referent no longer exists, calling the reference object
returns `None':

     >>> del o, o2
     >>> print r()
     None

   Testing that a weak reference object is still live should be done
using the expression `REF.get() is not None'.  Normally, application
code that needs to use a reference object should follow this pattern:

     o = ref.get()
     if o is None:
         # referent has been garbage collected
         print "Object has been allocated; can't frobnicate."
     else:
         print "Object is still live!"
         o.do_something_useful()

   Using a separate test for "liveness" creates race conditions in
threaded applications; another thread can cause a weak reference to
become invalidated before the `get()' method is called; the idiom shown
above is safe in threaded applications as well as single-threaded
applications.


File: python-lib.info,  Node: Example,  Next: Weak References in Extension Types,  Prev: Weak Reference Objects,  Up: weakref

Example
-------

   This simple example shows how an application can use objects IDs to
retrieve objects that it has seen before.  The IDs of the objects can
then be used in other data structures without forcing the objects to
remain alive, but the objects can still be retrieved by ID if they do.

     import weakref
     
     _id2obj_dict = weakref.WeakValueDictionary()
     
     def remember(obj):
         _id2obj_dict[id(obj)] = obj
     
     def id2obj(id):
         return _id2obj_dict.get(id)


File: python-lib.info,  Node: Weak References in Extension Types,  Prev: Example,  Up: weakref

Weak References in Extension Types
----------------------------------

   One of the goals of the implementation is to allow any type to
participate in the weak reference mechanism without incurring the
overhead on those objects which do not benefit by weak referencing
(such as numbers).

   For an object to be weakly referencable, the extension must include a
`PyObject *' field in the instance structure for the use of the weak
reference mechanism; it must be initialized to `NULL' by the object's
constructor.  It must also set the `tp_weaklistoffset' field of the
corresponding type object to the offset of the field.  For example, the
instance type is defined with the following structure:

     typedef struct {
         PyObject_HEAD
         PyClassObject *in_class;       /* The class object */
         PyObject      *in_dict;        /* A dictionary */
         PyObject      *in_weakreflist; /* List of weak references */
     } PyInstanceObject;

   The statically-declared type object for instances is defined this
way:

     PyTypeObject PyInstance_Type = {
         PyObject_HEAD_INIT(&PyType_Type)
         0,
         "instance",
     
         /* lots of stuff omitted for brevity */
     
         offsetof(PyInstanceObject, in_weakreflist) /* tp_weaklistoffset */
     };

   The only further addition is that the destructor needs to call the
weak reference manager to clear any weak references and return if the
object has been resurrected.  This needs to occur before any other
parts of the destruction have occurred:

     static void
     instance_dealloc(PyInstanceObject *inst)
     {
         /* allocate tempories if needed, but do not begin
            destruction here
          */
     
         if (!PyObject_ClearWeakRefs((PyObject *) inst))
             return;
     
         /* proceed with object destuction normally */
     }


File: python-lib.info,  Node: fpectl,  Next: atexit,  Prev: weakref,  Up: Python Runtime Services

Floating point exception control
================================

   This module was documented by Lee Busby <busby1@llnl.gov>.
This section was written by Lee Busby <busby1@llnl.gov>.
Provide control for floating point exception handling.

   Most computers carry out floating point operationsin conformance
with the so-called IEEE-754 standard.  On any real computer, some
floating point operations produce results that cannot be expressed as a
normal floating point value.  For example, try

     >>> import math
     >>> math.exp(1000)
     inf
     >>> math.exp(1000)/math.exp(1000)
     nan

   (The example above will work on many platforms.  DEC Alpha may be
one exception.)  "Inf" is a special, non-numeric value in IEEE-754 that
stands for "infinity", and "nan" means "not a number."  Note that,
other than the non-numeric results, nothing special happened when you
asked Python to carry out those calculations.  That is in fact the
default behaviour prescribed in the IEEE-754 standard, and if it works
for you, stop reading now.

   In some circumstances, it would be better to raise an exception and
stop processing at the point where the faulty operation was attempted.
The `fpectl' module is for use in that situation.  It provides control
over floating point units from several hardware manufacturers, allowing
the user to turn on the generation of `SIGFPE' whenever any of the
IEEE-754 exceptions Division by Zero, Overflow, or Invalid Operation
occurs.  In tandem with a pair of wrapper macros that are inserted into
the C code comprising your python system, `SIGFPE' is trapped and
converted into the Python `FloatingPointError' exception.

   The `fpectl' module defines the following functions and may raise
the given exception:

`turnon_sigfpe()'
     Turn on the generation of `SIGFPE', and set up an appropriate
     signal handler.

`turnoff_sigfpe()'
     Reset default handling of floating point exceptions.

`FloatingPointError'
     After `turnon_sigfpe()' has been executed, a floating point
     operation that raises one of the IEEE-754 exceptions Division by
     Zero, Overflow, or Invalid operation will in turn raise this
     standard Python exception.

* Menu:

* Example 2::
* Limitations and other considerations::


File: python-lib.info,  Node: Example 2,  Next: Limitations and other considerations,  Prev: fpectl,  Up: fpectl

Example
-------

   The following example demonstrates how to start up and test
operation of the `fpectl' module.

     >>> import fpectl
     >>> import fpetest
     >>> fpectl.turnon_sigfpe()
     >>> fpetest.test()
     overflow        PASS
     FloatingPointError: Overflow
     
     div by 0        PASS
     FloatingPointError: Division by zero
       [ more output from test elided ]
     >>> import math
     >>> math.exp(1000)
     Traceback (most recent call last):
       File "<stdin>", line 1, in ?
     FloatingPointError: in math_1


File: python-lib.info,  Node: Limitations and other considerations,  Prev: Example 2,  Up: fpectl

Limitations and other considerations
------------------------------------

   Setting up a given processor to trap IEEE-754 floating point errors
currently requires custom code on a per-architecture basis.  You may
have to modify `fpectl' to control your particular hardware.

   Conversion of an IEEE-754 exception to a Python exception requires
that the wrapper macros `PyFPE_START_PROTECT' and `PyFPE_END_PROTECT'
be inserted into your code in an appropriate fashion.  Python itself
has been modified to support the `fpectl' module, but many other codes
of interest to numerical analysts have not.

   The `fpectl' module is not thread-safe.

   See also:

   Some files in the source distribution may be interesting in learning
more about how this module operates. The include file `Include/pyfpe.h'
discusses the implementation of this module at some length.
`Modules/fpetestmodule.c' gives several examples of use. Many
additional examples can be found in `Objects/floatobject.c'.


File: python-lib.info,  Node: atexit,  Next: types,  Prev: fpectl,  Up: Python Runtime Services

Exit handlers
=============

   This module was documented by Skip Montanaro <skip@mojam.com>.
This section was written by Skip Montanaro <skip@mojam.com>.
Register and execute cleanup functions.

   _Added in Python version 2.0_

   The `atexit' module defines a single function to register cleanup
functions.  Functions thus registered are automatically executed upon
normal interpreter termination.

   Note: the functions registered via this module are not called when
the program is killed by a signal, when a Python fatal internal error
is detected, or when `os._exit()' is called.

   This is an alternate interface to the functionality provided by the
`sys.exitfunc' variable.

   Note: This module is unlikely to work correctly when used with other
code that sets `sys.exitfunc'.  In particular, other core Python
modules are free to use `atexit' without the programmer's knowledge.
Authors who use `sys.exitfunc' should convert their code to use
`atexit' instead.  The simplest way to convert code that sets
`sys.exitfunc' is to import `atexit' and register the function that had
been bound to `sys.exitfunc'.

`register(func[, *args[, **kargs]])'
     Register FUNC as a function to be executed at termination.  Any
     optional arguments that are to be passed to FUNC must be passed as
     arguments to `register()'.

     At normal program termination (for instance, if `sys.exit()' is
     called or the main module's execution completes), all functions
     registered are called in last in, first out order.  The assumption
     is that lower level modules will normally be imported before
     higher level modules and thus must be cleaned up later.

   See also:

   *Note readline:: Useful example of `atexit' to read and write
`readline' history files.

* Menu:

* atexit Example::


File: python-lib.info,  Node: atexit Example,  Prev: atexit,  Up: atexit

`atexit' Example
----------------

   The following simple example demonstrates how a module can initialize
a counter from a file when it is imported and save the counter's
updated value automatically when the program terminates without relying
on the application making an explicit call into this module at
termination.

     try:
         _count = int(open("/tmp/counter").read())
     except IOError:
         _count = 0
     
     def incrcounter(n):
         global _count
         _count = _count + n
     
     def savecounter():
         open("/tmp/counter", "w").write("%d" % _count)
     
     import atexit
     atexit.register(savecounter)


File: python-lib.info,  Node: types,  Next: UserDict,  Prev: atexit,  Up: Python Runtime Services

Names for all built-in types
============================

   Names for all built-in types.

   This module defines names for all object types that are used by the
standard Python interpreter, but not for the types defined by various
extension modules.  It is safe to use `from types import *' -- the
module does not export any names besides the ones listed here.  New
names exported by future versions of this module will all end in `Type'.

   Typical use is for functions that do different things depending on
their argument types, like the following:

     from types import *
     def delete(list, item):
         if type(item) is IntType:
            del list[item]
         else:
            list.remove(item)

   The module defines the following names:

`NoneType'
     The type of `None'.

`TypeType'
     The type of type objects (such as returned by `type()').

`IntType'
     The type of integers (e.g. `1').

`LongType'
     The type of long integers (e.g. `1L').

`FloatType'
     The type of floating point numbers (e.g. `1.0').

`ComplexType'
     The type of complex numbers (e.g. `1.0j').

`StringType'
     The type of character strings (e.g. `'Spam'').

`UnicodeType'
     The type of Unicode character strings (e.g. `u'Spam'').

`TupleType'
     The type of tuples (e.g. `(1, 2, 3, 'Spam')').

`ListType'
     The type of lists (e.g. `[0, 1, 2, 3]').

`DictType'
     The type of dictionaries (e.g. `{'Bacon': 1, 'Ham': 0}').

`DictionaryType'
     An alternate name for `DictType'.

`FunctionType'
     The type of user-defined functions and lambdas.

`LambdaType'
     An alternate name for `FunctionType'.

`CodeType'
     The type for code objects such as returned by `compile()'.

`ClassType'
     The type of user-defined classes.

`InstanceType'
     The type of instances of user-defined classes.

`MethodType'
     The type of methods of user-defined class instances.

`UnboundMethodType'
     An alternate name for `MethodType'.

`BuiltinFunctionType'
     The type of built-in functions like `len()' or `sys.exit()'.

`BuiltinMethodType'
     An alternate name for `BuiltinFunction'.

`ModuleType'
     The type of modules.

`FileType'
     The type of open file objects such as `sys.stdout'.

`XRangeType'
     The type of range objects returned by `xrange()'.

`SliceType'
     The type of objects returned by `slice()'.

`EllipsisType'
     The type of `Ellipsis'.

`TracebackType'
     The type of traceback objects such as found in `sys.exc_traceback'.

`FrameType'
     The type of frame objects such as found in `tb.tb_frame' if `tb'
     is a traceback object.

`BufferType'
     The type of buffer objects created by the `buffer()' function.


File: python-lib.info,  Node: UserDict,  Next: UserList,  Prev: types,  Up: Python Runtime Services

Class wrapper for dictionary objects
====================================

   Class wrapper for dictionary objects.

   This module defines a class that acts as a wrapper around dictionary
objects.  It is a useful base class for your own dictionary-like
classes, which can inherit from them and override existing methods or
add new ones.  In this way one can add new behaviors to dictionaries.

   The `UserDict' module defines the `UserDict' class:

`UserDict([initialdata])'
     Class that simulates a dictionary.  The instance's contents are
     kept in a regular dictionary, which is accessible via the `data'
     attribute of `UserDict' instances.  If INITIALDATA is provided,
     `data' is initialized with its contents; note that a reference to
     INITIALDATA will not be kept, allowing it be used used for other
     purposes.

   In addition to supporting the methods and operations of mappings (see
section *Note Mapping Types::), `UserDict' instances provide the
following attribute:

`data'
     A real dictionary used to store the contents of the `UserDict'
     class.


File: python-lib.info,  Node: UserList,  Next: UserString,  Prev: UserDict,  Up: Python Runtime Services

Class wrapper for list objects
==============================

   Class wrapper for list objects.

   This module defines a class that acts as a wrapper around list
objects.  It is a useful base class for your own list-like classes,
which can inherit from them and override existing methods or add new
ones.  In this way one can add new behaviors to lists.

   The `UserList' module defines the `UserList' class:

`UserList([list])'
     Class that simulates a list.  The instance's contents are kept in
     a regular list, which is accessible via the `data' attribute of
     `UserList' instances.  The instance's contents are initially set
     to a copy of LIST, defaulting to the empty list `[]'.  LIST can be
     either a regular Python list, or an instance of `UserList' (or a
     subclass).

   In addition to supporting the methods and operations of mutable
sequences (see section *Note Sequence Types::), `UserList' instances
provide the following attribute:

`data'
     A real Python list object used to store the contents of the
     `UserList' class.

   *Subclassing requirements:* Subclasses of `UserList' are expect to
offer a constructor which can be called with either no arguments or one
argument.  List operations which return a new sequence attempt to
create an instance of the actual implementation class.  To do so, it
assumes that the constructor can be called with a single parameter,
which is a sequence object used as a data source.

   If a derived class does not wish to comply with this requirement, all
of the special methods supported by this class will need to be
overridden; please consult the sources for information about the
methods which need to be provided in that case.

   _Changed in Python version 2.0_


File: python-lib.info,  Node: UserString,  Next: operator,  Prev: UserList,  Up: Python Runtime Services

Class wrapper for string objects
================================

   Class wrapper for string objects.  This module was documented by
Peter Funk <pf@artcom-gmbh.de>.
This section was written by Peter Funk <pf@artcom-gmbh.de>.
This module defines a class that acts as a wrapper around string
objects.  It is a useful base class for your own string-like classes,
which can inherit from them and override existing methods or add new
ones.  In this way one can add new behaviors to strings.

   It should be noted that these classes are highly inefficient compared
to real string or Unicode objects; this is especially the case for
`MutableString'.

   The `UserString' module defines the following classes:

`UserString([sequence])'
     Class that simulates a string or a Unicode string object.  The
     instance's content is kept in a regular string or Unicode string
     object, which is accessible via the `data' attribute of
     `UserString' instances.  The instance's contents are initially set
     to a copy of SEQUENCE.  SEQUENCE can be either a regular Python
     string or Unicode string, an instance of `UserString' (or a
     subclass) or an arbitrary sequence which can be converted into a
     string using the built-in `str()' function.

`MutableString([sequence])'
     This class is derived from the `UserString' above and redefines
     strings to be _mutable_.  Mutable strings can't be used as
     dictionary keys, because dictionaries require _immutable_ objects
     as keys.  The main intention of this class is to serve as an
     educational example for inheritance and necessity to remove
     (override) the `__hash__()' method in order to trap attempts to
     use a mutable object as dictionary key, which would be otherwise
     very error prone and hard to track down.

   In addition to supporting the methods and operations of string and
Unicode objects (see section *Note String Methods::, "String Methods"),
`UserString' instances provide the following attribute:

`data'
     A real Python string or Unicode object used to store the content
     of the `UserString' class.


File: python-lib.info,  Node: operator,  Next: inspect,  Prev: UserString,  Up: Python Runtime Services

Standard operators as functions.
================================

   This section was written by Skip Montanaro <skip@automatrix.com>.
All Python's standard operators as built-in functions.

   The `operator' module exports a set of functions implemented in C
corresponding to the intrinsic operators of Python.  For example,
`operator.add(x, y)' is equivalent to the expression `x+y'.  The
function names are those used for special class methods; variants
without leading and trailing `__' are also provided for convenience.

   The `operator' module defines the following functions:

`add(a, b)'

`__add__ a, b'
     Return A `+' B, for A and B numbers.

`sub(a, b)'

`__sub__ a, b'
     Return A `-' B.

`mul(a, b)'

`__mul__ a, b'
     Return A `*' B, for A and B numbers.

`div(a, b)'

`__div__ a, b'
     Return A `/' B.

`mod(a, b)'

`__mod__ a, b'
     Return A `%' B.

`neg(o)'

`__neg__ o'
     Return O negated.

`pos(o)'

`__pos__ o'
     Return O positive.

`abs(o)'

`__abs__ o'
     Return the absolute value of O.

`inv(o)'

`invert o'

`__inv__ o'

`__invert__ o'
     Return the bitwise inverse of the number O.  The names `invert()'
     and `__invert__()' were added in Python 2.0.

`lshift(a, b)'

`__lshift__ a, b'
     Return A shifted left by B.

`rshift(a, b)'

`__rshift__ a, b'
     Return A shifted right by B.

`and_(a, b)'

`__and__ a, b'
     Return the bitwise and of A and B.

`or_(a, b)'

`__or__ a, b'
     Return the bitwise or of A and B.

`xor(a, b)'

`__xor__ a, b'
     Return the bitwise exclusive or of A and B.

`not_(o)'

`__not__ o'
     Return the outcome of `not' O.  (Note that there is no `__not__()'
     method for object instances; only the interpreter core defines
     this operation.)

`truth(o)'
     Return `1' if O is true, and 0 otherwise.

`concat(a, b)'

`__concat__ a, b'
     Return A `+' B for A and B sequences.

`repeat(a, b)'

`__repeat__ a, b'
     Return A `*' B where A is a sequence and B is an integer.

`contains(a, b)'

`__contains__ a, b'
     Return the outcome of the test B `in' A.  Note the reversed
     operands.  The name `__contains__()' was added in Python 2.0.

`sequenceIncludes(...)'
     _This is deprecated in Python 2.0.  Use `contains()' instead._
     Alias for `contains()'.

`countOf(a, b)'
     Return the number of occurrences of B in A.

`indexOf(a, b)'
     Return the index of the first of occurrence of B in A.

`getitem(a, b)'

`__getitem__ a, b'
     Return the value of A at index B.

`setitem(a, b, c)'

`__setitem__ a, b, c'
     Set the value of A at index B to C.

`delitem(a, b)'

`__delitem__ a, b'
     Remove the value of A at index B.

`getslice(a, b, c)'

`__getslice__ a, b, c'
     Return the slice of A from index B to index C`-1'.

`setslice(a, b, c, v)'

`__setslice__ a, b, c, v'
     Set the slice of A from index B to index C`-1' to the sequence V.

`delslice(a, b, c)'

`__delslice__ a, b, c'
     Delete the slice of A from index B to index C`-1'.

   The `operator' also defines a few predicates to test the type of
objects.  *Note:*  Be careful not to misinterpret the results of these
functions; only `isCallable()' has any measure of reliability with
instance objects.  For example:

     >>> class C:
     ...     pass
     ...
     >>> import operator
     >>> o = C()
     >>> operator.isMappingType(o)
     1

`isCallable(o)'
     _This is deprecated in Python 2.0.  Use the `callable()' built-in
     function instead._ Returns true if the object O can be called like
     a function, otherwise it returns false.  True is returned for
     functions, bound and unbound methods, class objects, and instance
     objects which support the `__call__()' method.

`isMappingType(o)'
     Returns true if the object O supports the mapping interface.  This
     is true for dictionaries and all instance objects.  *Warning:*
     There is no reliable way to test if an instance supports the
     complete mapping protocol since the interface itself is
     ill-defined.  This makes this test less useful than it otherwise
     might be.

`isNumberType(o)'
     Returns true if the object O represents a number.  This is true
     for all numeric types implemented in C, and for all instance
     objects.  *Warning:*  There is no reliable way to test if an
     instance supports the complete numeric interface since the
     interface itself is ill-defined.  This makes this test less useful
     than it otherwise might be.

`isSequenceType(o)'
     Returns true if the object O supports the sequence protocol.  This
     returns true for all objects which define sequence methods in C,
     and for all instance objects.  *Warning:* There is no reliable way
     to test if an instance supports the complete sequence interface
     since the interface itself is ill-defined.  This makes this test
     less useful than it otherwise might be.

   Example: Build a dictionary that maps the ordinals from `0' to `256'
to their character equivalents.

     >>> import operator
     >>> d = {}
     >>> keys = range(256)
     >>> vals = map(chr, keys)
     >>> map(operator.setitem, [d]*len(keys), keys, vals)

* Menu:

* Mapping Operators to Functions::


File: python-lib.info,  Node: Mapping Operators to Functions,  Prev: operator,  Up: operator

Mapping Operators to Functions
------------------------------

   This table shows how abstract operations correspond to operator
symbols in the Python syntax and the functions in the `operator' module.

Operation                Syntax                   Function
------                   -----                    -----
Addition                 `A + B'                  `add(A, B)'
Concatenation            `SEQ1 + SEQ2'            `concat(SEQ1, SEQ2)'
Containment Test         `O in SEQ'               `contains(SEQ, O)'
Division                 `A / B'                  `div(A, B)'
Bitwise And              `A & B'                  `and_(A, B)'
Bitwise Exclusive Or     `A ^ B'                  `xor(A, B)'
Bitwise Inversion        `~{} A'                  `invert(A)'
Bitwise Or               `A | B'                  `or_(A, B)'
Indexed Assignment       `O[K] = V'               `setitem(O, K, V)'
Indexed Deletion         `del O[K]'               `delitem(O, K)'
Indexing                 `O[K]'                   `getitem(O, K)'
Left Shift               `A <`<' B'               `lshift(A, B)'
Modulo                   `A % B'                  `mod(A, B)'
Multiplication           `A * B'                  `mul(A, B)'
Negation (Arithmetic)    `- A'                    `neg(A)'
Negation (Logical)       `not A'                  `not_(A)'
Right Shift              `A >`>' B'               `rshift(A, B)'
Sequence Repitition      `SEQ * I'                `repeat(SEQ, I)'
Slice Assignment         `SEQ[I:J]' = VALUES      `setslice(SEQ, I, J,
                                                  VALUES)'
Slice Deletion           `del SEQ[I:J]'           `delslice(SEQ, I, J)'
Slicing                  `SEQ[I:J]'               `getslice(SEQ, I, J)'
String Formatting        `S % O'                  `mod(S, O)'
Subtraction              `A - B'                  `sub(A, B)'
Truth Test               `O'                      `truth(O)'


File: python-lib.info,  Node: inspect,  Next: traceback,  Prev: operator,  Up: Python Runtime Services

Inspect live objects
====================

   Extract information and source code from live objects.  This module
was documented by Ka-Ping Yee <ping@lfw.org>.
This section was written by Ka-Ping Yee <ping@lfw.org>.
_Added in Python version 2.1_

   The `inspect' module provides several useful functions to help get
information about live objects such as modules, classes, methods,
functions, tracebacks, frame objects, and code objects.  For example,
it can help you examine the contents of a class, retrieve the source
code of a method, extract and format the argument list for a function,
or get all the information you need to display a detailed traceback.

   There are four main kinds of services provided by this module: type
checking, getting source code, inspecting classes and functions, and
examining the interpreter stack.

* Menu:

* Types and members::
* Retrieving source code::
* Classes and functions::
* interpreter stack::


File: python-lib.info,  Node: Types and members,  Next: Retrieving source code,  Prev: inspect,  Up: inspect

Types and members
-----------------

   The `getmembers()' function retrieves the members of an object such
as a class or module.  The nine functions whose names begin with "is"
are mainly provided as convenient choices for the second argument to
`getmembers()'.  They also help you determine when you can expect to
find the following special attributes:

Type                     Attribute                Description
------                   -----                    -----
module                   __doc__                  documentation string
                         __file__                 filename (missing for
                                                  built-in modules)
class                    __doc__                  documentation string
                         __module__               name of module in which
                                                  this class was defined
method                   __doc__                  documentation string
                         __name__                 name with which this
                                                  method was defined
                         im_class                 class object in which
                                                  this method belongs
                         im_func                  function object
                                                  containing
                                                  implementation of method
                         im_self                  instance to which this
                                                  method is bound, or
                                                  `None'
function                 __doc__                  documentation string
                         __name__                 name with which this
                                                  function was defined
                         func_code                code object containing
                                                  compiled function
                                                  bytecode
                         func_defaults            tuple of any default
                                                  values for arguments
                         func_doc                 (same as __doc__)
                         func_globals             global namespace in
                                                  which this function was
                                                  defined
                         func_name                (same as __name__)
traceback                tb_frame                 frame object at this
                                                  level
                         tb_lasti                 index of last attempted
                                                  instruction in bytecode
                         tb_lineno                current line number in
                                                  Python source code
                         tb_next                  next inner traceback
                                                  object (called by this
                                                  level)
frame                    f_back                   next outer frame object
                                                  (this frame's caller)
                         f_builtins               built-in namespace seen
                                                  by this frame
                         f_code                   code object being
                                                  executed in this frame
                         f_exc_traceback          traceback if raised in
                                                  this frame, or `None'
                         f_exc_type               exception type if
                                                  raised in this frame,
                                                  or `None'
                         f_exc_value              exception value if
                                                  raised in this frame,
                                                  or `None'
                         f_globals                global namespace seen
                                                  by this frame
                         f_lasti                  index of last attempted
                                                  instruction in bytecode
                         f_lineno                 current line number in
                                                  Python source code
                         f_locals                 local namespace seen by
                                                  this frame
                         f_restricted             0 or 1 if frame is in
                                                  restricted execution
                                                  mode
                         f_trace                  tracing function for
                                                  this frame, or `None'
code                     co_argcount              number of arguments
                                                  (not including * or **
                                                  args)
                         co_code                  string of raw compiled
                                                  bytecode
                         co_consts                tuple of constants used
                                                  in the bytecode
                         co_filename              name of file in which
                                                  this code object was
                                                  created
                         co_firstlineno           number of first line in
                                                  Python source code
                         co_flags                 bitmap: 1=optimized `|'
                                                  2=newlocals `|' 4=*arg
                                                  `|' 8=**arg
                         co_lnotab                encoded mapping of line
                                                  numbers to bytecode
                                                  indices
                         co_name                  name with which this
                                                  code object was defined
                         co_names                 tuple of names of local
                                                  variables
                         co_nlocals               number of local
                                                  variables
                         co_stacksize             virtual machine stack
                                                  space required
                         co_varnames              tuple of names of
                                                  arguments and local
                                                  variables
builtin                  __doc__                  documentation string
                         __name__                 original name of this
                                                  function or method
                         __self__                 instance to which a
                                                  method is bound, or
                                                  `None'

`getmembers(object[, predicate])'
     Return all the members of an object in a list of (name, value)
     pairs sorted by name.  If the optional PREDICATE argument is
     supplied, only members for which the predicate returns a true
     value are included.

`getmoduleinfo(path)'
     Return a tuple of values that describe how Python will interpret
     the file identified by PATH if it is a module, or `None' if it
     would not be identified as a module.  The return tuple is `(NAME,
     SUFFIX, MODE, MTYPE)', where NAME is the name of the module
     without the name of any enclosing package, SUFFIX is the trailing
     part of the file name (which may not be a dot-delimited
     extension), MODE is the `open()' mode that would be used (`'r'' or
     `'rb''), and MTYPE is an integer giving the type of the module.
     MTYPE will have a value which can be compared to the constants
     defined in the `imp' module; see the documentation for that module
     for more information on module types.

`getmodulename(path)'
     Return the name of the module named by the file PATH, without
     including the names of enclosing packages.  This uses the same
     algortihm as the interpreter uses when searching for modules.  If
     the name cannot be matched according to the interpreter's rules,
     `None' is returned.

`ismodule(object)'
     Return true if the object is a module.

`isclass(object)'
     Return true if the object is a class.

`ismethod(object)'
     Return true if the object is a method.

`isfunction(object)'
     Return true if the object is a Python function or unnamed (lambda)
     function.

`istraceback(object)'
     Return true if the object is a traceback.

`isframe(object)'
     Return true if the object is a frame.

`iscode(object)'
     Return true if the object is a code.

`isbuiltin(object)'
     Return true if the object is a built-in function.

`isroutine(object)'
     Return true if the object is a user-defined or built-in function
     or method.


File: python-lib.info,  Node: Retrieving source code,  Next: Classes and functions,  Prev: Types and members,  Up: inspect

Retrieving source code
----------------------

`getdoc(object)'
     Get the documentation string for an object.  All tabs are expanded
     to spaces.  To clean up docstrings that are indented to line up
     with blocks of code, any whitespace than can be uniformly removed
     from the second line onwards is removed.

`getcomments(object)'
     Return in a single string any lines of comments immediately
     preceding the object's source code (for a class, function, or
     method), or at the top of the Python source file (if the object is
     a module).

`getfile(object)'
     Return the name of the (text or binary) file in which an object was
     defined.  This will fail with a `TypeError' if the object is a
     built-in module, class, or function.

`getmodule(object)'
     Try to guess which module an object was defined in.

`getsourcefile(object)'
     Return the name of the Python source file in which an object was
     defined.  This will fail with a `TypeError' if the object is a
     built-in module, class, or function.

`getsourcelines(object)'
     Return a list of source lines and starting line number for an
     object.  The argument may be a module, class, method, function,
     traceback, frame, or code object.  The source code is returned as
     a list of the lines corresponding to the object and the line
     number indicates where in the original source file the first line
     of code was found.  An `IOError' is raised if the source code
     cannot be retrieved.

`getsource(object)'
     Return the text of the source code for an object.  The argument
     may be a module, class, method, function, traceback, frame, or
     code object.  The source code is returned as a single string.  An
     `IOError' is raised if the source code cannot be retrieved.

