This is Info file /home/pdm/tmp/Python-1.5.2p1/Doc/lib/python-lib.info,
produced by Makeinfo version 1.68 from the input file lib.texi.

   July 6, 1999			1.5.2


File: python-lib.info,  Node: Top,  Next: Front Matter,  Prev: (dir),  Up: (dir)

Python Library Reference
************************

* Menu:

* Front Matter::
* Introduction::
* Built-in Objects::
* Python Services::
* String Services::
* Miscellaneous Services::
* Generic Operating System Services::
* Optional Operating System Services::
* Unix Specific Services::
* Python Debugger::
* Python Profiler::
* Internet Protocols and Support::
* Internet Data Handling::
* Restricted Execution::
* Multimedia Services::
* Cryptographic Services::
* SGI IRIX Specific Services::
* SunOS Specific Services::
* MS Windows Specific Services::
* Undocumented Modules::
* Module Index::
* Class-Exception-Object Index::
* Function-Method-Variable Index::
* Miscellaneous Index::


File: python-lib.info,  Node: Front Matter,  Next: Introduction,  Prev: Top,  Up: Top

Front Matter
************

   Copyright (C) 1991-1995 by Stichting Mathematisch Centrum,
Amsterdam, The Netherlands.

   All Rights Reserved

   Permission to use, copy, modify, and distribute this software and its
documentation for any purpose and without fee is hereby granted,
provided that the above copyright notice appear in all copies and that
both that copyright notice and this permission notice appear in
supporting documentation, and that the names of Stichting Mathematisch
Centrum or CWI or Corporation for National Research Initiatives or CNRI
not be used in advertising or publicity pertaining to distribution of
the software without specific, written prior permission.

   While CWI is the initial source for this software, a modified version
is made available by the Corporation for National Research Initiatives
(CNRI) at the Internet address `ftp://ftp.python.org'.

   STICHTING MATHEMATISCH CENTRUM AND CNRI DISCLAIM ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH
CENTRUM OR CNRI BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL
DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
THIS SOFTWARE.

     Python is an extensible, interpreted, object-oriented programming
     language.  It supports a wide range of applications, from simple
     text processing scripts to interactive WWW browsers.

     While the *Python Reference Manual* describes the exact syntax and
     semantics of the language, it does not describe the standard
     library that is distributed with the language, and which greatly
     enhances its immediate usability.  This library contains built-in
     modules (written in C) that provide access to system functionality
     such as file I/O that would otherwise be inaccessible to Python
     programmers, as well as modules written in Python that provide
     standardized solutions for many problems that occur in everyday
     programming.  Some of these modules are explicitly designed to
     encourage and enhance the portability of Python programs.

     This library reference manual documents Python's standard library,
     as well as many optional library modules (which may or may not be
     available, depending on whether the underlying platform supports
     them and on the configuration choices made at compile time).  It
     also documents the standard types of the language and its built-in
     functions and exceptions, many of which are not or incompletely
     documented in the Reference Manual.

     This manual assumes basic knowledge about the Python language.
     For an informal introduction to Python, see the *Python Tutorial*;
     the *Python Reference Manual* remains the highest authority on
     syntactic and semantic questions.  Finally, the manual entitled
     *Extending and Embedding the Python Interpreter* describes how to
     add new extensions to Python and how to embed it in other
     applications.



File: python-lib.info,  Node: Introduction,  Next: Built-in Objects,  Prev: Front Matter,  Up: Top

Introduction
************

   The "Python library" contains several different kinds of components.

   It contains data types that would normally be considered part of the
"core" of a language, such as numbers and lists.  For these types, the
Python language core defines the form of literals and places some
constraints on their semantics, but does not fully define the
semantics.  (On the other hand, the language core does define syntactic
properties like the spelling and priorities of operators.)

   The library also contains built-in functions and exceptions --
objects that can be used by all Python code without the need of an
`import' statement.  Some of these are defined by the core language,
but many are not essential for the core semantics and are only
described here.

   The bulk of the library, however, consists of a collection of
modules.  There are many ways to dissect this collection.  Some modules
are written in C and built in to the Python interpreter; others are
written in Python and imported in source form.  Some modules provide
interfaces that are highly specific to Python, like printing a stack
trace; some provide interfaces that are specific to particular
operating systems, like socket I/O; others provide interfaces that are
specific to a particular application domain, like the World-Wide Web.
Some modules are avaiable in all versions and ports of Python; others
are only available when the underlying system supports or requires
them; yet others are available only when a particular configuration
option was chosen at the time when Python was compiled and installed.

   This manual is organized "from the inside out": it first describes
the built-in data types, then the built-in functions and exceptions,
and finally the modules, grouped in chapters of related modules.  The
ordering of the chapters as well as the ordering of the modules within
each chapter is roughly from most relevant to least important.

   This means that if you start reading this manual from the start, and
skip to the next chapter when you get bored, you will get a reasonable
overview of the available modules and application areas that are
supported by the Python library.  Of course, you don't *have* to read
it like a novel -- you can also browse the table of contents (in front
of the manual), or look for a specific function, module or term in the
index (in the back).  And finally, if you enjoy learning about random
subjects, you choose a random page number (see module `random') and
read a section or two.  Regardless of the order in which you read the
sections of this manual, it helps to start with chapter *Note Built-in
Objects::, "Built-in Types, Exceptions and Functions," as the remainder
of the manual assumes familiarity with this material.

   Let the show begin!


File: python-lib.info,  Node: Built-in Objects,  Next: Python Services,  Prev: Introduction,  Up: Top

Built-in Types, Exceptions and Functions
****************************************

   Names for built-in exceptions and functions are found in a separate
symbol table.  This table is searched last when the interpreter looks
up the meaning of a name, so local and global user-defined names can
override built-in names.  Built-in types are described together here
for easy reference.(1)

   The tables in this chapter document the priorities of operators by
listing them in order of ascending priority (within a table) and
grouping operators that have the same priority in the same box.  Binary
operators of the same priority group from left to right.  (Unary
operators group from right to left, but there you have no real choice.)
See Chapter 5 of the *Python Reference Manual* for the complete
picture on operator priorities.

* Menu:

* Built-in Types::
* Built-in Exceptions::
* Built-in Functions::

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

   (1)  Most descriptions sorely lack explanations of the exceptions
that may be raised -- this will be fixed in a future version of this
manual.


File: python-lib.info,  Node: Built-in Types,  Next: Built-in Exceptions,  Prev: Built-in Objects,  Up: Built-in Objects

Built-in Types
==============

   The following sections describe the standard types that are built
into the interpreter.  These are the numeric types, sequence types, and
several others, including types themselves.  There is no explicit
Boolean type; use integers instead.

   Some operations are supported by several object types; in particular,
all objects can be compared, tested for truth value, and converted to a
string (with the ``...`' notation).  The latter conversion is
implicitly used when an object is written by the `print' statement.

* Menu:

* Truth Value Testing::
* Boolean Operations::
* Comparisons::
* Numeric Types::
* Sequence Types::
* Mapping Types::
* Other Built-in Types::
* Special Attributes::


File: python-lib.info,  Node: Truth Value Testing,  Next: Boolean Operations,  Prev: Built-in Types,  Up: Built-in Types

Truth Value Testing
-------------------

   Any object can be tested for truth value, for use in an `if' or
`while' condition or as operand of the Boolean operations below.  The
following values are considered false:

   * `None'

   * zero of any numeric type, e.g., `0', `0L', `0.0'.

   * any empty sequence, e.g., `''', `()', `[]'.

   * any empty mapping, e.g., `{}'.

   * instances of user-defined classes, if the class defines a
     `__nonzero__()' or `__len__()' method, when that method returns
     zero.

   All other values are considered true -- so objects of many types are
always true.

   Operations and built-in functions that have a Boolean result always
return `0' for false and `1' for true, unless otherwise stated.
(Important exception: the Boolean operations `or' and `and' always
return one of their operands.)


File: python-lib.info,  Node: Boolean Operations,  Next: Comparisons,  Prev: Truth Value Testing,  Up: Built-in Types

Boolean Operations
------------------

   These are the Boolean operations, ordered by ascending priority:

Operation                Result                   Notes                    
------                   -----                    -----                    
X or Y                   if X is false, then Y,   (1)                      
                         else X                                            
X and Y                  if X is false, then X,   (1)                      
                         else Y                                            
not X                    if X is false, then      (2)                      
                         `1', else `0'                                     

Notes:

`(1)'
     These only evaluate their second argument if needed for their
     outcome.

`(2)'
     `not' has a lower priority than non-Boolean operators, so e.g.
     `not a == b' is interpreted as `not(a == b)', and `a == not b' is
     a syntax error.


File: python-lib.info,  Node: Comparisons,  Next: Numeric Types,  Prev: Boolean Operations,  Up: Built-in Types

Comparisons
-----------

   Comparison operations are supported by all objects.  They all have
the same priority (which is higher than that of the Boolean operations).
Comparisons can be chained arbitrarily, e.g. `x < y <= z' is equivalent
to `x < y and y <= z', except that `y' is evaluated only once (but in
both cases `z' is not evaluated at all when `x < y' is found to be
false).

   This table summarizes the comparison operations:

Operation                Meaning                  Notes                    
------                   -----                    -----                    
<                        strictly less than                                
<=                       less than or equal                                
>                        strictly greater than                             
>=                       greater than or equal                             
==                       equal                                             
<>                       not equal                (1)                      
!=                       not equal                (1)                      
is                       object identity                                   
is not                   negated object identity                           

Notes:

`(1)'
     `<>' and `!=' are alternate spellings for the same operator.  (I
     couldn't choose between ABC and C! :-)

   Objects of different types, except different numeric types, never
compare equal; such objects are ordered consistently but arbitrarily
(so that sorting a heterogeneous array yields a consistent result).
Furthermore, some types (e.g., windows) support only a degenerate
notion of comparison where any two objects of that type are unequal.
Again, such objects are ordered arbitrarily but consistently.

   (Implementation note: objects of different types except numbers are
ordered by their type names; objects of the same types that don't
support proper comparison are ordered by their address.)

   Two more operations with the same syntactic priority, `in' and `not
in', are supported only by sequence types (below).


File: python-lib.info,  Node: Numeric Types,  Next: Sequence Types,  Prev: Comparisons,  Up: Built-in Types

Numeric Types
-------------

   There are four numeric types: "plain integers", "long integers",
"floating point numbers", and "complex numbers".  Plain integers (also
just called "integers") are implemented using `long' in C, which gives
them at least 32 bits of precision.  Long integers have unlimited
precision.  Floating point numbers are implemented using `double' in C.
All bets on their precision are off unless you happen to know the
machine you are working with.

   Complex numbers have a real and imaginary part, which are both
implemented using `double' in C.  To extract these parts from a complex
number Z, use `Z.real' and `Z.imag'.

   Numbers are created by numeric literals or as the result of built-in
functions and operators.  Unadorned integer literals (including hex and
octal numbers) yield plain integers.  Integer literals with an `L' or
`l' suffix yield long integers (`L' is preferred because `1l' looks too
much like eleven!).  Numeric literals containing a decimal point or an
exponent sign yield floating point numbers.  Appending `j' or `J' to a
numeric literal yields a complex number.

   Python fully supports mixed arithmetic: when a binary arithmetic
operator has operands of different numeric types, the operand with the
"smaller" type is converted to that of the other, where plain integer
is smaller than long integer is smaller than floating point is smaller
than complex.  Comparisons between numbers of mixed type use the same
rule.(1) The functions `int()', `long()', `float()', and `complex()'
can be used to coerce numbers to a specific type.

   All numeric types support the following operations, sorted by
ascending priority (operations in the same box have the same priority;
all numeric operations have a higher priority than comparison
operations):

Operation                Result                   Notes                    
------                   -----                    -----                    
X + Y                    sum of X and Y                                    
X - Y                    difference of X and Y                             
X * Y                    product of X and Y                                
X / Y                    quotient of X and Y      (1)                      
X %{} Y                  remainder of `X / Y'                              
-X                       X negated                                         
+X                       X unchanged                                       
abs(X)                   absolute value or                                 
                         magnitude of X                                    
int(X)                   X converted to integer   (2)                      
long(X)                  X converted to long      (2)                      
                         integer                                           
float(X)                 X converted to floating                           
                         point                                             
complex(RE,IM)           a complex number with                             
                         real part RE, imaginary                           
                         part IM.  IM defaults                             
                         to zero.                                          
C.conjugate()            conjugate of the                                  
                         complex number C                                  
divmod(X, Y)             the pair `(X / Y, X %{}  (3)                      
                         Y)'                                               
pow(X, Y)                X to the power Y                                  
X ** Y                   X to the power Y                                  

Notes:
`(1)'
     For (plain or long) integer division, the result is an integer.
     The result is always rounded towards minus infinity: 1/2 is 0,
     (-1)/2 is -1, 1/(-2) is -1, and (-1)/(-2) is 0.

`(2)'
     Conversion from floating point to (long or plain) integer may
     round or truncate as in C; see functions `floor()' and `ceil()' in
     module `math' for well-defined conversions.

`(3)'
     See the section on built-in functions for an exact definition.

* Menu:

* Bit-string Operations::

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

   (1)  As a consequence, the list `[1, 2]' is considered equal to
`[1.0, 2.0]', and similar for tuples.


File: python-lib.info,  Node: Bit-string Operations,  Prev: Numeric Types,  Up: Numeric Types

Bit-string Operations on Integer Types
......................................

   Plain and long integer types support additional operations that make
sense only for bit-strings.  Negative numbers are treated as their 2's
complement value (for long integers, this assumes a sufficiently large
number of bits that no overflow occurs during the operation).

   The priorities of the binary bit-wise operations are all lower than
the numeric operations and higher than the comparisons; the unary
operation `~' has the same priority as the other unary numeric
operations (`+' and `-').

   This table lists the bit-string operations sorted in ascending
priority (operations in the same box have the same priority):

Operation                Result                   Notes                    
------                   -----                    -----                    
X | Y                    bitwise "or" of X and Y                           
X ^{} Y                  bitwise "exclusive or"                            
                         of X and Y                                        
X &{} Y                  bitwise "and" of X and                            
                         Y                                                 
X << N                   X shifted left by N      (1), (2)                 
                         bits                                              
X >> N                   X shifted right by N     (1), (3)                 
                         bits                                              
~X                       the bits of X inverted                            

Notes:
`(1)'
     Negative shift counts are illegal and cause a `ValueError' to be
     raised.

`(2)'
     A left shift by N bits is equivalent to multiplication by `pow(2,
     N)' without overflow check.

`(3)'
     A right shift by N bits is equivalent to division by `pow(2, N)'
     without overflow check.


File: python-lib.info,  Node: Sequence Types,  Next: Mapping Types,  Prev: Numeric Types,  Up: Built-in Types

Sequence Types
--------------

   There are three sequence types: strings, lists and tuples.

   Strings literals are written in single or double quotes: `'xyzzy'',
`"frobozz"'.  See Chapter 2 of the *Python Reference Manual* for more
about string literals.  Lists are constructed with square brackets,
separating items with commas: `[a, b, c]'.  Tuples are constructed by
the comma operator (not within square brackets), with or without
enclosing parentheses, but an empty tuple must have the enclosing
parentheses, e.g., `a, b, c' or `()'.  A single item tuple must have a
trailing comma, e.g., `(d,)'.

   Sequence types support the following operations.  The `in' and `not
in' operations have the same priorities as the comparison operations.
The `+' and `*' operations have the same priority as the corresponding
numeric operations.(1)

   This table lists the sequence operations sorted in ascending priority
(operations in the same box have the same priority).  In the table, S
and T are sequences of the same type; N, I and J are integers:

Operation                Result                   Notes                    
------                   -----                    -----                    
X in S                   `1' if an item of S is                            
                         equal to X, else `0'                              
X not in S               `0' if an item of S is                            
                         equal to X, else `1'                              
S + T                    the concatenation of S                            
                         and T                                             
S * N, N * S             N copies of S            (3)                      
                         concatenated                                      
S[I]                     I'th item of S, origin   (1)                      
                         0                                                 
S[I:J]                   slice of S from I to J   (1), (2)                 
len(S)                   length of S                                       
min(S)                   smallest item of S                                
max(S)                   largest item of S                                 

Notes:

`(1)'
     If I or J is negative, the index is relative to the end of the
     string, i.e., `len(S) + I' or `len(S) + J' is substituted.  But
     note that `-0' is still `0'.

`(2)'
     The slice of S from I to J is defined as the sequence of items
     with index K such that `I <= K < J'.  If I or J is greater than
     `len(S)', use `len(S)'.  If I is omitted, use `0'.  If J is
     omitted, use `len(S)'.  If I is greater than or equal to J, the
     slice is empty.

`(3)'
     Values of N less than `0' are treated as `0' (which yields an
     empty sequence of the same type as S).

* Menu:

* More String Operations::
* Mutable Sequence Types::

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

   (1) They must have since the parser can't tell the type of the
operands.


File: python-lib.info,  Node: More String Operations,  Next: Mutable Sequence Types,  Prev: Sequence Types,  Up: Sequence Types

More String Operations
......................

   String objects have one unique built-in operation: the `%' operator
(modulo) with a string left argument interprets this string as a C
`sprintf()' format string to be applied to the right argument, and
returns the string resulting from this formatting operation.

   The right argument should be a tuple with one item for each argument
required by the format string; if the string requires a single
argument, the right argument may also be a single non-tuple object.(1)
The following format characters are understood: `%', `c', `s', `i',
`d', `u', `o', `x', `X', `e', `E', `f', `g', `G'.  Width and precision
may be a `*' to specify that an integer argument specifies the actual
width or precision.  The flag characters `-', `+', blank, `#' and `0'
are understood.  The size specifiers `h', `l' or `L' may be present but
are ignored.  The `%s' conversion takes any Python object and converts
it to a string using `str()' before formatting it.  The ANSI features
`%p' and `%n' are not supported.  Since Python strings have an explicit
length, `%s' conversions don't assume that `'\0'' is the end of the
string.

   For safety reasons, floating point precisions are clipped to 50;
`%f' conversions for numbers whose absolute value is over 1e25 are
replaced by `%g' conversions.(2) All other errors raise exceptions.

   If the right argument is a dictionary (or any kind of mapping), then
the formats in the string must have a parenthesized key into that
dictionary inserted immediately after the `%' character, and each
format formats the corresponding entry from the mapping.  For example:

     >>> count = 2
     >>> language = 'Python'
     >>> print '%(language)s has %(count)03d quote types.' % vars()
     Python has 002 quote types.

   In this case no `*' specifiers may occur in a format (since they
require a sequential parameter list).

   Additional string operations are defined in standard module `string'
and in built-in module `re'.

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

   (1) A tuple object in this case should be a singleton.

   (2)  These numbers are fairly arbitrary.  They are intended to avoid
printing endless strings of meaningless digits without hampering
correct use and without having to know the exact precision of floating
point values on a particular machine.


File: python-lib.info,  Node: Mutable Sequence Types,  Prev: More String Operations,  Up: Sequence Types

Mutable Sequence Types
......................

   List objects support additional operations that allow in-place
modification of the object.  These operations would be supported by
other mutable sequence types (when added to the language) as well.
Strings and tuples are immutable sequence types and such objects cannot
be modified once created.  The following operations are defined on
mutable sequence types (where X is an arbitrary object):

Operation                Result                   Notes                    
------                   -----                    -----                    
S[I] = X                 item I of S is replaced                           
                         by X                                              
S[I:J] = T               slice of S from I to J                            
                         is replaced by T                                  
del S[I:J]               same as `S[I:J] = []'                             
S.append(X)              same as                                           
                         `S[len(S):len(S)] =                               
                         [X]'                                              
S.extend(X)              same as                  (5)                      
                         `S[len(S):len(S)] = X'                            
S.count(X)               return number of I's                              
                         for which `S[I] == X'                             
S.index(X)               return smallest I such   (1)                      
                         that `S[I] == X'                                  
S.insert(I, X)           same as `S[I:I] = [X]'                            
                         if `I >= 0'                                       
S.pop([I])               same as `X = S[I]; del   (4)                      
                         S[I]; return X'                                   
S.remove(X)              same as `del             (1)                      
                         S[S.index(X)]'                                    
S.reverse()              reverses the items of S  (3)                      
                         in place                                          
S.sort([CMPFUNC])        sort the items of S in   (2), (3)                 
                         place                                             

   {types}

Notes:
`(1)'
     Raises an exception when X is not found in S.

`(2)'
     The `sort()' method takes an optional argument specifying a
     comparison function of two arguments (list items) which should
     return `-1', `0' or `1' depending on whether the first argument is
     considered smaller than, equal to, or larger than the second
     argument.  Note that this slows the sorting process down
     considerably; e.g. to sort a list in reverse order it is much
     faster to use calls to the methods `sort()' and `reverse()' than
     to use the built-in function `sort()' with a comparison function
     that reverses the ordering of the elements.

`(3)'
     The `sort()' and `reverse()' methods modify the list in place for
     economy of space when sorting or reversing a large list.  They
     don't return the sorted or reversed list to remind you of this
     side effect.

`(4)'
     The `pop()' method is experimental and not supported by other
     mutable sequence types than lists.  The optional argument I
     defaults to `-1', so that by default the last item is removed and
     returned.

`(5)'
     Raises an exception when X is not a list object.  The `extend()'
     method is experimental and not supported by mutable types other
     than lists.


File: python-lib.info,  Node: Mapping Types,  Next: Other Built-in Types,  Prev: Sequence Types,  Up: Built-in Types

Mapping Types
-------------

   A "mapping" object maps values of one type (the key type) to
arbitrary objects.  Mappings are mutable objects.  There is currently
only one standard mapping type, the "dictionary".  A dictionary's keys
are almost arbitrary values.  The only types of values not acceptable as
keys are values containing lists or dictionaries or other mutable types
that are compared by value rather than by object identity.  Numeric
types used for keys obey the normal rules for numeric comparison: if
two numbers compare equal (e.g. `1' and `1.0') then they can be used
interchangeably to index the same dictionary entry.

   Dictionaries are created by placing a comma-separated list of `KEY:
VALUE' pairs within braces, for example: `{'jack': 4098, 'sjoerd':
4127}' or `{4098: 'jack', 4127: 'sjoerd'}'.

   The following operations are defined on mappings (where A and B are
mappings, K is a key, and V and X are arbitrary objects):

Operation                Result                   Notes                    
------                   -----                    -----                    
len(A)                   the number of items in                            
                         A                                                 
A[K]                     the item of A with key   (1)                      
                         K                                                 
A[K] = X                 set `A[K]' to X                                   
del A[K]                 remove `A[K]' from A     (1)                      
A.clear()                remove all items from                             
                         `a'                                               
A.copy()                 a (shallow) copy of `a'                           
A.has_key(K)             `1' if A has a key K,                             
                         else `0'                                          
A.items()                a copy of A's list of    (2)                      
                         (KEY, VALUE) pairs                                
A.keys()                 a copy of A's list of    (2)                      
                         keys                                              
A.update(B)              `for k, v in B.items():  (3)                      
                         A[k] = v'                                         
A.values()               a copy of A's list of    (2)                      
                         values                                            
A.get(K[, X])            `A[K]' if                (4)                      
                         `A.has_key(K)', else X                            

Notes:
`(1)'
     Raises a `KeyError' exception if K is not in the map.

`(2)'
     Keys and values are listed in random order.

`(3)'
     B must be of the same type as A.

`(4)'
     Never raises an exception if K is not in the map, instead it
     returns F.  F is optional; when F is not provided and K is not in
     the map, `None' is returned.


File: python-lib.info,  Node: Other Built-in Types,  Next: Special Attributes,  Prev: Mapping Types,  Up: Built-in Types

Other Built-in Types
--------------------

   The interpreter supports several other kinds of objects.  Most of
these support only one or two operations.

* Menu:

* Modules::
* Classes and Instances::
* Functions::
* Methods::
* Code Objects::
* Type Objects::
* Null Object::
* Ellipsis Object::
* File Objectsfile::
* Internal Objects::


File: python-lib.info,  Node: Modules,  Next: Classes and Instances,  Prev: Other Built-in Types,  Up: Other Built-in Types

Modules
.......

   The only special operation on a module is attribute access:
`M.NAME', where M is a module and NAME accesses a name defined in M's
symbol table.  Module attributes can be assigned to.  (Note that the
`import' statement is not, strictly speaking, an operation on a module
object; `import FOO' does not require a module object named FOO to
exist, rather it requires an (external) *definition* for a module named
FOO somewhere.)

   A special member of every module is `__dict__'.  This is the
dictionary containing the module's symbol table.  Modifying this
dictionary will actually change the module's symbol table, but direct
assignment to the `__dict__' attribute is not possible (i.e., you can
write `M.__dict__['a'] = 1', which defines `M.a' to be `1', but you
can't write `M.__dict__ = {}'.

   Modules built into the interpreter are written like this: `<module
'sys' (built-in)>'.  If loaded from a file, they are written as
`<module 'os' from '/usr/local/lib/python1.5/os.pyc'>'.


File: python-lib.info,  Node: Classes and Instances,  Next: Functions,  Prev: Modules,  Up: Other Built-in Types

Classes and Class Instances
...........................

   See Chapters 3 and 7 of the *Python Reference Manual* for these.


File: python-lib.info,  Node: Functions,  Next: Methods,  Prev: Classes and Instances,  Up: Other Built-in Types

Functions
.........

   Function objects are created by function definitions.  The only
operation on a function object is to call it: `FUNC(ARGUMENT-LIST)'.

   There are really two flavors of function objects: built-in functions
and user-defined functions.  Both support the same operation (to call
the function), but the implementation is different, hence the different
object types.

   The implementation adds two special read-only attributes:
`F.func_code' is a function's "code object" (see below) and
`F.func_globals' is the dictionary used as the function's global name
space (this is the same as `M.__dict__' where M is the module in which
the function F was defined).


File: python-lib.info,  Node: Methods,  Next: Code Objects,  Prev: Functions,  Up: Other Built-in Types

Methods
.......

   Methods are functions that are called using the attribute notation.
There are two flavors: built-in methods (such as `append()' on lists)
and class instance methods.  Built-in methods are described with the
types that support them.

   The implementation adds two special read-only attributes to class
instance methods: `M.im_self' is the object on which the method
operates, and `M.im_func' is the function implementing the method.
Calling `M(ARG-1, ARG-2, ..., ARG-N)' is completely equivalent to
calling `M.im_func(M.im_self, ARG-1, ARG-2, ..., ARG-N)'.

   See the *Python Reference Manual* for more information.


File: python-lib.info,  Node: Code Objects,  Next: Type Objects,  Prev: Methods,  Up: Other Built-in Types

Code Objects
............

   Code objects are used by the implementation to represent
"pseudo-compiled" executable Python code such as a function body.  They
differ from function objects because they don't contain a reference to
their global execution environment.  Code objects are returned by the
built-in `compile()' function and can be extracted from function
objects through their `func_code' attribute.

   A code object can be executed or evaluated by passing it (instead of
a source string) to the `exec' statement or the built-in `eval()'
function.

   See the *Python Reference Manual* for more information.


File: python-lib.info,  Node: Type Objects,  Next: Null Object,  Prev: Code Objects,  Up: Other Built-in Types

Type Objects
............

   Type objects represent the various object types.  An object's type is
accessed by the built-in function `type()'.  There are no special
operations on types.  The standard module `types' defines names for all
standard built-in types.

   Types are written like this: `<type 'int'>'.


File: python-lib.info,  Node: Null Object,  Next: Ellipsis Object,  Prev: Type Objects,  Up: Other Built-in Types

The Null Object
...............

   This object is returned by functions that don't explicitly return a
value.  It supports no special operations.  There is exactly one null
object, named `None' (a built-in name).

   It is written as `None'.


File: python-lib.info,  Node: Ellipsis Object,  Next: File Objectsfile,  Prev: Null Object,  Up: Other Built-in Types

The Ellipsis Object
...................

   This object is used by extended slice notation (see the *Python
Reference Manual*).  It supports no special operations.  There is
exactly one ellipsis object, named `Ellipsis' (a built-in name).

   It is written as `Ellipsis'.


File: python-lib.info,  Node: File Objectsfile,  Next: Internal Objects,  Prev: Ellipsis Object,  Up: Other Built-in Types

File Objects...........

   File objects are implemented using C's `stdio' package and can be
created with the built-in function `open()' described section *Note
traceback::, "Built-in Functions."  They are also returned by some
other built-in functions and methods, e.g., `posix.popen()' and
`posix.fdopen()' and the `makefile()' method of socket objects.

   When a file operation fails for an I/O-related reason, the exception
`IOError' is raised.  This includes situations where the operation is
not defined for some reason, like `seek()' on a tty device or writing a
file opened for reading.

   Files have the following methods:

`close()'
     Close the file.  A closed file cannot be read or written anymore.

`flush()'
     Flush the internal buffer, like `stdio''s `fflush()'.

`isatty()'
     Return `1' if the file is connected to a tty(-like) device, else
     `0'.

`fileno()'
     Return the integer "file descriptor" that is used by the underlying
     implementation to request I/O operations from the operating system.
     This can be useful for other, lower level interfaces that use file
     descriptors, e.g. module `fcntl' or `os.read()' and friends.

`read([size])'
     Read at most SIZE bytes from the file (less if the read hits `EOF'
     before obtaining SIZE bytes).  If the SIZE argument is negative or
     omitted, read all data until `EOF' is reached.  The bytes are
     returned as a string object.  An empty string is returned when
     `EOF' is encountered immediately.  (For certain files, like ttys,
     it makes sense to continue reading after an `EOF' is hit.)  Note
     that this method may call the underlying C function `fread()' more
     than once in an effort to acquire as close to SIZE bytes as
     possible.

`readline([size])'
     Read one entire line from the file.  A trailing newline character
     is kept in the string(1) (but may be absent when a file ends with
     an incomplete line).  If the SIZE argument is present and
     non-negative, it is a maximum byte count (including the trailing
     newline) and an incomplete line may be returned.  An empty string
     is returned when `EOF' is hit immediately.  Note: unlike `stdio''s
     `fgets()', the returned string contains null characters (`'\0'')
     if they occurred in the input.

`readlines([sizehint])'
     Read until `EOF' using `readline()' and return a list containing
     the lines thus read.  If the optional SIZEHINT argument is
     present, instead of reading up to `EOF', whole lines totalling
     approximately SIZEHINT bytes (possibly after rounding up to an
     internal buffer size) are read.

`seek(offset[, whence])'
     Set the file's current position, like `stdio''s `fseek()'.  The
     WHENCE argument is optional and defaults to `0' (absolute file
     positioning); other values are `1' (seek relative to the current
     position) and `2' (seek relative to the file's end).  There is no
     return value.

`tell()'
     Return the file's current position, like `stdio''s `ftell()'.

`truncate([size])'
     Truncate the file's size.  If the optional size argument present,
     the file is truncated to (at most) that size.  The size defaults
     to the current position.  Availability of this function depends on
     the operating system version (e.g., not all UNIX versions support
     this operation).

`write(str)'
     Write a string to the file.  There is no return value.  Note: due
     to buffering, the string may not actually show up in the file until
     the `flush()' or `close()' method is called.

`writelines(list)'
     Write a list of strings to the file.  There is no return value.
     (The name is intended to match `readlines()'; `writelines()' does
     not add line separators.)

   File objects also offer the following attributes:

`closed'
     Boolean indicating the current state of the file object.  This is a
     read-only attribute; the `close()' method changes the value.

`mode'
     The I/O mode for the file.  If the file was created using the
     `open()' built-in function, this will be the value of the MODE
     parameter.  This is a read-only attribute.

`name'
     If the file object was created using `open()', the name of the
     file.  Otherwise, some string that indicates the source of the
     file object, of the form `<...>'.  This is a read-only attribute.

`softspace'
     Boolean that indicates whether a space character needs to be
     printed before another value when using the `print' statement.
     Classes that are trying to simulate a file object should also have
     a writable `softspace' attribute, which should be initialized to
     zero.  This will be automatic for classes implemented in Python;
     types implemented in C will have to provide a writable `softspace'
     attribute.

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

   (1)  The advantage of leaving the newline on is that an empty string
can be returned to mean `EOF' without being ambiguous.  Another
advantage is that (in cases where it might matter, e.g. if you  want to
make an exact copy of a file while scanning its lines)  you can tell
whether the last line of a file ended in a newline or not (yes this
happens!).


File: python-lib.info,  Node: Internal Objects,  Prev: File Objectsfile,  Up: Other Built-in Types

Internal Objects
................

   See the *Python Reference Manual* for this information.  It
describes code objects, stack frame objects, traceback objects, and
slice objects.


File: python-lib.info,  Node: Special Attributes,  Prev: Other Built-in Types,  Up: Built-in Types

Special Attributes
------------------

   The implementation adds a few special read-only attributes to several
object types, where they are relevant:

`__dict__'
     A dictionary of some sort used to store an object's (writable)
     attributes.

`__methods__'
     List of the methods of many built-in object types, e.g.,
     `[].__methods__' yields `['append', 'count', 'index', 'insert',
     'pop', 'remove', 'reverse', 'sort']'.

`__members__'
     Similar to `__methods__', but lists data attributes.

`__class__'
     The class to which a class instance belongs.

`__bases__'
     The tuple of base classes of a class object.

