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: imp,  Next: code,  Prev: warnings,  Up: Python Runtime Services

Access the `import' internals
=============================

   Access the implementation of the `import' statement.

   This module provides an interface to the mechanisms used to
implement the `import' statement.  It defines the following constants
and functions:

`get_magic()'
     Return the magic string value used to recognize byte-compiled code
     files (`.pyc' files).  (This value may be different for each
     Python version.)

`get_suffixes()'
     Return a list of triples, each describing a particular type of
     module.  Each triple has the form `(SUFFIX, MODE, TYPE)', where
     SUFFIX is a string to be appended to the module name to form the
     filename to search for, MODE is the mode string to pass to the
     built-in `open()' function to open the file (this can be `'r'' for
     text files or `'rb'' for binary files), and TYPE is the file type,
     which has one of the values `PY_SOURCE', `PY_COMPILED', or
     `C_EXTENSION', described below.

`find_module(name[, path])'
     Try to find the module NAME on the search path PATH.  If PATH is a
     list of directory names, each directory is searched for files with
     any of the suffixes returned by `get_suffixes()' above.  Invalid
     names in the list are silently ignored (but all list items must be
     strings).  If PATH is omitted or `None', the list of directory
     names given by `sys.path' is searched, but first it searches a few
     special places: it tries to find a built-in module with the given
     name (`C_BUILTIN'), then a frozen module (`PY_FROZEN'), and on
     some systems some other places are looked in as well (on the Mac,
     it looks for a resource (`PY_RESOURCE'); on Windows, it looks in
     the registry which may point to a specific file).

     If search is successful, the return value is a triple `(FILE,
     PATHNAME, DESCRIPTION)' where FILE is an open file object
     positioned at the beginning, PATHNAME is the pathname of the file
     found, and DESCRIPTION is a triple as contained in the list
     returned by `get_suffixes()' describing the kind of module found.
     If the module does not live in a file, the returned FILE is
     `None', FILENAME is the empty string, and the DESCRIPTION tuple
     contains empty strings for its suffix and mode; the module type is
     as indicate in parentheses above.  If the search is unsuccessful,
     `ImportError' is raised.  Other exceptions indicate problems with
     the arguments or environment.

     This function does not handle hierarchical module names (names
     containing dots).  In order to find P.M, i.e., submodule M of
     package P, use `find_module()' and `load_module()' to find and
     load package P, and then use `find_module()' with the PATH
     argument set to `P.__path__'.  When P itself has a dotted name,
     apply this recipe recursively.

`load_module(name, file, filename, description)'
     Load a module that was previously found by `find_module()' (or by
     an otherwise conducted search yielding compatible results).  This
     function does more than importing the module: if the module was
     already imported, it is equivalent to a `reload()'!  The NAME
     argument indicates the full module name (including the package
     name, if this is a submodule of a package).  The FILE argument is
     an open file, and FILENAME is the corresponding file name; these
     can be `None' and `''', respectively, when the module is not being
     loaded from a file.  The DESCRIPTION argument is a tuple, as would
     be returned by `get_suffixes()', describing what kind of module
     must be loaded.

     If the load is successful, the return value is the module object;
     otherwise, an exception (usually `ImportError') is raised.

     *Important:* the caller is responsible for closing the FILE
     argument, if it was not `None', even when an exception is raised.
     This is best done using a `try' ... `finally' statement.

`new_module(name)'
     Return a new empty module object called NAME.  This object is
     _not_ inserted in `sys.modules'.

   The following constants with integer values, defined in this module,
are used to indicate the search result of `find_module()'.

`PY_SOURCE'
     The module was found as a source file.

`PY_COMPILED'
     The module was found as a compiled code object file.

`C_EXTENSION'
     The module was found as dynamically loadable shared library.

`PY_RESOURCE'
     The module was found as a Macintosh resource.  This value can only
     be returned on a Macintosh.

`PKG_DIRECTORY'
     The module was found as a package directory.

`C_BUILTIN'
     The module was found as a built-in module.

`PY_FROZEN'
     The module was found as a frozen module (see `init_frozen()').

   The following constant and functions are obsolete; their
functionality is available through `find_module()' or `load_module()'.
They are kept around for backward compatibility:

`SEARCH_ERROR'
     Unused.

`init_builtin(name)'
     Initialize the built-in module called NAME and return its module
     object.  If the module was already initialized, it will be
     initialized _again_.  A few modules cannot be initialized twice --
     attempting to initialize these again will raise an `ImportError'
     exception.  If there is no built-in module called NAME, `None' is
     returned.

`init_frozen(name)'
     Initialize the frozen module called NAME and return its module
     object.  If the module was already initialized, it will be
     initialized _again_.  If there is no frozen module called NAME,
     `None' is returned.  (Frozen modules are modules written in Python
     whose compiled byte-code object is incorporated into a
     custom-built Python interpreter by Python's `freeze' utility.  See
     `Tools/freeze/' for now.)

`is_builtin(name)'
     Return `1' if there is a built-in module called NAME which can be
     initialized again.  Return `-1' if there is a built-in module
     called NAME which cannot be initialized again (see
     `init_builtin()').  Return `0' if there is no built-in module
     called NAME.

`is_frozen(name)'
     Return `1' if there is a frozen module (see `init_frozen()')
     called NAME, or `0' if there is no such module.

`load_compiled(name, pathname, file)'
     Load and initialize a module implemented as a byte-compiled code
     file and return its module object.  If the module was already
     initialized, it will be initialized _again_.  The NAME argument is
     used to create or access a module object.  The PATHNAME argument
     points to the byte-compiled code file.  The FILE argument is the
     byte-compiled code file, open for reading in binary mode, from the
     beginning.  It must currently be a real file object, not a
     user-defined class emulating a file.

`load_dynamic(name, pathname[, file])'
     Load and initialize a module implemented as a dynamically loadable
     shared library and return its module object.  If the module was
     already initialized, it will be initialized _again_.  Some modules
     don't like that and may raise an exception.  The PATHNAME argument
     must point to the shared library.  The NAME argument is used to
     construct the name of the initialization function: an external C
     function called `initNAME()' in the shared library is called.  The
     optional FILE argument is ignored.  (Note: using shared libraries
     is highly system dependent, and not all systems support it.)

`load_source(name, pathname, file)'
     Load and initialize a module implemented as a Python source file
     and return its module object.  If the module was already
     initialized, it will be initialized _again_.  The NAME argument is
     used to create or access a module object.  The PATHNAME argument
     points to the source file.  The FILE argument is the source file,
     open for reading as text, from the beginning.  It must currently
     be a real file object, not a user-defined class emulating a file.
     Note that if a properly matching byte-compiled file (with suffix
     `.pyc' or `.pyo') exists, it will be used instead of parsing the
     given source file.

* Menu:

* Examples::


File: python-lib.info,  Node: Examples,  Prev: imp,  Up: imp

Examples
--------

   The following function emulates what was the standard import
statement up to Python 1.4 (i.e., no hierarchical module names).  (This
_implementation_ wouldn't work in that version, since `find_module()'
has been extended and `load_module()' has been added in 1.4.)

     import imp
     import sys
     
     def __import__(name, globals=None, locals=None, fromlist=None):
         # Fast path: see if the module has already been imported.
         try:
             return sys.modules[name]
         except KeyError:
             pass
     
         # If any of the following calls raises an exception,
         # there's a problem we can't handle -- let the caller handle it.
     
         fp, pathname, description = imp.find_module(name)
     
         try:
             return imp.load_module(name, fp, pathname, description)
         finally:
             # Since we may exit via an exception, close fp explicitly.
             if fp:
                 fp.close()

   A more complete example that implements hierarchical module names and
includes a `reload()' function can be found in the standard module
`knee' (which is intended as an example only -- don't rely on any part
of it being a standard interface).


File: python-lib.info,  Node: code,  Next: codeop,  Prev: imp,  Up: Python Runtime Services

Interpreter base classes
========================

   Base classes for interactive Python interpreters.

   The `code' module provides facilities to implement read-eval-print
loops in Python.  Two classes and convenience functions are included
which can be used to build applications which provide an interactive
interpreter prompt.

`InteractiveInterpreter([locals])'
     This class deals with parsing and interpreter state (the user's
     namespace); it does not deal with input buffering or prompting or
     input file naming (the filename is always passed in explicitly).
     The optional LOCALS argument specifies the dictionary in which
     code will be executed; it defaults to a newly created dictionary
     with key `'__name__'' set to `'__console__'' and key `'__doc__''
     set to `None'.

`InteractiveConsole([locals[, filename]])'
     Closely emulate the behavior of the interactive Python interpreter.
     This class builds on `InteractiveInterpreter' and adds prompting
     using the familiar `sys.ps1' and `sys.ps2', and input buffering.

`interact([banner[, readfunc[, local]]])'
     Convenience function to run a read-eval-print loop.  This creates a
     new instance of `InteractiveConsole' and sets READFUNC to be used
     as the `raw_input()' method, if provided.  If LOCAL is provided,
     it is passed to the `InteractiveConsole' constructor for use as
     the default namespace for the interpreter loop.  The `interact()'
     method of the instance is then run with BANNER passed as the banner
     to use, if provided.  The console object is discarded after use.

`compile_command(source[, filename[, symbol]])'
     This function is useful for programs that want to emulate Python's
     interpreter main loop (a.k.a. the read-eval-print loop).  The
     tricky part is to determine when the user has entered an
     incomplete command that can be completed by entering more text (as
     opposed to a complete command or a syntax error).  This function
     _almost_ always makes the same decision as the real interpreter
     main loop.

     SOURCE is the source string; FILENAME is the optional filename
     from which source was read, defaulting to `'<input>''; and SYMBOL
     is the optional grammar start symbol, which should be either
     `'single'' (the default) or `'eval''.

     Returns a code object (the same as `compile(SOURCE, FILENAME,
     SYMBOL)') if the command is complete and valid; `None' if the
     command is incomplete; raises `SyntaxError' if the command is
     complete and contains a syntax error, or raises `OverflowError' if
     the command includes a numeric constant which exceeds the range of
     the appropriate numeric type.

* Menu:

* Interactive Interpreter Objects::
* Interactive Console Objects::


File: python-lib.info,  Node: Interactive Interpreter Objects,  Next: Interactive Console Objects,  Prev: code,  Up: code

Interactive Interpreter Objects
-------------------------------

`runsource(source[, filename[, symbol]])'
     Compile and run some source in the interpreter.  Arguments are the
     same as for `compile_command()'; the default for FILENAME is
     `'<input>'', and for SYMBOL is `'single''.  One several things can
     happen:

        * The input is incorrect; `compile_command()' raised an
          exception (`SyntaxError' or `OverflowError').  A syntax
          traceback will be printed by calling the `showsyntaxerror()'
          method.  `runsource()' returns `0'.

        * The input is incomplete, and more input is required;
          `compile_command()' returned `None'.  `runsource()' returns
          `1'.

        * The input is complete; `compile_command()' returned a code
          object.  The code is executed by calling the `runcode()'
          (which also handles run-time exceptions, except for
          `SystemExit').  `runsource()' returns `0'.

     The return value can be used to decide whether to use `sys.ps1' or
     `sys.ps2' to prompt the next line.

`runcode(code)'
     Execute a code object.  When an exception occurs,
     `showtraceback()' is called to display a traceback.  All
     exceptions are caught except `SystemExit', which is allowed to
     propagate.

     A note about `KeyboardInterrupt': this exception may occur
     elsewhere in this code, and may not always be caught.  The caller
     should be prepared to deal with it.

`showsyntaxerror([filename])'
     Display the syntax error that just occurred.  This does not display
     a stack trace because there isn't one for syntax errors.  If
     FILENAME is given, it is stuffed into the exception instead of the
     default filename provided by Python's parser, because it always
     uses `'<string>'' when reading from a string.  The output is
     written by the `write()' method.

`showtraceback()'
     Display the exception that just occurred.  We remove the first
     stack item because it is within the interpreter object
     implementation.  The output is written by the `write()' method.

`write(data)'
     Write a string to the standard error stream (`sys.stderr').
     Derived classes should override this to provide the appropriate
     output handling as needed.


File: python-lib.info,  Node: Interactive Console Objects,  Prev: Interactive Interpreter Objects,  Up: code

Interactive Console Objects
---------------------------

   The `InteractiveConsole' class is a subclass of
`InteractiveInterpreter', and so offers all the methods of the
interpreter objects as well as the following additions.

`interact([banner])'
     Closely emulate the interactive Python console.  The optional
     banner argument specify the banner to print before the first
     interaction; by default it prints a banner similar to the one
     printed by the standard Python interpreter, followed by the class
     name of the console object in parentheses (so as not to confuse
     this with the real interpreter - since it's so close!).

`push(line)'
     Push a line of source text to the interpreter.  The line should
     not have a trailing newline; it may have internal newlines.  The
     line is appended to a buffer and the interpreter's `runsource()'
     method is called with the concatenated contents of the buffer as
     source.  If this indicates that the command was executed or
     invalid, the buffer is reset; otherwise, the command is
     incomplete, and the buffer is left as it was after the line was
     appended.  The return value is `1' if more input is required, `0'
     if the line was dealt with in some way (this is the same as
     `runsource()').

`resetbuffer()'
     Remove any unhandled source text from the input buffer.

`raw_input([prompt])'
     Write a prompt and read a line.  The returned line does not include
     the trailing newline.  When the user enters the `EOF' key sequence,
     `EOFError' is raised.  The base implementation uses the built-in
     function `raw_input()'; a subclass may replace this with a
     different implementation.


File: python-lib.info,  Node: codeop,  Next: pprint,  Prev: code,  Up: Python Runtime Services

Compile Python code
===================

   This section was written by Moshe Zadka <moshez@zadka.site.co.il>.
Compile (possibly incomplete) Python code.

   The `codeop' module provides a function to compile Python code with
hints on whether it is certainly complete, possibly complete or
definitely incomplete.  This is used by the `code' module and should
not normally be used directly.

   The `codeop' module defines the following function:

`compile_command(source[, filename[, symbol]])'
     Tries to compile SOURCE, which should be a string of Python code
     and return a code object if SOURCE is valid Python code. In that
     case, the filename attribute of the code object will be FILENAME,
     which defaults to `'<input>''.  Returns `None' if SOURCE is _not_
     valid Python code, but is a prefix of valid Python code.

     If there is a problem with SOURCE, an exception will be raised.
     `SyntaxError' is raised if there is invalid Python syntax, and
     `OverflowError' if there is an invalid numeric constant.

     The SYMBOL argument determines whether SOURCE is compiled as a
     statement (`'single'', the default) or as an expression
     (`'eval'').  Any other value will cause `ValueError' to be raised.

     *Caveat:* It is possible (but not likely) that the parser stops
     parsing with a successful outcome before reaching the end of the
     source; in this case, trailing symbols may be ignored instead of
     causing an error.  For example, a backslash followed by two
     newlines may be followed by arbitrary garbage.  This will be fixed
     once the API for the parser is better.


File: python-lib.info,  Node: pprint,  Next: repr,  Prev: codeop,  Up: Python Runtime Services

Data pretty printer
===================

   Data pretty printer.  This module was documented by Fred L. Drake,
Jr. <fdrake@acm.org>.
This section was written by Fred L. Drake, Jr. <fdrake@acm.org>.
The `pprint' module provides a capability to "pretty-print" arbitrary
Python data structures in a form which can be used as input to the
interpreter.  If the formatted structures include objects which are not
fundamental Python types, the representation may not be loadable.  This
may be the case if objects such as files, sockets, classes, or
instances are included, as well as many other builtin objects which are
not representable as Python constants.

   The formatted representation keeps objects on a single line if it
can, and breaks them onto multiple lines if they don't fit within the
allowed width.  Construct `PrettyPrinter' objects explicitly if you
need to adjust the width constraint.

   The `pprint' module defines one class:

`PrettyPrinter(...)'
     Construct a `PrettyPrinter' instance.  This constructor
     understands several keyword parameters.  An output stream may be
     set using the STREAM keyword; the only method used on the stream
     object is the file protocol's `write()' method.  If not specified,
     the `PrettyPrinter' adopts `sys.stdout'.  Three additional
     parameters may be used to control the formatted representation.
     The keywords are INDENT, DEPTH, and WIDTH.  The amount of
     indentation added for each recursive level is specified by INDENT;
     the default is one.  Other values can cause output to look a
     little odd, but can make nesting easier to spot.  The number of
     levels which may be printed is controlled by DEPTH; if the data
     structure being printed is too deep, the next contained level is
     replaced by `...'.  By default, there is no constraint on the
     depth of the objects being formatted.  The desired output width is
     constrained using the WIDTH parameter; the default is eighty
     characters.  If a structure cannot be formatted within the
     constrained width, a best effort will be made.

          >>> import pprint, sys
          >>> stuff = sys.path[:]
          >>> stuff.insert(0, stuff[:])
          >>> pp = pprint.PrettyPrinter(indent=4)
          >>> pp.pprint(stuff)
          [   [   '',
                  '/usr/local/lib/python1.5',
                  '/usr/local/lib/python1.5/test',
                  '/usr/local/lib/python1.5/sunos5',
                  '/usr/local/lib/python1.5/sharedmodules',
                  '/usr/local/lib/python1.5/tkinter'],
              '',
              '/usr/local/lib/python1.5',
              '/usr/local/lib/python1.5/test',
              '/usr/local/lib/python1.5/sunos5',
              '/usr/local/lib/python1.5/sharedmodules',
              '/usr/local/lib/python1.5/tkinter']
          >>>
          >>> import parser
          >>> tup = parser.ast2tuple(
          ...     parser.suite(open('pprint.py').read()))[1][1][1]
          >>> pp = pprint.PrettyPrinter(depth=6)
          >>> pp.pprint(tup)
          (266, (267, (307, (287, (288, (...))))))

   The `PrettyPrinter' class supports several derivative functions:

`pformat(object)'
     Return the formatted representation of OBJECT as a string.  The
     default parameters for formatting are used.

`pprint(object[, stream])'
     Prints the formatted representation of OBJECT on STREAM, followed
     by a newline.  If STREAM is omitted, `sys.stdout' is used.  This
     may be used in the interactive interpreter instead of a `print'
     statement for inspecting values.  The default parameters for
     formatting are used.

          >>> stuff = sys.path[:]
          >>> stuff.insert(0, stuff)
          >>> pprint.pprint(stuff)
          [<Recursion on list with id=869440>,
           '',
           '/usr/local/lib/python1.5',
           '/usr/local/lib/python1.5/test',
           '/usr/local/lib/python1.5/sunos5',
           '/usr/local/lib/python1.5/sharedmodules',
           '/usr/local/lib/python1.5/tkinter']

`isreadable(object)'
     Determine if the formatted representation of OBJECT is "readable,"
     or can be used to reconstruct the value using `eval()'.  This
     always returns false for recursive objects.

          >>> pprint.isreadable(stuff)
          0

`isrecursive(object)'
     Determine if OBJECT requires a recursive representation.

   One more support function is also defined:

`saferepr(object)'
     Return a string representation of OBJECT, protected against
     recursive data structures.  If the representation of OBJECT
     exposes a recursive entry, the recursive reference will be
     represented as `<Recursion on TYPENAME with id=NUMBER>'.  The
     representation is not otherwise formatted.

     >>> pprint.saferepr(stuff)
     "[<Recursion on list with id=682968>, '', '/usr/local/lib/python1.5', '/usr/loca
     l/lib/python1.5/test', '/usr/local/lib/python1.5/sunos5', '/usr/local/lib/python
     1.5/sharedmodules', '/usr/local/lib/python1.5/tkinter']"

* Menu:

* PrettyPrinter Objects::


File: python-lib.info,  Node: PrettyPrinter Objects,  Prev: pprint,  Up: pprint

PrettyPrinter Objects
---------------------

   `PrettyPrinter' instances have the following methods:

`pformat(object)'
     Return the formatted representation of OBJECT.  This takes into
     Account the options passed to the `PrettyPrinter' constructor.

`pprint(object)'
     Print the formatted representation of OBJECT on the configured
     stream, followed by a newline.

   The following methods provide the implementations for the
corresponding functions of the same names.  Using these methods on an
instance is slightly more efficient since new `PrettyPrinter' objects
don't need to be created.

`isreadable(object)'
     Determine if the formatted representation of the object is
     "readable," or can be used to reconstruct the value using
     `eval()'.  Note that this returns false for recursive objects.  If
     the DEPTH parameter of the `PrettyPrinter' is set and the object
     is deeper than allowed, this returns false.

`isrecursive(object)'
     Determine if the object requires a recursive representation.


File: python-lib.info,  Node: repr,  Next: new,  Prev: pprint,  Up: Python Runtime Services

Alternate `repr()' implementation
=================================

   This section was written by Fred L. Drake, Jr. <fdrake@acm.org>.
Alternate `repr()' implementation with size limits.

   The `repr' module provides a means for producing object
representations with limits on the size of the resulting strings.  This
is used in the Python debugger and may be useful in other contexts as
well.

   This module provides a class, an instance, and a function:

`Repr()'
     Class which provides formatting services useful in implementing
     functions similar to the built-in `repr()'; size limits for
     different object types are added to avoid the generation of
     representations which are excessively long.

`aRepr'
     This is an instance of `Repr' which is used to provide the
     `repr()' function described below.  Changing the attributes of
     this object will affect the size limits used by `repr()' and the
     Python debugger.

`repr(obj)'
     This is the `repr()' method of `aRepr'.  It returns a string
     similar to that returned by the built-in function of the same
     name, but with limits on most sizes.

* Menu:

* Repr Objects::
* Subclassing Repr Objects::


File: python-lib.info,  Node: Repr Objects,  Next: Subclassing Repr Objects,  Prev: repr,  Up: repr

Repr Objects
------------

   `Repr' instances provide several members which can be used to
provide size limits for the representations of different object types,
and methods which format specific object types.

`maxlevel'
     Depth limit on the creation of recursive representations.  The
     default is `6'.

`maxdict'

`maxlist'

`maxtuple'
     Limits on the number of entries represented for the named object
     type.  The default for `maxdict' is `4', for the others, `6'.

`maxlong'
     Maximum number of characters in the representation for a long
     integer.  Digits are dropped from the middle.  The default is `40'.

`maxstring'
     Limit on the number of characters in the representation of the
     string.  Note that the "normal" representation of the string is
     used as the character source: if escape sequences are needed in the
     representation, these may be mangled when the representation is
     shortened.  The default is `30'.

`maxother'
     This limit is used to control the size of object types for which no
     specific formatting method is available on the `Repr' object.  It
     is applied in a similar manner as `maxstring'.  The default is
     `20'.

`repr(obj)'
     The equivalent to the built-in `repr()' that uses the formatting
     imposed by the instance.

`repr1(obj, level)'
     Recursive implementation used by `repr()'.  This uses the type of
     OBJ to determine which formatting method to call, passing it OBJ
     and LEVEL.  The type-specific methods should call `repr1()' to
     perform recursive formatting, with `LEVEL - 1' for the value of
     LEVEL in the recursive call.

`repr_TYPE(obj, level)'
     Formatting methods for specific types are implemented as methods
     with a name based on the type name.  In the method name, TYPE is
     replaced by `string.join(string.split(type(OBJ).__name__, '_')'.
     Dispatch to these methods is handled by `repr1()'.  Type-specific
     methods which need to recursively format a value should call
     `self.repr1(SUBOBJ, LEVEL - 1)'.


File: python-lib.info,  Node: Subclassing Repr Objects,  Prev: Repr Objects,  Up: repr

Subclassing Repr Objects
------------------------

   The use of dynamic dispatching by `Repr.repr1()' allows subclasses
of `Repr' to add support for additional built-in object types or to
modify the handling of types already supported.  This example shows how
special support for file objects could be added:

     import repr
     import sys
     
     class MyRepr(repr.Repr):
         def repr_file(self, obj, level):
             if obj.name in ['<stdin>', '<stdout>', '<stderr>']:
                 return obj.name
             else:
                 return `obj`
     
     aRepr = MyRepr()
     print aRepr.repr(sys.stdin)          # prints '<stdin>'


File: python-lib.info,  Node: new,  Next: site,  Prev: repr,  Up: Python Runtime Services

Creation of runtime internal objects
====================================

   This section was written by Moshe Zadka <moshez@zadka.site.co.il>.
Interface to the creation of runtime implementation objects.

   The `new' module allows an interface to the interpreter object
creation functions. This is for use primarily in marshal-type functions,
when a new object needs to be created "magically" and not by using the
regular creation functions. This module provides a low-level interface
to the interpreter, so care must be exercised when using this module.

   The `new' module defines the following functions:

`instance(class[, dict])'
     This function creates an instance of CLASS with dictionary DICT
     without calling the `__init__()' constructor.  If DICT is omitted
     or `None', a new, empty dictionary is created for the new
     instance.  Note that there are no guarantees that the object will
     be in a consistent state.

`instancemethod(function, instance, class)'
     This function will return a method object, bound to INSTANCE, or
     unbound if INSTANCE is `None'.  FUNCTION must be callable, and
     INSTANCE must be an instance object or `None'.

`function(code, globals[, name[, argdefs]])'
     Returns a (Python) function with the given code and globals. If
     NAME is given, it must be a string or `None'.  If it is a string,
     the function will have the given name, otherwise the function name
     will be taken from `CODE.co_name'.  If ARGDEFS is given, it must
     be a tuple and will be used to determine the default values of
     parameters.

`code(argcount, nlocals, stacksize, flags, codestring, constants, names, varnames, filename, name, firstlineno, lnotab)'
     This function is an interface to the `PyCode_New()' C function.

`module(name)'
     This function returns a new module object with name NAME.  NAME
     must be a string.

`classobj(name, baseclasses, dict)'
     This function returns a new class object, with name NAME, derived
     from BASECLASSES (which should be a tuple of classes) and with
     namespace DICT.


File: python-lib.info,  Node: site,  Next: user,  Prev: new,  Up: Python Runtime Services

Site-specific configuration hook
================================

   A standard way to reference site-specific modules.

   *This module is automatically imported during initialization.*

   In earlier versions of Python (up to and including 1.5a3), scripts or
modules that needed to use site-specific modules would place `import
site' somewhere near the top of their code.  This is no longer
necessary.

   This will append site-specific paths to the module search path.

   It starts by constructing up to four directories from a head and a
tail part.  For the head part, it uses `sys.prefix' and
`sys.exec_prefix'; empty heads are skipped.  For the tail part, it uses
the empty string (on Macintosh or Windows) or it uses first
`lib/python2.1/site-packages' and then `lib/site-python' (on UNIX).
For each of the distinct head-tail combinations, it sees if it refers
to an existing directory, and if so, adds to `sys.path', and also
inspects the path for configuration files.

   A path configuration file is a file whose name has the form
`PACKAGE.pth'; its contents are additional items (one per line) to be
added to `sys.path'.  Non-existing items are never added to `sys.path',
but no check is made that the item refers to a directory (rather than a
file).  No item is added to `sys.path' more than once.  Blank lines and
lines beginning with `#' are skipped.  Lines starting with `import' are
executed.

   For example, suppose `sys.prefix' and `sys.exec_prefix' are set to
`/usr/local'.  The Python 2.1 library is then installed in
`/usr/local/lib/python2.1' (where only the first three characters of
`sys.version' are used to form the installation path name).  Suppose
this has a subdirectory `/usr/local/lib/python2.1/site-packages' with
three subsubdirectories, `foo', `bar' and `spam', and two path
configuration files, `foo.pth' and `bar.pth'.  Assume `foo.pth'
contains the following:

     # foo package configuration
     
     foo
     bar
     bletch

   and `bar.pth' contains:

     # bar package configuration
     
     bar

   Then the following directories are added to `sys.path', in this
order:

     /usr/local/lib/python1.5/site-packages/bar
     /usr/local/lib/python1.5/site-packages/foo

   Note that `bletch' is omitted because it doesn't exist; the `bar'
directory precedes the `foo' directory because `bar.pth' comes
alphabetically before `foo.pth'; and `spam' is omitted because it is
not mentioned in either path configuration file.

   After these path manipulations, an attempt is made to import a module
named `sitecustomize', which can perform arbitrary site-specific
customizations.  If this import fails with an `ImportError' exception,
it is silently ignored.

   Note that for some non-UNIX systems, `sys.prefix' and
`sys.exec_prefix' are empty, and the path manipulations are skipped;
however the import of `sitecustomize' is still attempted.


File: python-lib.info,  Node: user,  Next: __builtin__,  Prev: site,  Up: Python Runtime Services

User-specific configuration hook
================================

   A standard way to reference user-specific modules.

   As a policy, Python doesn't run user-specified code on startup of
Python programs.  (Only interactive sessions execute the script
specified in the `PYTHONSTARTUP' environment variable if it exists).

   However, some programs or sites may find it convenient to allow users
to have a standard customization file, which gets run when a program
requests it.  This module implements such a mechanism.  A program that
wishes to use the mechanism must execute the statement

     import user

   The `user' module looks for a file `.pythonrc.py' in the user's home
directory and if it can be opened, executes it (using `execfile()') in
its own (i.e. the module `user''s) global namespace.  Errors during
this phase are not caught; that's up to the program that imports the
`user' module, if it wishes.  The home directory is assumed to be named
by the `HOME' environment variable; if this is not set, the current
directory is used.

   The user's `.pythonrc.py' could conceivably test for `sys.version'
if it wishes to do different things depending on the Python version.

   A warning to users: be very conservative in what you place in your
`.pythonrc.py' file.  Since you don't know which programs will use it,
changing the behavior of standard modules or functions is generally not
a good idea.

   A suggestion for programmers who wish to use this mechanism: a simple
way to let users specify options for your package is to have them
define variables in their `.pythonrc.py' file that you test in your
module.  For example, a module `spam' that has a verbosity level can
look for a variable `user.spam_verbose', as follows:

     import user
     try:
         verbose = user.spam_verbose  # user's verbosity preference
     except AttributeError:
         verbose = 0                  # default verbosity

   Programs with extensive customization needs are better off reading a
program-specific customization file.

   Programs with security or privacy concerns should _not_ import this
module; a user can easily break into a program by placing arbitrary
code in the `.pythonrc.py' file.

   Modules for general use should _not_ import this module; it may
interfere with the operation of the importing program.

   See also:

   *Note site:: Site-wide customization mechanism.


File: python-lib.info,  Node: __builtin__,  Next: __main__,  Prev: user,  Up: Python Runtime Services

Built-in functions
==================

   The set of built-in functions.

   This module provides direct access to all `built-in' identifiers of
Python; e.g. `__builtin__.open' is the full name for the built-in
function `open()'.  See section *Note Built-in Functions::, "Built-in
Functions."


File: python-lib.info,  Node: __main__,  Prev: __builtin__,  Up: Python Runtime Services

Top-level script environment
============================

   The environment where the top-level script is run.

   This module represents the (otherwise anonymous) scope in which the
interpreter's main program executes -- commands read either from
standard input, from a script file, or from an interactive prompt.  It
is this environment in which the idiomatic "conditional script" stanza
causes a script to run:

     if __name__ == "__main__":
         main()


File: python-lib.info,  Node: String Services,  Next: Miscellaneous Services,  Prev: Python Runtime Services,  Up: Top

String Services
***************

   The modules described in this chapter provide a wide range of string
manipulation operations.  Here's an overview:

* Menu:

* string::
* re::
* struct::
* difflib::
* fpformat::
* StringIO::
* cStringIO::
* codecs::
* unicodedata::


File: python-lib.info,  Node: string,  Next: re,  Prev: String Services,  Up: String Services

Common string operations
========================

   Common string operations.

   This module defines some constants useful for checking character
classes and some useful string functions.  See the module `re' for
string functions based on regular expressions.

   The constants defined in this module are:

`digits'
     The string `'0123456789''.

`hexdigits'
     The string `'0123456789abcdefABCDEF''.

`letters'
     The concatenation of the strings `lowercase' and `uppercase'
     described below.

`lowercase'
     A string containing all the characters that are considered
     lowercase letters.  On most systems this is the string
     `'abcdefghijklmnopqrstuvwxyz''.  Do not change its definition --
     the effect on the routines `upper()' and `swapcase()' is undefined.

`octdigits'
     The string `'01234567''.

`punctuation'
     String of ASCII characters which are considered punctuation
     characters in the `C' locale.

`printable'
     String of characters which are considered printable.  This is a
     combination of `digits', `letters', `punctuation', and
     `whitespace'.

`uppercase'
     A string containing all the characters that are considered
     uppercase letters.  On most systems this is the string
     `'ABCDEFGHIJKLMNOPQRSTUVWXYZ''.  Do not change its definition --
     the effect on the routines `lower()' and `swapcase()' is undefined.

`whitespace'
     A string containing all characters that are considered whitespace.
     On most systems this includes the characters space, tab, linefeed,
     return, formfeed, and vertical tab.  Do not change its definition
     -- the effect on the routines `strip()' and `split()' is undefined.

   Many of the functions provided by this module are also defined as
methods of string and Unicode objects; see "String Methods" (section
*Note String Methods::) for more information on those.  The functions
defined in this module are:

`atof(s)'
     _This is deprecated in Python 2.0.  Use the `float()' built-in
     function._ Convert a string to a floating point number.  The
     string must have the standard syntax for a floating point literal
     in Python, optionally preceded by a sign (`+' or `-').  Note that
     this behaves identical to the built-in function `float()' when
     passed a string.

     *Note:* When passing in a string, values for NaNand Infinity may
     be returned, depending on the underlying C library.  The specific
     set of strings accepted which cause these values to be returned
     depends entirely on the C library and is known to vary.

`atoi(s[, base])'
     _This is deprecated in Python 2.0.  Use the `int()' built-in
     function._ Convert string S to an integer in the given BASE.  The
     string must consist of one or more digits, optionally preceded by a
     sign (`+' or `-').  The BASE defaults to 10.  If it is 0, a
     default base is chosen depending on the leading characters of the
     string (after stripping the sign): `0x' or `0X' means 16, `0'
     means 8, anything else means 10.  If BASE is 16, a leading `0x' or
     `0X' is always accepted, though not required.  This behaves
     identically to the built-in function `int()' when passed a string.
     (Also note: for a more flexible interpretation of numeric
     literals, use the built-in function `eval()'.)

`atol(s[, base])'
     _This is deprecated in Python 2.0.  Use the `long()' built-in
     function._ Convert string S to a long integer in the given BASE.
     The string must consist of one or more digits, optionally preceded
     by a sign (`+' or `-').  The BASE argument has the same meaning as
     for `atoi()'.  A trailing `l' or `L' is not allowed, except if the
     base is 0.  Note that when invoked without BASE or with BASE set
     to 10, this behaves identical to the built-in function `long()'
     when passed a string.

`capitalize(word)'
     Capitalize the first character of the argument.

`capwords(s)'
     Split the argument into words using `split()', capitalize each
     word using `capitalize()', and join the capitalized words using
     `join()'.  Note that this replaces runs of whitespace characters
     by a single space, and removes leading and trailing whitespace.

`expandtabs(s[, tabsize])'
     Expand tabs in a string, i.e. replace them by one or more spaces,
     depending on the current column and the given tab size.  The column
     number is reset to zero after each newline occurring in the string.
     This doesn't understand other non-printing characters or escape
     sequences.  The tab size defaults to 8.

`find(s, sub[, start[,end]])'
     Return the lowest index in S where the substring SUB is found such
     that SUB is wholly contained in `S[START:END]'.  Return `-1' on
     failure.  Defaults for START and END and interpretation of
     negative values is the same as for slices.

`rfind(s, sub[, start[, end]])'
     Like `find()' but find the highest index.

`index(s, sub[, start[, end]])'
     Like `find()' but raise `ValueError' when the substring is not
     found.

`rindex(s, sub[, start[, end]])'
     Like `rfind()' but raise `ValueError' when the substring is not
     found.

`count(s, sub[, start[, end]])'
     Return the number of (non-overlapping) occurrences of substring
     SUB in string `S[START:END]'.  Defaults for START and END and
     interpretation of negative values are the same as for slices.

`lower(s)'
     Return a copy of S, but with upper case letters converted to lower
     case.

`maketrans(from, to)'
     Return a translation table suitable for passing to `translate()'
     or `regex.compile()', that will map each character in FROM into
     the character at the same position in TO; FROM and TO must have
     the same length.

     *Warning:* don't use strings derived from `lowercase' and
     `uppercase' as arguments; in some locales, these don't have the
     same length.  For case conversions, always use `lower()' and
     `upper()'.

`split(s[, sep[, maxsplit]])'
     Return a list of the words of the string S.  If the optional
     second argument SEP is absent or `None', the words are separated
     by arbitrary strings of whitespace characters (space, tab,
     newline, return, formfeed).  If the second argument SEP is present
     and not `None', it specifies a string to be used as the word
     separator.  The returned list will then have one more item than
     the number of non-overlapping occurrences of the separator in the
     string.  The optional third argument MAXSPLIT defaults to 0.  If
     it is nonzero, at most MAXSPLIT number of splits occur, and the
     remainder of the string is returned as the final element of the
     list (thus, the list will have at most `MAXSPLIT+1' elements).

`splitfields(s[, sep[, maxsplit]])'
     This function behaves identically to `split()'.  (In the past,
     `split()' was only used with one argument, while `splitfields()'
     was only used with two arguments.)

`join(words[, sep])'
     Concatenate a list or tuple of words with intervening occurrences
     of SEP.  The default value for SEP is a single space character.
     It is always true that `string.join(string.split(S, SEP), SEP)'
     equals S.

`joinfields(words[, sep])'
     This function behaves identical to `join()'.  (In the past,
     `join()' was only used with one argument, while `joinfields()' was
     only used with two arguments.)

`lstrip(s)'
     Return a copy of S but without leading whitespace characters.

`rstrip(s)'
     Return a copy of S but without trailing whitespace characters.

`strip(s)'
     Return a copy of S without leading or trailing whitespace.

`swapcase(s)'
     Return a copy of S, but with lower case letters converted to upper
     case and vice versa.

`translate(s, table[, deletechars])'
     Delete all characters from S that are in DELETECHARS (if present),
     and then translate the characters using TABLE, which must be a
     256-character string giving the translation for each character
     value, indexed by its ordinal.

`upper(s)'
     Return a copy of S, but with lower case letters converted to upper
     case.

`ljust(s, width)'

`rjust s, width'

`center s, width'
     These functions respectively left-justify, right-justify and center
     a string in a field of given width.  They return a string that is
     at least WIDTH characters wide, created by padding the string S
     with spaces until the given width on the right, left or both
     sides.  The string is never truncated.

`zfill(s, width)'
     Pad a numeric string on the left with zero digits until the given
     width is reached.  Strings starting with a sign are handled
     correctly.

`replace(str, old, new[, maxsplit])'
     Return a copy of string STR with all occurrences of substring OLD
     replaced by NEW.  If the optional argument MAXSPLIT is given, the
     first MAXSPLIT occurrences are replaced.

   This module is implemented in Python.  Much of its functionality has
been reimplemented in the built-in module `strop'.  However, you should
_never_ import the latter module directly.  When `string' discovers
that `strop' exists, it transparently replaces parts of itself with the
implementation from `strop'.  After initialization, there is _no_
overhead in using `string' instead of `strop'.


File: python-lib.info,  Node: re,  Next: struct,  Prev: string,  Up: String Services

Regular expression operations
=============================

   This module was documented by Andrew M. Kuchling <amk1@bigfoot.com>.
This module was documented by Fredrik Lundh <effbot@telia.com>.
This section was written by Andrew M. Kuchling <amk1@bigfoot.com>.
Regular expression search and match operations with a Perl-style
expression syntax.

   This module provides regular expression matching operations similar
to those found in Perl.  Regular expression pattern strings may not
contain null bytes, but can specify the null byte using the `\NUMBER'
notation.  Both patterns and strings to be searched can be Unicode
strings as well as 8-bit strings.  The `re' module is always available.

   Regular expressions use the backslash character (`\') to indicate
special forms or to allow special characters to be used without
invoking their special meaning.  This collides with Python's usage of
the same character for the same purpose in string literals; for
example, to match a literal backslash, one might have to write `'\\\\''
as the pattern string, because the regular expression must be `\\', and
each backslash must be expressed as `\\' inside a regular Python string
literal.

   The solution is to use Python's raw string notation for regular
expression patterns; backslashes are not handled in any special way in
a string literal prefixed with `r'.  So `r"\n"' is a two-character
string containing `\' and `n', while `"\n"' is a one-character string
containing a newline.  Usually patterns will be expressed in Python
code using this raw string notation.

   *Implementation note:* The `re' module has two distinct
implementations: `sre' is the default implementation and includes
Unicode support, but may run into stack limitations for some patterns.
Though this will be fixed for a future release of Python, the older
implementation (without Unicode support) is still available as the
`pre' module.

   See also:

   `Mastering Regular Expressions'{Book on regular expressions by
Jeffrey Friedl, published by O'Reilly.  The Python material in this
book dates from before the `re' module, but it covers writing good
regular expression patterns in great detail.}

* Menu:

* Regular Expression Syntax::
* Matching vs. Searching::
* Contents of Module re::
* Regular Expression Objects::
* Match Objects::

