15.14 Standard Module FrameWork

node231.html
node203.html
node229.html
node1.html
node270.html
---
# 15.14 Standard Module FrameWork
The FrameWork module contains classes that together provide a
framework for an interactive Macintosh application. The programmer
builds an application by creating subclasses that override various
methods of the bases classes, thereby implementing the functionality
wanted. Overriding functionality can often be done on various
different levels, i.e. to handle clicks in a single dialog window in a
non-standard way it is not necessary to override the complete event
handling.
The FrameWork is still very much work-in-progress, and the
documentation describes only the most important functionality, and not
in the most logical manner at that. Examine the source or the examples
for more details.
The FrameWork module defines the following functions:
---
- Application objects (node231.html#SECTION00161410000000000000000)
Window Objects (node232.html#SECTION00161420000000000000000)
ControlsWindow Object (node233.html#SECTION00161430000000000000000)
ScrolledWindow Object (node234.html#SECTION00161440000000000000000)
DialogWindow Objects (node235.html#SECTION00161450000000000000000)
---
node231.html
node203.html
node229.html
node1.html
node270.html
guido@python.org


Application objects

node232.html
node230.html
node230.html
node1.html
node270.html
---
## Application objects
Application objects have the following methods, among others:
---
node232.html
node230.html
node230.html
node1.html
node270.html
guido@python.org


Window Objects

node233.html
node230.html
node231.html
node1.html
node270.html
---
## Window Objects
Window objects have the following methods, among others:
---
guido@python.org


ControlsWindow Object

node234.html
node230.html
node232.html
node1.html
node270.html
---
## ControlsWindow Object
ControlsWindow objects have the following methods besides those of
Window objects:
---
guido@python.org


ScrolledWindow Object

node235.html
node230.html
node233.html
node1.html
node270.html
---
## ScrolledWindow Object
ScrolledWindow objects are ControlsWindow objects with the following
extra methods:
---
guido@python.org


DialogWindow Objects

node236.html
node230.html
node234.html
node1.html
node270.html
---
## DialogWindow Objects
DialogWindow objects have the following methods besides those of
Window objects:
---
guido@python.org


15.15 Standard Module MiniAEFrame

node237.html
node203.html
node235.html
node1.html
node270.html
---
# 15.15 Standard Module MiniAEFrame
The module MiniAEFrame provides a framework for an application
that can function as an OSA server, i.e. receive and process
AppleEvents. It can be used in conjunction with FrameWork or
standalone.
This module is temporary, it will eventually be replaced by a module
that handles argument names better and possibly automates making your
application scriptable.
The MiniAEFrame module defines the following classes:
---
- AEServer Objects (node237.html#SECTION00161510000000000000000)
---
guido@python.org


AEServer Objects

node238.html
node236.html
node236.html
node1.html
node270.html
---
## AEServer Objects
Note that there are some serious problems with the current
design. AppleEvents which have non-identifier 4-char designators for
arguments are not implementable, and it is not possible to return an
error to the originator. This will be addressed in a future release.
---
guido@python.org


16 SGI IRIX Specific Services

node239.html
lib.html
node237.html
node1.html
node270.html
---
# 16 SGI IRIX Specific Services
The modules described in this chapter provide interfaces to features
that are unique to SGI's IRIX operating system (versions 4 and 5).
---
- 16.1 Built-in Module al (node239.html#SECTION0017100000000000000000)
- Configuration Objects (node240.html#SECTION0017110000000000000000)
Port Objects (node241.html#SECTION0017120000000000000000)
16.2 Standard Module AL (node242.html#SECTION0017200000000000000000)
16.3 Built-in Module cd (node243.html#SECTION0017300000000000000000)
16.4 Built-in Module fl (node244.html#SECTION0017400000000000000000)
- Functions Defined in Module fl (node245.html#SECTION0017410000000000000000)
Form Objects (node246.html#SECTION0017420000000000000000)
FORMS Objects (node247.html#SECTION0017430000000000000000)
16.5 Standard Module FL (node248.html#SECTION0017500000000000000000)
16.6 Standard Module flp (node249.html#SECTION0017600000000000000000)
16.7 Built-in Module fm (node250.html#SECTION0017700000000000000000)
16.8 Built-in Module gl (node251.html#SECTION0017800000000000000000)
16.9 Standard Modules GL and DEVICE (node252.html#SECTION0017900000000000000000)
16.10 Built-in Module imgfile (node253.html#SECTION00171000000000000000000)
---
guido@python.org


16.1 Built-in Module al

node240.html
node238.html
node238.html
node1.html
node270.html
---
# 16.1 Built-in Module al
This module provides access to the audio facilities of the SGI Indy
and Indigo workstations. See section 3A of the IRIX man pages for
details. You'll need to read those man pages to understand what these
functions do! Some of the functions are not available in IRIX
releases before 4.0.5. Again, see the manual to check whether a
specific function is available on your platform.
All functions and methods defined in this module are equivalent to
the C functions with `AL' prefixed to their name.
Symbolic constants from the C header file `<audio.h>' are defined
in the standard module AL, see below.
Warning: the current version of the audio library may dump core
when bad argument values are passed rather than returning an error
status. Unfortunately, since the precise circumstances under which
this may happen are undocumented and hard to check, the Python
interface can provide no protection against this kind of problems.
(One example is specifying an excessive queue size -- there is no
documented upper limit.)
The module defines the following functions:
---
- Configuration Objects (node240.html#SECTION0017110000000000000000)
Port Objects (node241.html#SECTION0017120000000000000000)
---
node240.html
node238.html
node238.html
node1.html
node270.html
guido@python.org


Special Attributes

node25.html
node4.html
node23.html
node1.html
node270.html
---
## Special Attributes
The implementation adds a few special read-only attributes to several
object types, where they are relevant:
- x.__dict__ is a dictionary of some sort used to store an
object's (writable) attributes;x.__methods__ lists the methods of many built-in object types,
e.g., [].__methods__ yields
['append', 'count', 'index', 'insert', 'remove', 'reverse', 'sort'];x.__members__ lists data attributes;x.__class__ is the class to which a class instance belongs;x.__bases__ is the tuple of base classes of a class object.
---
guido@python.org


Configuration Objects

node241.html
node239.html
node239.html
node1.html
node270.html
---
## Configuration Objects
Configuration objects (returned by al.newconfig() have the
following methods:
---
guido@python.org


Port Objects

node242.html
node239.html
node240.html
node1.html
node270.html
---
## Port Objects
Port objects (returned by al.openport() have the following
methods:
---
guido@python.org


16.2 Standard Module AL

node243.html
node238.html
node241.html
node1.html
node270.html
---
# 16.2 Standard Module AL
This module defines symbolic constants needed to use the built-in
module al (see above); they are equivalent to those defined in
the C header file `<audio.h>' except that the name prefix
`AL_' is omitted. Read the module source for a complete list of
the defined names. Suggested use:
```text
import al
from AL import *
```
---
guido@python.org


16.3 Built-in Module cd

node244.html
node238.html
node242.html
node1.html
node270.html
---
# 16.3 Built-in Module cd
This module provides an interface to the Silicon Graphics CD library.
It is available only on Silicon Graphics systems.
The way the library works is as follows. A program opens the CD-ROM
device with cd.open() and creates a parser to parse the data
from the CD with cd.createparser(). The object returned by
cd.open() can be used to read data from the CD, but also to get
status information for the CD-ROM device, and to get information about
the CD, such as the table of contents. Data from the CD is passed to
the parser, which parses the frames, and calls any callback
functions that have previously been added.
An audio CD is divided into tracks or programs (the terms
are used interchangeably). Tracks can be subdivided into
indices. An audio CD contains a table of contents which
gives the starts of the tracks on the CD. Index 0 is usually the
pause before the start of a track. The start of the track as given by
the table of contents is normally the start of index 1.
Positions on a CD can be represented in two ways. Either a frame
number or a tuple of three values, minutes, seconds and frames. Most
functions use the latter representation. Positions can be both
relative to the beginning of the CD, and to the beginning of the
track.
Module cd defines the following functions and constants:
The module defines the following variables:
The following variables are states as returned by getstatus:
Player objects (returned by cd.open()) have the following
methods:
Parser objects (returned by cd.createparser()) have the
following methods:
---
node244.html
node238.html
node242.html
node1.html
node270.html
guido@python.org


16.4 Built-in Module fl

node245.html
node238.html
node243.html
node1.html
node270.html
---
# 16.4 Built-in Module fl
This module provides an interface to the FORMS Library by Mark
Overmars. The source for the library can be retrieved by anonymous
ftp from host `ftp.cs.ruu.nl', directory `SGI/FORMS'. It
was last tested with version 2.0b.
Most functions are literal translations of their C equivalents,
dropping the initial `fl_' from their name. Constants used by
the library are defined in module FL described below.
The creation of objects is a little different in Python than in C:
instead of the `current form' maintained by the library to which new
FORMS objects are added, all functions that add a FORMS object to a
form are methods of the Python object representing the form.
Consequently, there are no Python equivalents for the C functions
fl_addto_form and fl_end_form, and the equivalent of
fl_bgn_form is called fl.make_form.
Watch out for the somewhat confusing terminology: FORMS uses the word
object for the buttons, sliders etc. that you can place in a form.
In Python, `object' means any value. The Python interface to FORMS
introduces two new Python object types: form objects (representing an
entire form) and FORMS objects (representing one button, slider etc.).
Hopefully this isn't too confusing...
There are no `free objects' in the Python interface to FORMS, nor is
there an easy way to add object classes written in Python. The FORMS
interface to GL event handling is available, though, so you can mix
FORMS with pure GL windows.
Please note: importing fl implies a call to the GL function
foreground() and to the FORMS routine fl_init().
---
- Functions Defined in Module fl (node245.html#SECTION0017410000000000000000)
Form Objects (node246.html#SECTION0017420000000000000000)
FORMS Objects (node247.html#SECTION0017430000000000000000)
---
guido@python.org


Functions Defined in Module fl

node246.html
node244.html
node244.html
node1.html
node270.html
---
## Functions Defined in Module fl
Module fl defines the following functions. For more information
about what they do, see the description of the equivalent C function
in the FORMS documentation:
---
node246.html
node244.html
node244.html
node1.html
node270.html
guido@python.org


Form Objects

node247.html
node244.html
node245.html
node1.html
node270.html
---
## Form Objects
Form objects (returned by fl.make_form() above) have the
following methods. Each method corresponds to a C function whose name
is prefixed with `fl_'; and whose first argument is a form
pointer; please refer to the official FORMS documentation for
descriptions.
All the `add_...' functions return a Python object representing
the FORMS object. Methods of FORMS objects are described below. Most
kinds of FORMS object also have some methods specific to that kind;
these methods are listed here.
Form objects have the following data attributes; see the FORMS
documentation:
Name | Type | Meaning
---
node247.html
node244.html
node245.html
node1.html
node270.html
guido@python.org


FORMS Objects

node248.html
node244.html
node246.html
node1.html
node270.html
---
## FORMS Objects
Besides methods specific to particular kinds of FORMS objects, all
FORMS objects also have the following methods:
FORMS objects have these data attributes; see the FORMS documentation:
Name | Type | Meaning
---
guido@python.org


16.5 Standard Module FL

node249.html
node238.html
node247.html
node1.html
node270.html
---
# 16.5 Standard Module FL
This module defines symbolic constants needed to use the built-in
module fl (see above); they are equivalent to those defined in
the C header file `<forms.h>' except that the name prefix
`FL_' is omitted. Read the module source for a complete list of
the defined names. Suggested use:
```text
import fl
from FL import *
```
---
guido@python.org


16.6 Standard Module flp

node250.html
node238.html
node248.html
node1.html
node270.html
---
# 16.6 Standard Module flp
This module defines functions that can read form definitions created
by the `form designer' (fdesign) program that comes with the
FORMS library (see module fl above).
For now, see the file `flp.doc' in the Python library source
directory for a description.
XXX A complete description should be inserted here!
---
guido@python.org


2.2 Built-in Exceptions

node26.html
node3.html
node24.html
node1.html
node270.html
---
# 2.2 Built-in Exceptions
Exceptions can be class objects or string objects. While
traditionally, most exceptions have been string objects, in Python
1.5, all standard exceptions have been converted to class objects,
and users are encouraged to the the same. The source code for those
exceptions is present in the standard library module
exceptions; this module never needs to be imported explicitly.
For backward compatibility, when Python is invoked with the -X
option, the standard exceptions are strings. This may be needed to
run some code that breaks because of the different semantics of class
based exceptions. The -X option will become obsolete in future
Python versions, so the recommended solution is to fix the code.
Two distinct string objects with the same value are considered different
exceptions. This is done to force programmers to use exception names
rather than their string value when specifying exception handlers.
The string value of all built-in exceptions is their name, but this is
not a requirement for user-defined exceptions or exceptions defined by
library modules.
For class exceptions, in a try statement with an except
clause that mentions a particular class, that clause also handles
any exception classes derived from that class (but not exception
classes from which it is derived). Two exception classes
that are not related via subclassing are never equivalent, even if
they have the same name.
The built-in exceptions listed below can be generated by the
interpreter or built-in functions. Except where mentioned, they have
an ``associated value'' indicating the detailed cause of the error.
This may be a string or a tuple containing several items of
information (e.g., an error code and a string explaining the code).
The associated value is the second argument to the raise
statement. For string exceptions, the associated value itself will be
stored in the variable named as the second argument of the
except clause (if any). For class exceptions derived from
the root class Exception, that variable receives the exception
instance, and the associated value is present as the exception
instance's args attribute; this is a tuple even if the second
argument to raise was not (then it is a singleton tuple).
User code can raise built-in exceptions. This can be used to test an
exception handler or to report an error condition ``just like'' the
situation in which the interpreter raises the same exception; but
beware that there is nothing to prevent user code from raising an
inappropriate error.
The following exceptions are only used as base classes for other
exceptions. When string-based standard exceptions are used, they
are tuples containing the directly derived classes.
The following exceptions are the exceptions that are actually raised.
They are class objects, except when the -X option is used to
revert back to string-based standard exceptions.
---
node26.html
node3.html
node24.html
node1.html
node270.html
guido@python.org


16.7 Built-in Module fm

node251.html
node238.html
node249.html
node1.html
node270.html
---
# 16.7 Built-in Module fm
This module provides access to the IRIS Font Manager library.
It is available only on Silicon Graphics machines.
See also: 4Sight User's Guide, Section 1, Chapter 5: Using the IRIS
Font Manager.
This is not yet a full interface to the IRIS Font Manager.
Among the unsupported features are: matrix operations; cache
operations; character operations (use string operations instead); some
details of font info; individual glyph metrics; and printer matching.
It supports the following operations:
Font handle objects support the following operations:
---
node251.html
node238.html
node249.html
node1.html
node270.html
guido@python.org


16.8 Built-in Module gl

node252.html
node238.html
node250.html
node1.html
node270.html
---
# 16.8 Built-in Module gl
This module provides access to the Silicon Graphics
Graphics Library.
It is available only on Silicon Graphics machines.
Warning:
Some illegal calls to the GL library cause the Python interpreter to dump
core.
In particular, the use of most GL calls is unsafe before the first
window is opened.
The module is too large to document here in its entirety, but the
following should help you to get started.
The parameter conventions for the C functions are translated to Python as
follows:
- All (short, long, unsigned) int values are represented by Python
integers.All float and double values are represented by Python floating point
numbers.
In most cases, Python integers are also allowed.All arrays are represented by one-dimensional Python lists.
In most cases, tuples are also allowed.All string and character arguments are represented by Python strings,
for instance,
winopen('Hi There!')
and
rotate(900, 'z').All (short, long, unsigned) integer arguments or return values that are
only used to specify the length of an array argument are omitted.
For example, the C call
```text
lmdef(deftype, index, np, props)
```
is translated to Python as
```text
lmdef(deftype, index, props)
```
Output arguments are omitted from the argument list; they are
transmitted as function return values instead.
If more than one value must be returned, the return value is a tuple.
If the C function has both a regular return value (that is not omitted
because of the previous rule) and an output argument, the return value
comes first in the tuple.
Examples: the C call
```text
getmcolor(i, &red, &green, &blue)
```
is translated to Python as
```text
red, green, blue = getmcolor(i)
```
The following functions are non-standard or have special argument
conventions:
Here is a tiny but complete example GL program in Python:
```text
import gl, GL, time

def main():
gl.foreground()
gl.prefposition(500, 900, 500, 900)
w = gl.winopen('CrissCross')
gl.ortho2(0.0, 400.0, 0.0, 400.0)
gl.color(GL.WHITE)
gl.clear()
gl.color(GL.RED)
gl.bgnline()
gl.v2f(0.0, 0.0)
gl.v2f(400.0, 400.0)
gl.endline()
gl.bgnline()
gl.v2f(400.0, 0.0)
gl.v2f(0.0, 400.0)
gl.endline()
time.sleep(5)

main()
```
---
node252.html
node238.html
node250.html
node1.html
node270.html
guido@python.org


16.9 Standard Modules GL and DEVICE

node253.html
node238.html
node251.html
node1.html
node270.html
---
# 16.9 Standard Modules GL and DEVICE
These modules define the constants used by the Silicon Graphics
Graphics Library
that C programmers find in the header files
`<gl/gl.h>'
and
`<gl/device.h>'.
Read the module source files for details.
---
guido@python.org


16.10 Built-in Module imgfile

node254.html
node238.html
node252.html
node1.html
node270.html
---
# 16.10 Built-in Module imgfile
The imgfile module allows python programs to access SGI imglib image
files (also known as `.rgb' files). The module is far from
complete, but is provided anyway since the functionality that there is
is enough in some cases. Currently, colormap files are not supported.
The module defines the following variables and functions:
---
node254.html
node238.html
node252.html
node1.html
node270.html
guido@python.org


17 SunOS Specific Services

node255.html
lib.html
node253.html
node1.html
node270.html
---
# 17 SunOS Specific Services
The modules described in this chapter provide interfaces to features
that are unique to the SunOS operating system (versions 4 and 5; the
latter is also known as Solaris version 2).
---
- 17.1 Built-in Module sunaudiodev (node255.html#SECTION0018100000000000000000)
- Audio Device Objects (node256.html#SECTION0018110000000000000000)
---
guido@python.org


17.1 Built-in Module sunaudiodev

node256.html
node254.html
node254.html
node1.html
node270.html
---
# 17.1 Built-in Module sunaudiodev
This module allows you to access the sun audio interface. The sun
audio hardware is capable of recording and playing back audio data
in U-LAW format with a sample rate of 8K per second. A full
description can be gotten with `man audio'.
The module defines the following variables and functions:
---
- Audio Device Objects (node256.html#SECTION0018110000000000000000)
---
guido@python.org


Audio Device Objects

node257.html
node255.html
node255.html
node1.html
node270.html
---
## Audio Device Objects
The audio device objects are returned by open define the
following methods (except control objects which only provide
getinfo, setinfo and drain):
There is a companion module, SUNAUDIODEV, which defines useful
symbolic constants like MIN_GAIN, MAX_GAIN,
SPEAKER, etc. The names of
the constants are the same names as used in the C include file
`<sun/audioio.h>', with the leading string `AUDIO_'
stripped.
Useability of the control device is limited at the moment, since there
is no way to use the ``wait for something to happen'' feature the
device provides.
---
node257.html
node255.html
node255.html
node1.html
node270.html
guido@python.org


18 Undocumented Modules

node258.html
lib.html
node256.html
node1.html
node270.html
---
# 18 Undocumented Modules
Here's a quick listing of modules that are currently undocumented, but
that should be documented. Feel free to contribute documentation for
them! (The idea and most contents for this chapter were taken from a
posting by Fredrik Lundh; I have revised some modules' status.)
---
- 18.1 Fundamental, and pretty straightforward to document (node258.html#SECTION0019100000000000000000)
18.2 Frameworks; somewhat harder to document, but well worth the effort (node259.html#SECTION0019200000000000000000)
18.3 Stuff useful to a lot of people, including the CGI crowd (node260.html#SECTION0019300000000000000000)
18.4 Miscellaneous useful utilities (node261.html#SECTION0019400000000000000000)
18.5 Parsing Python (node262.html#SECTION0019500000000000000000)
18.6 Platform specific modules (node263.html#SECTION0019600000000000000000)
18.7 Code objects and files, debugger etc. (node264.html#SECTION0019700000000000000000)
18.8 Multimedia (node265.html#SECTION0019800000000000000000)
18.9 Oddities (node266.html#SECTION0019900000000000000000)
18.10 Obsolete (node267.html#SECTION00191000000000000000000)
18.11 Extension modules (node268.html#SECTION00191100000000000000000)
---
guido@python.org


node259.html
node257.html
node257.html
node1.html
node270.html
---
# 18.1 Fundamental, and pretty straightforward to document
cPickle.c - mostly the same as pickle but no subclassing
cStringIO.c - mostly the same as StringIO but no subclassing
---
guido@python.org


node260.html
node257.html
node258.html
node1.html
node270.html
---
# 18.2 Frameworks; somewhat harder to document, but well worth the effort
Tkinter.py - Interface to Tcl/Tk for graphical user interfaces;
Fredrik Lundh is working on this one!
CGIHTTPServer.py - CGI-savvy HTTP Server
SimpleHTTPServer.py - Simple HTTP Server
---
guido@python.org


2.3 Built-in Functions

node27.html
node3.html
node25.html
node1.html
node270.html
---
# 2.3 Built-in Functions
The Python interpreter has a number of functions built into it that
are always available. They are listed here in alphabetical order.
---
node27.html
node3.html
node25.html
node1.html
node270.html
guido@python.org


node261.html
node257.html
node259.html
node1.html
node270.html
---
# 18.3 Stuff useful to a lot of people, including the CGI crowd
MimeWriter.py - Generic MIME writer
multifile.py - make each part of a multipart message ``feel'' like
fileinput.py - convenient loop over the lines in a list of input files.
---
guido@python.org


18.4 Miscellaneous useful utilities

node262.html
node257.html
node260.html
node1.html
node270.html
---
# 18.4 Miscellaneous useful utilities
Some of these are very old and/or not very robust; marked with ``hmm''.
calendar.py - Calendar printing functions
ConfigParser.py - Parse a file of sectioned configuration parameters
cmp.py - Efficiently compare files
cmpcache.py - Efficiently compare files (uses statcache)
dircache.py - like os.listdir, but caches results
dircmp.py - class to build directory diff tools on
linecache.py - Cache lines from files (used by pdb)
pipes.py - Conversion pipeline templates (hmm)
popen2.py - improved popen, can read AND write simultaneously
statcache.py - Maintain a cache of file stats
colorsys.py - Conversion between RGB and other color systems
dbhash.py - (g)dbm-like wrapper for bsdhash.hashopen
mhlib.py - MH interface
pty.py - Pseudo terminal utilities
tty.py - Terminal utilities
cmd.py - build line-oriented command interpreters (used by pdb)
bdb.py - A generic Python debugger base class (used by pdb)
ihooks.py - Import hook support (for ni and rexec)
---
guido@python.org


18.5 Parsing Python

node263.html
node257.html
node261.html
node1.html
node270.html
---
# 18.5 Parsing Python
(One could argue that these should all be documented together with the
parser module.)
tokenize.py - regular expression that recognizes Python tokens; also
contains helper code for colorizing Python source code.
pyclbr.py - Parse a Python file and retrieve classes and methods
---
guido@python.org


18.6 Platform specific modules

node264.html
node257.html
node262.html
node1.html
node270.html
---
# 18.6 Platform specific modules
ntpath.py - equivalent of posixpath on 32-bit Windows
dospath.py - equivalent of posixpath on MS-DOS
---
guido@python.org


node265.html
node257.html
node263.html
node1.html
node270.html
---
# 18.7 Code objects and files, debugger etc.
compileall.py - force "compilation" of all .py files in a directory
py_compile.py - "compile" a .py file to a .pyc file
repr.py - Redo the `...` (representation) but with limits on most
sizes (used by pdb)
---
guido@python.org


18.8 Multimedia

node266.html
node257.html
node264.html
node1.html
node270.html
---
# 18.8 Multimedia
audiodev.py - Plays audio files
sunau.py - parse Sun and NeXT audio files
sunaudio.py - interpret sun audio headers
toaiff.py - Convert "arbitrary" sound files to AIFF files
sndhdr.py - recognizing sound files
wave.py - parse WAVE files
whatsound.py - recognizing sound files
---
guido@python.org


18.9 Oddities

node267.html
node257.html
node265.html
node1.html
node270.html
---
# 18.9 Oddities
These modules are probably also obsolete, or just not very useful.
bisect.py - Bisection algorithms (this is actually useful at times)
dump.py - Print python code that reconstructs a variable
find.py - find files matching pattern in directory tree
fpformat.py - General floating point formatting functions - obsolete
grep.py - grep
mutex.py - Mutual exclusion - for use with module sched
packmail.py - create a self-unpacking Unix shell archive
poly.py - Polynomials
sched.py - event scheduler class
shutil.py - utility functions usable in a shell-like program
util.py - useful functions that don't fit elsewhere
zmod.py - Compute properties of mathematical "fields"
tzparse.py - Parse a timezone specification (unfinished)
---
guido@python.org


18.10 Obsolete

node268.html
node257.html
node266.html
node1.html
node270.html
---
# 18.10 Obsolete
newdir.py - New dir() function (the standard dir() is now just as good)
addpack.py - standard support for "packages" (use ni instead)
fmt.py - text formatting abstractions (too slow)
Para.py - helper for fmt.py
lockfile.py - wrapper around FCNTL file locking (use
fcntl.lockf/flock intead)
tb.py - Print tracebacks, with a dump of local variables (use
pdb.pm() or traceback.py instead)
codehack.py - extract function name or line number from a function
code object (these are now accessible as attributes: co.co_name,
func.func_name, co.co_firstlineno)
---
guido@python.org


18.11 Extension modules

node269.html
node257.html
node267.html
node1.html
node270.html
---
# 18.11 Extension modules
bsddbmodule.c - Interface to the Berkeley DB interface (yet another
dbm clone).
cursesmodule.c - Curses interface.
dbhashmodule.c - Obsolete; this functionality is now provided by
bsddbmodule.c.
dlmodule.c - A highly experimental and dangerous device for calling
arbitrary C functions in arbitrary shared libraries.
newmodule.c - Tommy Burnette's `new' module (creates new empty
objects of certain kinds) - dangerous.
nismodule.c - NIS (a.k.a. Sun's Yellow Pages) interface.
timingmodule.c - Measure time intervals to high resolution (obsolete
- use time.clock() instead).
stdwinmodule.c - Interface to STDWIN (an old, unsupported
platform-independent GUI package). Obsolete; use Tkinter for a
platform-independent GUI instead.
The following are SGI specific:
clmodule.c - Interface to the SGI compression library.
svmodule.c - Interface to the ``simple video'' board on SGI Indigo
(obsolete hardware).
---
guido@python.org


Module Index

node270.html
lib.html
node268.html
node1.html
node270.html
---
## Module Index
__builtin__ (node60.html#3956)
__main__ (node61.html#3963)
aifc (node195.html#12306)
al (node239.html#14093)
AL (node242.html#14217)
anydbm (node101.html#7149)
array (node82.html#5539)
audioop (node193.html#12051)
base64 (node181.html#11349)
BaseHTTPServer (node187.html#11642)
Bastion (node191.html#12022)
binascii (node175.html#11055)
binhex (node172.html#11003)
cd (node243.html#14226)
cgi (node140.html#9159)
CGIHTTPServer (node187.html#11653)
cmath (node78.html#5282)
code (node53.html#3289)
commands (node123.html#8758)
copy (node36.html#2696)
copy_reg (node34.html#2649)
crypt (node110.html#8053)
ctb (node206.html#12821)
dbm (node111.html#8072)
DEVICE (node252.html#15090)
dis (node56.html#3393)
dumbdbm (node101.html#7150)
EasyDialogs (node229.html#13784)
errno (node88.html#5993)
exceptions (node25.html#1118)
fcntl (node116.html#8264)
findertools (node221.html#13522)
fl (node244.html#14451)
FL (node248.html#14909)
flp (node249.html#14915)
fm (node250.html#14927)
fnmatch (node90.html#6394)
formatter (node163.html#10524)
FrameWork (node230.html#13822)
ftplib (node154.html#9479)
gdbm (node112.html#8105)
getopt (node86.html#5930)
gl (node251.html#15013)
GL (node252.html#15089)
glob (node89.html#6368)
gopherlib (node156.html#9670)
grp (node109.html#8028)
gzip (node104.html#7278)
htmllib (node161.html#10219)
httplib (node151.html#9397)
ic (node217.html#13321)
imageop (node194.html#12231)
imgfile (node253.html#15106)
imghdr (node198.html#12530)
imp (node38.html#2779)
jpeg (node196.html#12454)
keyword (node52.html#3280)
locale (node91.html#6440)
mac (node204.html#12775)
macconsole (node208.html#12957)
macdnr (node211.html#13060)
macfs (node213.html#13138)
MacOS (node219.html#13428)
macostools (node220.html#13484)
macpath (node205.html#12801)
macspeech (node226.html#13714)
mactcp (node222.html#13566)
mailbox (node184.html#11558)
mailcap (node180.html#11313)
marshal (node37.html#2725)
math (node77.html#5132)
md5 (node200.html#12569)
mimetools (node170.html#10887)
mimify (node186.html#11585)
MiniAEFrame (node236.html#14043)
mpz (node201.html#12612)
ni (node40.html#2973)
nntplib (node157.html#9702)
operator (node31.html#2140)
os (node84.html#5677)
parser (node41.html#3011)
pdb (node124.html#8791)
pickle (node33.html#2507)
posix (node106.html#7342)
posixfile (node117.html#8331)
posixpath (node107.html#7829)
pprint (node54.html#3314)
profile (node127.html#8939)
pstats (node127.html#8940)
pwd (node108.html#8000)
Queue (node99.html#7095)
quopri (node182.html#11393)
rand (node81.html#5512)
random (node80.html#5429)
re (node64.html#4244)
regex (node69.html#4684)
regsub (node72.html#4910)
resource (node118.html#8464)
rexec (node189.html#11823)
rfc822 (node168.html#10767)
rgbimg (node197.html#12493)
rotor (node202.html#12712)
select (node97.html#6985)
sgmllib (node160.html#10036)
shelve (node35.html#2676)
signal (node93.html#6585)
SimpleHTTPServer (node187.html#11652)
site (node58.html#3869)
socket (node94.html#6679)
SocketServer (node183.html#11425)
soundex (node75.html#5107)
stat (node122.html#8687)
string (node63.html#3970)
StringIO (node74.html#5095)
struct (node73.html#4974)
sunaudiodev (node255.html#15162)
symbol (node50.html#3220)
sys (node28.html#1839)
syslog (node121.html#8609)
tempfile (node87.html#5952)
TERMIOS (node115.html#8246)
termios (node113.html#8167)
thread (node98.html#7019)
time (node85.html#5796)
token (node51.html#3232)
traceback (node32.html#2442)
types (node29.html#2010)
urllib (node150.html#9305)
urlparse (node159.html#9991)
user (node59.html#3926)
UserDict (node30.html#2111)
UserList (node30.html#2112)
uu (node174.html#11027)
whichdb (node102.html#7178)
whrandom (node79.html#5380)
xdrlib (node176.html#11119)
xmllib (node162.html#10321)
zlib (node103.html#7191)
---
guido@python.org


3 Python Services

node28.html
lib.html
node26.html
node1.html
node270.html
---
# 3 Python Services
The modules described in this chapter provide a wide range of services
related to the Python interpreter and its interaction with its
environment. Here's an overview:
---
- 3.1 Built-in Module sys (node28.html#SECTION004100000000000000000)
3.2 Standard Module types (node29.html#SECTION004200000000000000000)
3.3 Standard Modules UserDict and UserList (node30.html#SECTION004300000000000000000)
3.4 Built-in Module operator (node31.html#SECTION004400000000000000000)
3.5 Standard Module traceback (node32.html#SECTION004500000000000000000)
3.6 Standard Module pickle (node33.html#SECTION004600000000000000000)
Standard Module copy_reg (node34.html#SECTION004700000000000000000)
3.8 Standard Module shelve (node35.html#SECTION004800000000000000000)
3.9 Standard Module copy (node36.html#SECTION004900000000000000000)
3.10 Built-in Module marshal (node37.html#SECTION0041000000000000000000)
3.11 Built-in Module imp (node38.html#SECTION0041100000000000000000)
- Examples (node39.html#SECTION0041110000000000000000)
3.12 Standard Module ni (node40.html#SECTION0041200000000000000000)
3.13 Built-in Module parser (node41.html#SECTION0041300000000000000000)
- Creating AST Objects (node42.html#SECTION0041310000000000000000)
Converting AST Objects (node43.html#SECTION0041320000000000000000)
Queries on AST Objects (node44.html#SECTION0041330000000000000000)
Exceptions and Error Handling (node45.html#SECTION0041340000000000000000)
AST Objects (node46.html#SECTION0041350000000000000000)
Examples (node47.html#SECTION0041360000000000000000)
- Emulation of compile() (node48.html#SECTION0041361000000000000000)
Information Discovery (node49.html#SECTION0041362000000000000000)
3.14 Standard Module symbol (node50.html#SECTION0041400000000000000000)
3.15 Standard Module token (node51.html#SECTION0041500000000000000000)
3.16 Standard Module keyword (node52.html#SECTION0041600000000000000000)
3.17 Standard Module code (node53.html#SECTION0041700000000000000000)
3.18 Standard Module pprint (node54.html#SECTION0041800000000000000000)
- PrettyPrinter Objects (node55.html#SECTION0041810000000000000000)
3.19 Standard Module dis (node56.html#SECTION0041900000000000000000)
- Python Byte Code Instructions (node57.html#SECTION0041910000000000000000)
3.20 Standard Module site (node58.html#SECTION0042000000000000000000)
3.21 Standard Module user (node59.html#SECTION0042100000000000000000)
Built-in Module __builtin__ (node60.html#SECTION0042200000000000000000)
Built-in Module __main__ (node61.html#SECTION0042300000000000000000)
---
guido@python.org


About this document ...

lib.html
node270.html
node1.html
node270.html
---
# About this document ...
Python Library Reference
This document was generated using the LaTeX2HTML (http://www-dsed.llnl.gov/files/programs/unix/latex2html/manual/) translator Version 96.1 (Feb 5, 1996) Copyright © 1993, 1994, 1995, 1996, Nikos Drakos (http://cbl.leeds.ac.uk/nikos/personal.html), Computer Based Learning Unit, University of Leeds.
The command line arguments were:
latex2html -address guido@python.org lib.tex.
The translation was initiated by Fred L. Drake on Tue Feb 17 10:28:55 EST 1998
---
guido@python.org


3.1 Built-in Module sys

node29.html
node27.html
node27.html
node1.html
node270.html
---
# 3.1 Built-in Module sys
This module provides access to some variables used or maintained by the
interpreter and to functions that interact strongly with the interpreter.
It is always available.
---
node29.html
node27.html
node27.html
node1.html
node270.html
guido@python.org


3.2 Standard Module types

node30.html
node27.html
node28.html
node1.html
node270.html
---
# 3.2 Standard Module types
This module defines names for all object types that are used by the
standard Python interpreter (but not for the types defined by various
extension modules). It is safe to use ``from types import *'' --
the module does not export any other names besides the ones listed
here. New names exported by future versions of this module will
all end in Type.
Typical use is for functions that do different things depending on
their argument types, like the following:
```text
from types import *
def delete(list, item):
if type(item) is IntType:
del list[item]
else:
list.remove(item)
```
The module defines the following names:
---
node30.html
node27.html
node28.html
node1.html
node270.html
guido@python.org


node4.html
lib.html
node2.html
node1.html
node270.html
---
# 2 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.footnode.html#27
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.
---
- 2.1 Built-in Types (node4.html#SECTION003100000000000000000)
- Truth Value Testing (node5.html#SECTION003110000000000000000)
Boolean Operations (node6.html#SECTION003120000000000000000)
Comparisons (node7.html#SECTION003130000000000000000)
Numeric Types (node8.html#SECTION003140000000000000000)
- Bit-string Operations on Integer Types (node9.html#SECTION003141000000000000000)
Sequence Types (node10.html#SECTION003150000000000000000)
- More String Operations (node11.html#SECTION003151000000000000000)
Mutable Sequence Types (node12.html#SECTION003152000000000000000)
Mapping Types (node13.html#SECTION003160000000000000000)
Other Built-in Types (node14.html#SECTION003170000000000000000)
- Modules (node15.html#SECTION003171000000000000000)
Classes and Class Instances (node16.html#SECTION003172000000000000000)
Functions (node17.html#SECTION003173000000000000000)
Methods (node18.html#SECTION003174000000000000000)
Code Objects (node19.html#SECTION003175000000000000000)
Type Objects (node20.html#SECTION003176000000000000000)
The Null Object (node21.html#SECTION003177000000000000000)
File Objects (node22.html#SECTION003178000000000000000)
Internal Objects (node23.html#SECTION003179000000000000000)
Special Attributes (node24.html#SECTION003180000000000000000)
2.2 Built-in Exceptions (node25.html#SECTION003200000000000000000)
2.3 Built-in Functions (node26.html#SECTION003300000000000000000)
---
guido@python.org


node31.html
node27.html
node29.html
node1.html
node270.html
---
# 3.3 Standard Modules UserDict and UserList
Each of these modules defines a class that acts as a wrapper around
either dictionary or list objects. They're useful base classes for
your own dictionary-like or list-like classes, which can inherit from
them and override existing methods or add new ones. In this way one
can add new behaviours to dictionaries or lists.
The UserDict module defines the UserDict class:
The UserList module defines the UserList class:
---
guido@python.org


3.4 Built-in Module operator

node32.html
node27.html
node30.html
node1.html
node270.html
---
# 3.4 Built-in Module operator
The operator module exports a set of functions implemented in C
corresponding to the intrinsic operators of Python. For example,
operator.add(x, y) is equivalent to the expression x+y. The
function names are those used for special class methods; variants without
leading and trailing `__' are also provided for convenience.
The operator module defines the following functions:
Example: Build a dictionary that maps the ordinals from 0 to
256 to their character equivalents.
```text
>>> import operator
>>> d = {}
>>> keys = range(256)
>>> vals = map(chr, keys)
>>> map(operator.setitem, [d]*len(keys), keys, vals)
```
---
node32.html
node27.html
node30.html
node1.html
node270.html
guido@python.org


3.5 Standard Module traceback

node33.html
node27.html
node31.html
node1.html
node270.html
---
# 3.5 Standard Module traceback
This module provides a standard interface to format and print stack
traces of Python programs. It exactly mimics the behavior of the
Python interpreter when it prints a stack trace. This is useful when
you want to print stack traces under program control, e.g. in a
``wrapper'' around the interpreter.
The module uses traceback objects -- this is the object type
that is stored in the variables sys.exc_traceback and
sys.last_traceback.
The module defines the following functions:
---
node33.html
node27.html
node31.html
node1.html
node270.html
guido@python.org


3.6 Standard Module pickle

node34.html
node27.html
node32.html
node1.html
node270.html
---
# 3.6 Standard Module pickle
The pickle module implements a basic but powerful algorithm for
``pickling'' (a.k.a. serializing, marshalling or flattening) nearly
arbitrary Python objects. This is the act of converting objects to a
stream of bytes (and back: ``unpickling'').
This is a more primitive notion than
persistency -- although pickle reads and writes file objects,
it does not handle the issue of naming persistent objects, nor the
(even more complicated) area of concurrent access to persistent
objects. The pickle module can transform a complex object into
a byte stream and it can transform the byte stream into an object with
the same internal structure. The most obvious thing to do with these
byte streams is to write them onto a file, but it is also conceivable
to send them across a network or store them in a database. The module
shelve provides a simple interface to pickle and unpickle
objects on ``dbm''-style database files.
Note: The pickle module is rather slow. A
reimplementation of the same algorithm in C, which is up to 1000 times
faster, is available as the cPickle
module. This has the same interface except that Pickler and
Unpickler are factory functions, not classes (so they cannot be
used as a base class for inheritance).
Unlike the built-in module marshal, pickle handles the
following correctly:
- recursive objects (objects containing references to themselves)object sharing (references to the same object in different places)user-defined classes and their instances
The data format used by pickle is Python-specific. This has
the advantage that there are no restrictions imposed by external
standards such as XDR
(which can't represent pointer sharing); however
it means that non-Python programs may not be able to reconstruct
pickled Python objects.
By default, the pickle data format uses a printable ASCII
representation. This is slightly more voluminous than a binary
representation. The big advantage of using printable ASCII (and of
some other characteristics of pickle's representation) is that
for debugging or recovery purposes it is possible for a human to read
the pickled file with a standard text editor.
A binary format, which is slightly more efficient, can be chosen by
specifying a nonzero (true) value for the bin argument to the
Pickler constructor or the dump() and dumps()
functions. The binary format is not the default because of backwards
compatibility with the Python 1.4 pickle module. In a future version,
the default may change to binary.
The pickle module doesn't handle code objects, which the
marshal module does. I suppose pickle could, and maybe
it should, but there's probably no great need for it right now (as
long as marshal continues to be used for reading and writing
code objects), and at least this avoids the possibility of smuggling
Trojan horses into a program.
For the benefit of persistency modules written using pickle, it
supports the notion of a reference to an object outside the pickled
data stream. Such objects are referenced by a name, which is an
arbitrary string of printable ASCII characters. The resolution of
such names is not defined by the pickle module -- the
persistent object module will have to implement a method
persistent_load(). To write references to persistent objects,
the persistent module must define a method persistent_id() which
returns either None or the persistent ID of the object.
There are some restrictions on the pickling of class instances.
First of all, the class must be defined at the top level in a module.
Furthermore, all its instance variables must be picklable.
When a pickled class instance is unpickled, its __init__() method
is normally not invoked. Note: This is a deviation
from previous versions of this module; the change was introduced in
Python 1.5b2. The reason for the change is that in many cases it is
desirable to have a constructor that requires arguments; it is a
(minor) nuisance to have to provide a __getinitargs__() method.
If it is desirable that the __init__() method be called on
unpickling, a class can define a method __getinitargs__(),
which should return a tuple containing the arguments to be
passed to the class constructor (__init__()). This method is
called at pickle time; the tuple it returns is incorporated in the
pickle for the instance.
Classes can further influence how their instances are pickled -- if the class
defines the method __getstate__(), it is called and the return
state is pickled as the contents for the instance, and if the class
defines the method __setstate__(), it is called with the
unpickled state. (Note that these methods can also be used to
implement copying class instances.) If there is no
__getstate__() method, the instance's __dict__ is
pickled. If there is no __setstate__() method, the pickled
object must be a dictionary and its items are assigned to the new
instance's dictionary. (If a class defines both __getstate__()
and __setstate__(), the state object needn't be a dictionary
-- these methods can do what they want.) This protocol is also used
by the shallow and deep copying operations defined in the copy
module.
Note that when class instances are pickled, their class's code and
data are not pickled along with them. Only the instance data are
pickled. This is done on purpose, so you can fix bugs in a class or
add methods and still load objects that were created with an earlier
version of the class. If you plan to have long-lived objects that
will see many versions of a class, it may be worthwhile to put a version
number in the objects so that suitable conversions can be made by the
class's __setstate__() method.
When a class itself is pickled, only its name is pickled -- the class
definition is not pickled, but re-imported by the unpickling process.
Therefore, the restriction that the class must be defined at the top
level in a module applies to pickled classes as well.
The interface can be summarized as follows.
To pickle an object x onto a file f, open for writing:
```text
p = pickle.Pickler(f)
p.dump(x)
```
A shorthand for this is:
```text
pickle.dump(x, f)
```
To unpickle an object x from a file f, open for reading:
```text
u = pickle.Unpickler(f)
x = u.load()
```
A shorthand is:
```text
x = pickle.load(f)
```
The Pickler class only calls the method f.write() with a
string argument. The Unpickler calls the methods f.read()
(with an integer argument) and f.readline() (without argument),
both returning a string. It is explicitly allowed to pass non-file
objects here, as long as they have the right methods.
The constructor for the Pickler class has an optional second
argument, bin. If this is present and nonzero, the binary
pickle format is used; if it is zero or absent, the (less efficient,
but backwards compatible) text pickle format is used. The
Unpickler class does not have an argument to distinguish
between binary and text pickle formats; it accepts either format.
The following types can be pickled:
- Noneintegers, long integers, floating point numbersstringstuples, lists and dictionaries containing only picklable objectsclasses that are defined at the top level in a moduleinstances of such classes whose __dict__ or
__setstate__() is picklable
Attempts to pickle unpicklable objects will raise the
PicklingError exception; when this happens, an unspecified
number of bytes may have been written to the file.
It is possible to make multiple calls to the dump() method of
the same Pickler instance. These must then be matched to the
same number of calls to the load() instance of the
corresponding Unpickler instance. If the same object is
pickled by multiple dump() calls, the load() will all
yield references to the same object. Warning: this is intended
for pickling multiple objects without intervening modifications to the
objects or their parts. If you modify an object and then pickle it
again using the same Pickler instance, the object is not
pickled again -- a reference to it is pickled and the
Unpickler will return the old value, not the modified one.
(There are two problems here: (a) detecting changes, and (b)
marshalling a minimal set of changes. I have no answers. Garbage
Collection may also become a problem here.)
Apart from the Pickler and Unpickler classes, the
module defines the following functions, and an exception:
---
node34.html
node27.html
node32.html
node1.html
node270.html
guido@python.org


Standard Module copy_reg

node35.html
node27.html
node33.html
node1.html
node270.html
---
# Standard Module copy_reg
The copy_reg module provides support for the
pickle and
cPickle modules. The
copy module is likely to use this in the
future as well. It provides configuration information about object
constructors which are not classes. Such constructors may be factory
functions or class instances.
---
guido@python.org


3.8 Standard Module shelve

node36.html
node27.html
node34.html
node1.html
node270.html
---
# 3.8 Standard Module shelve
A ``shelf'' is a persistent, dictionary-like object. The difference
with ``dbm'' databases is that the values (not the keys!) in a shelf
can be essentially arbitrary Python objects -- anything that the
pickle module can handle. This includes most class instances,
recursive data types, and objects containing lots of shared
sub-objects. The keys are ordinary strings.
To summarize the interface (key is a string, data is an
arbitrary object):
```text
import shelve

d = shelve.open(filename) # open, with (g)dbm filename -- no suffix

d[key] = data # store data at key (overwrites old data if
# using an existing key)
data = d[key] # retrieve data at key (raise KeyError if no
# such key)
del d[key] # delete data stored at key (raises KeyError
# if no such key)
flag = d.has_key(key) # true if the key exists
list = d.keys() # a list of all existing keys (slow!)

d.close() # close it
```
Restrictions:
- The choice of which database package will be used (e.g. dbm or
gdbm)
depends on which interface is available. Therefore it isn't safe to
open the database directly using dbm. The database is also
(unfortunately) subject to the limitations of dbm, if it is used --
this means that (the pickled representation of) the objects stored in
the database should be fairly small, and in rare cases key collisions
may cause the database to refuse updates.
Dependent on the implementation, closing a persistent dictionary may
or may not be necessary to flush changes to disk.The shelve module does not support concurrent read/write
access to shelved objects. (Multiple simultaneous read accesses are
safe.) When a program has a shelf open for writing, no other program
should have it open for reading or writing. Unix file locking can
be used to solve this, but this differs across Unix versions and
requires knowledge about the database implementation used.
---
guido@python.org


3.9 Standard Module copy

node37.html
node27.html
node35.html
node1.html
node270.html
---
# 3.9 Standard Module copy
This module provides generic (shallow and deep) copying operations.
Interface summary:
```text
import copy

x = copy.copy(y) # make a shallow copy of y
x = copy.deepcopy(y) # make a deep copy of y
```
For module specific errors, copy.error is raised.
The difference between shallow and deep copying is only relevant for
compound objects (objects that contain other objects, like lists or
class instances):
- A shallow copy constructs a new compound object and then (to the
extent possible) inserts references into it to the objects found
in the original.A deep copy constructs a new compound object and then,
recursively, inserts copies into it of the objects found in the
original.
Two problems often exist with deep copy operations that don't exist
with shallow copy operations:
- Recursive objects (compound objects that, directly or indirectly,
contain a reference to themselves) may cause a recursive loop.Because deep copy copies everything it may copy too much, e.g.\
administrative data structures that should be shared even between
copies.
Python's deepcopy() operation avoids these problems by:
- keeping a table of objects already copied during the current
copying pass; andletting user-defined classes override the copying operation or the
set of components copied.
This version does not copy types like module, class, function, method,
nor stack trace, stack frame, nor file, socket, window, nor array, nor
any similar types.
Classes can use the same interfaces to control copying that they use
to control pickling: they can define methods called
__getinitargs__(), __getstate__() and
__setstate__(). See the description of module pickle
for information on these methods.
---
guido@python.org


3.10 Built-in Module marshal

node38.html
node27.html
node36.html
node1.html
node270.html
---
# 3.10 Built-in Module marshal
This module contains functions that can read and write Python
values in a binary format. The format is specific to Python, but
independent of machine architecture issues (e.g., you can write a
Python value to a file on a PC, transport the file to a Sun, and read
it back there). Details of the format are undocumented on purpose;
it may change between Python versions (although it rarely does).footnode.html#2726
This is not a general ``persistency'' module. For general persistency
and transfer of Python objects through RPC calls, see the modules
pickle and shelve. The marshal module exists
mainly to support reading and writing the ``pseudo-compiled'' code for
Python modules of `.pyc' files.
Not all Python object types are supported; in general, only objects
whose value is independent from a particular invocation of Python can
be written and read by this module. The following types are supported:
None, integers, long integers, floating point numbers,
strings, tuples, lists, dictionaries, and code objects, where it
should be understood that tuples, lists and dictionaries are only
supported as long as the values contained therein are themselves
supported; and recursive lists and dictionaries should not be written
(they will cause infinite loops).
Caveat: On machines where C's long int type has more than
32 bits (such as the DEC Alpha), it
is possible to create plain Python integers that are longer than 32
bits. Since the current marshal module uses 32 bits to
transfer plain Python integers, such values are silently truncated.
This particularly affects the use of very long integer literals in
Python modules -- these will be accepted by the parser on such
machines, but will be silently be truncated when the module is read
from the `.pyc' instead.footnode.html#2775
There are functions that read/write files as well as functions
operating on strings.
The module defines these functions:
---
node38.html
node27.html
node36.html
node1.html
node270.html
guido@python.org


3.11 Built-in Module imp

node39.html
node27.html
node37.html
node1.html
node270.html
---
# 3.11 Built-in Module imp
This module provides an interface to the mechanisms used to implement
the import statement. It defines the following constants and
functions:
The following constants with integer values, defined in this module,
are used to indicate the search result of find_module().
The following constant and functions are obsolete; their functionality
is available through find_module() or load_module().
They are kept around for backward compatibility:
---
- Examples (node39.html#SECTION0041110000000000000000)
---
node39.html
node27.html
node37.html
node1.html
node270.html
guido@python.org


Examples

node40.html
node38.html
node38.html
node1.html
node270.html
---
## 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
imp.find_module() has been extended and
imp.load_module() has been added in 1.4.)
```text
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).
---
guido@python.org


2.1 Built-in Types

node5.html
node3.html
node3.html
node1.html
node270.html
---
# 2.1 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.
---
- Truth Value Testing (node5.html#SECTION003110000000000000000)
Boolean Operations (node6.html#SECTION003120000000000000000)
Comparisons (node7.html#SECTION003130000000000000000)
Numeric Types (node8.html#SECTION003140000000000000000)
- Bit-string Operations on Integer Types (node9.html#SECTION003141000000000000000)
Sequence Types (node10.html#SECTION003150000000000000000)
- More String Operations (node11.html#SECTION003151000000000000000)
Mutable Sequence Types (node12.html#SECTION003152000000000000000)
Mapping Types (node13.html#SECTION003160000000000000000)
Other Built-in Types (node14.html#SECTION003170000000000000000)
- Modules (node15.html#SECTION003171000000000000000)
Classes and Class Instances (node16.html#SECTION003172000000000000000)
Functions (node17.html#SECTION003173000000000000000)
Methods (node18.html#SECTION003174000000000000000)
Code Objects (node19.html#SECTION003175000000000000000)
Type Objects (node20.html#SECTION003176000000000000000)
The Null Object (node21.html#SECTION003177000000000000000)
File Objects (node22.html#SECTION003178000000000000000)
Internal Objects (node23.html#SECTION003179000000000000000)
Special Attributes (node24.html#SECTION003180000000000000000)
---
guido@python.org


3.12 Standard Module ni

node41.html
node27.html
node39.html
node1.html
node270.html
---
# 3.12 Standard Module ni
Warning: This module is obsolete. As of Python 1.5a4,
package support (with different semantics for __init__ and no
support for __domain__ or __) is built in the
interpreter. The ni module is retained only for backward
compatibility. As of Python 1.5b2, it has been renamed to ni1;
if you really need it, you can use import ni1, but the
recommended approach is to rely on the built-in package support,
converting existing packages if needed. Note that mixing ni
and the built-in package support doesn't work: once you import
ni, all packages use it.
The ni module defines a new importing scheme, which supports
packages containing several Python modules. To enable package
support, execute import ni before importing any packages. Importing
this module automatically installs the relevant import hooks. There
are no publicly-usable functions or variables in the ni module.
To create a package named spam containing sub-modules ham, bacon and
eggs, create a directory `spam' somewhere on Python's module search
path, as given in sys.path. Then, create files called `ham.py', `bacon.py' and
`eggs.py' inside `spam'.
To import module ham from package spam and use function
hamneggs() from that module, you can use any of the following
possibilities:
```text
import spam.ham # *not* "import spam" !!!
spam.ham.hamneggs()
```
```text
from spam import ham
ham.hamneggs()
```
```text
from spam.ham import hamneggs
hamneggs()
```
import spam creates an
empty package named spam if one does not already exist, but it does
not automatically import spam's submodules.
The only submodule that is guaranteed to be imported is
spam.__init__, if it exists; it would be in a file named
`__init__.py' in the `spam' directory. Note that
spam.__init__ is a submodule of package spam. It can refer to
spam's namespace as __ (two underscores):
```text
__.spam_inited = 1 # Set a package-level variable
```
Additional initialization code (setting up variables, importing other
submodules) can be performed in `spam/__init__.py'.
---
guido@python.org


3.13 Built-in Module parser

node42.html
node27.html
node40.html
node1.html
node270.html
---
# 3.13 Built-in Module parser
The parser module provides an interface to Python's internal
parser and byte-code compiler. The primary purpose for this interface
is to allow Python code to edit the parse tree of a Python expression
and create executable code from this. This is better than trying
to parse and modify an arbitrary Python code fragment as a string
because parsing is performed in a manner identical to the code
forming the application. It is also faster.
There are a few things to note about this module which are important
to making use of the data structures created. This is not a tutorial
on editing the parse trees for Python code, but some examples of using
the parser module are presented.
Most importantly, a good understanding of the Python grammar processed
by the internal parser is required. For full information on the
language syntax, refer to the Python Language Reference. The
parser itself is created from a grammar specification defined in the file
`Grammar/Grammar' in the standard Python distribution. The parse
trees stored in the ``AST objects'' created by this module are the
actual output from the internal parser when created by the
expr() or suite() functions, described below. The AST
objects created by sequence2ast() faithfully simulate those
structures. Be aware that the values of the sequences which are
considered ``correct'' will vary from one version of Python to another
as the formal grammar for the language is revised. However,
transporting code from one Python version to another as source text
will always allow correct parse trees to be created in the target
version, with the only restriction being that migrating to an older
version of the interpreter will not support more recent language
constructs. The parse trees are not typically compatible from one
version to another, whereas source code has always been
forward-compatible.
Each element of the sequences returned by ast2list() or
ast2tuple() has a simple form. Sequences representing
non-terminal elements in the grammar always have a length greater than
one. The first element is an integer which identifies a production in
the grammar. These integers are given symbolic names in the C header
file `Include/graminit.h' and the Python module
symbol. Each additional element of the sequence represents
a component of the production as recognized in the input string: these
are always sequences which have the same form as the parent. An
important aspect of this structure which should be noted is that
keywords used to identify the parent node type, such as the keyword
if in an if_stmt, are included in the node tree without
any special treatment. For example, the if keyword is
represented by the tuple (1, 'if'), where 1 is the
numeric value associated with all NAME tokens, including
variable and function names defined by the user. In an alternate form
returned when line number information is requested, the same token
might be represented as (1, 'if', 12), where the 12
represents the line number at which the terminal symbol was found.
Terminal elements are represented in much the same way, but without
any child elements and the addition of the source text which was
identified. The example of the if keyword above is
representative. The various types of terminal symbols are defined in
the C header file `Include/token.h' and the Python module
token.
The AST objects are not required to support the functionality of this
module, but are provided for three purposes: to allow an application
to amortize the cost of processing complex parse trees, to provide a
parse tree representation which conserves memory space when compared
to the Python list or tuple representation, and to ease the creation
of additional modules in C which manipulate parse trees. A simple
``wrapper'' class may be created in Python to hide the use of AST
objects.
The parser module defines functions for a few distinct
purposes. The most important purposes are to create AST objects and
to convert AST objects to other representations such as parse trees
and compiled code objects, but there are also functions which serve to
query the type of parse tree represented by an AST object.
---
- Creating AST Objects (node42.html#SECTION0041310000000000000000)
Converting AST Objects (node43.html#SECTION0041320000000000000000)
Queries on AST Objects (node44.html#SECTION0041330000000000000000)
Exceptions and Error Handling (node45.html#SECTION0041340000000000000000)
AST Objects (node46.html#SECTION0041350000000000000000)
Examples (node47.html#SECTION0041360000000000000000)
- Emulation of compile() (node48.html#SECTION0041361000000000000000)
Information Discovery (node49.html#SECTION0041362000000000000000)
---
node42.html
node27.html
node40.html
node1.html
node270.html
guido@python.org


Creating AST Objects

node43.html
node41.html
node41.html
node1.html
node270.html
---
## Creating AST Objects
AST objects may be created from source code or from a parse tree.
When creating an AST object from source, different functions are used
to create the 'eval' and 'exec' forms.
---
node43.html
node41.html
node41.html
node1.html
node270.html
guido@python.org


Converting AST Objects

node44.html
node41.html
node42.html
node1.html
node270.html
---
## Converting AST Objects
AST objects, regardless of the input used to create them, may be
converted to parse trees represented as list- or tuple- trees, or may
be compiled into executable code objects. Parse trees may be
extracted with or without line numbering information.
---
node44.html
node41.html
node42.html
node1.html
node270.html
guido@python.org


Queries on AST Objects

node45.html
node41.html
node43.html
node1.html
node270.html
---
## Queries on AST Objects
Two functions are provided which allow an application to determine if
an AST was create as an expression or a suite. Neither of these
functions can be used to determine if an AST was created from source
code via expr() or suite() or from a parse tree
via sequence2ast().
---
guido@python.org


Exceptions and Error Handling

node46.html
node41.html
node44.html
node1.html
node270.html
---
## Exceptions and Error Handling
The parser module defines a single exception, but may also pass other
built-in exceptions from other portions of the Python runtime
environment. See each function for information about the exceptions
it can raise.
Note that the functions compileast(), expr(), and
suite() may throw exceptions which are normally thrown by the
parsing and compilation process. These include the built in
exceptions MemoryError, OverflowError,
SyntaxError, and SystemError. In these cases, these
exceptions carry all the meaning normally associated with them. Refer
to the descriptions of each function for detailed information.
---
guido@python.org


AST Objects

node47.html
node41.html
node45.html
node1.html
node270.html
---
## AST Objects
AST objects returned by expr(), suite(), and
sequence2ast() have no methods of their own.
Some of the functions defined which accept an AST object as their
first argument may change to object methods in the future. The type
of these objects is available as ASTType in the module.
Ordered and equality comparisons are supported between AST objects.
---
guido@python.org


Examples

node48.html
node41.html
node46.html
node1.html
node270.html
---
## Examples
The parser modules allows operations to be performed on the parse tree
of Python source code before the bytecode is generated, and provides
for inspection of the parse tree for information gathering purposes.
Two examples are presented. The simple example demonstrates emulation
of the compile() built-in function and
the complex example shows the use of a parse tree for information
discovery.
---
- Emulation of compile() (node48.html#SECTION0041361000000000000000)
Information Discovery (node49.html#SECTION0041362000000000000000)
---
guido@python.org


Emulation of compile()

node49.html
node47.html
node47.html
node1.html
node270.html
---
### Emulation of compile()
While many useful operations may take place between parsing and
bytecode generation, the simplest operation is to do nothing. For
this purpose, using the parser module to produce an
intermediate data structure is equivelent to the code
```text
>>> code = compile('a + 5', 'eval')
>>> a = 5
>>> eval(code)
10
```
The equivelent operation using the parser module is somewhat
longer, and allows the intermediate internal parse tree to be retained
as an AST object:
```text
>>> import parser
>>> ast = parser.expr('a + 5')
>>> code = parser.compileast(ast)
>>> a = 5
>>> eval(code)
10
```
An application which needs both AST and code objects can package this
code into readily available functions:
```text
import parser

def load_suite(source_string):
ast = parser.suite(source_string)
code = parser.compileast(ast)
return ast, code

def load_expression(source_string):
ast = parser.expr(source_string)
code = parser.compileast(ast)
return ast, code
```
---
guido@python.org


Information Discovery

node50.html
node47.html
node48.html
node1.html
node270.html
---
### Information Discovery
Some applications benefit from direct access to the parse tree. The
remainder of this section demonstrates how the parse tree provides
access to module documentation defined in docstrings without requiring
that the code being examined be loaded into a running interpreter via
import. This can be very useful for performing analyses of
untrusted code.
Generally, the example will demonstrate how the parse tree may be
traversed to distill interesting information. Two functions and a set
of classes are developed which provide programmatic access to high
level function and class definitions provided by a module. The
classes extract information from the parse tree and provide access to
the information at a useful semantic level, one function provides a
simple low-level pattern matching capability, and the other function
defines a high-level interface to the classes by handling file
operations on behalf of the caller. All source files mentioned here
which are not part of the Python installation are located in the
`Demo/parser/' directory of the distribution.
The dynamic nature of Python allows the programmer a great deal of
flexibility, but most modules need only a limited measure of this when
defining classes, functions, and methods. In this example, the only
definitions that will be considered are those which are defined in the
top level of their context, e.g., a function defined by a def
statement at column zero of a module, but not a function defined
within a branch of an if ... else construct, though
there are some good reasons for doing so in some situations. Nesting
of definitions will be handled by the code developed in the example.
To construct the upper-level extraction methods, we need to know what
the parse tree structure looks like and how much of it we actually
need to be concerned about. Python uses a moderately deep parse tree
so there are a large number of intermediate nodes. It is important to
read and understand the formal grammar used by Python. This is
specified in the file `Grammar/Grammar' in the distribution.
Consider the simplest case of interest when searching for docstrings:
a module consisting of a docstring and nothing else. (See file
`docstring.py'.)
```text
"""Some documentation.
"""
```
Using the interpreter to take a look at the parse tree, we find a
bewildering mass of numbers and parentheses, with the documentation
buried deep in nested tuples.
```text
>>> import parser
>>> import pprint
>>> ast = parser.suite(open('docstring.py').read())
>>> tup = parser.ast2tuple(ast)
>>> pprint.pprint(tup)
(257,
(264,
(265,
(266,
(267,
(307,
(287,
(288,
(289,
(290,
(292,
(293,
(294,
(295,
(296,
(297,
(298,
(299,
(300, (3, '"""Some documentation.\012"""'))))))))))))))))),
(4, ''))),
(4, ''),
(0, ''))
```
The numbers at the first element of each node in the tree are the node
types; they map directly to terminal and non-terminal symbols in the
grammar. Unfortunately, they are represented as integers in the
internal representation, and the Python structures generated do not
change that. However, the symbol and token modules
provide symbolic names for the node types and dictionaries which map
from the integers to the symbolic names for the node types.
In the output presented above, the outermost tuple contains four
elements: the integer 257 and three additional tuples. Node
type 257 has the symbolic name file_input. Each of
these inner tuples contains an integer as the first element; these
integers, 264, 4, and 0, represent the node types
stmt, NEWLINE, and ENDMARKER,
respectively.
Note that these values may change depending on the version of Python
you are using; consult `symbol.py' and `token.py' for
details of the mapping. It should be fairly clear that the outermost
node is related primarily to the input source rather than the contents
of the file, and may be disregarded for the moment. The stmt
node is much more interesting. In particular, all docstrings are
found in subtrees which are formed exactly as this node is formed,
with the only difference being the string itself. The association
between the docstring in a similar tree and the defined entity (class,
function, or module) which it describes is given by the position of
the docstring subtree within the tree defining the described
structure.
By replacing the actual docstring with something to signify a variable
component of the tree, we allow a simple pattern matching approach to
check any given subtree for equivelence to the general pattern for
docstrings. Since the example demonstrates information extraction, we
can safely require that the tree be in tuple form rather than list
form, allowing a simple variable representation to be
['variable_name']. A simple recursive function can implement
the pattern matching, returning a boolean and a dictionary of variable
name to value mappings. (See file `example.py'.)
```text
from types import ListType, TupleType

def match(pattern, data, vars=None):
if vars is None:
vars = {}
if type(pattern) is ListType:
vars[pattern[0]] = data
return 1, vars
if type(pattern) is not TupleType:
return (pattern == data), vars
if len(data) != len(pattern):
return 0, vars
for pattern, data in map(None, pattern, data):
same, vars = match(pattern, data, vars)
if not same:
break
return same, vars
```
Using this simple representation for syntactic variables and the symbolic
node types, the pattern for the candidate docstring subtrees becomes
fairly readable. (See file `example.py'.)
```text
import symbol
import token

DOCSTRING_STMT_PATTERN = (
symbol.stmt,
(symbol.simple_stmt,
(symbol.small_stmt,
(symbol.expr_stmt,
(symbol.testlist,
(symbol.test,
(symbol.and_test,
(symbol.not_test,
(symbol.comparison,
(symbol.expr,
(symbol.xor_expr,
(symbol.and_expr,
(symbol.shift_expr,
(symbol.arith_expr,
(symbol.term,
(symbol.factor,
(symbol.power,
(symbol.atom,
(token.STRING, ['docstring'])
)))))))))))))))),
(token.NEWLINE, '')
))
```
Using the match() function with this pattern, extracting the
module docstring from the parse tree created previously is easy:
```text
>>> found, vars = match(DOCSTRING_STMT_PATTERN, tup[1])
>>> found
1
>>> vars
{'docstring': '"""Some documentation.\012"""'}
```
Once specific data can be extracted from a location where it is
expected, the question of where information can be expected
needs to be answered. When dealing with docstrings, the answer is
fairly simple: the docstring is the first stmt node in a code
block (file_input or suite node types). A module
consists of a single file_input node, and class and function
definitions each contain exactly one suite node. Classes and
functions are readily identified as subtrees of code block nodes which
start with (stmt, (compound_stmt, (classdef, ... or
(stmt, (compound_stmt, (funcdef, .... Note that these subtrees
cannot be matched by match() since it does not support multiple
sibling nodes to match without regard to number. A more elaborate
matching function could be used to overcome this limitation, but this
is sufficient for the example.
Given the ability to determine whether a statement might be a
docstring and extract the actual string from the statement, some work
needs to be performed to walk the parse tree for an entire module and
extract information about the names defined in each context of the
module and associate any docstrings with the names. The code to
perform this work is not complicated, but bears some explanation.
The public interface to the classes is straightforward and should
probably be somewhat more flexible. Each ``major'' block of the
module is described by an object providing several methods for inquiry
and a constructor which accepts at least the subtree of the complete
parse tree which it represents. The ModuleInfo constructor
accepts an optional name parameter since it cannot
otherwise determine the name of the module.
The public classes include ClassInfo, FunctionInfo,
and ModuleInfo. All objects provide the
methods get_name(), get_docstring(),
get_class_names(), and get_class_info(). The
ClassInfo objects support get_method_names() and
get_method_info() while the other classes provide
get_function_names() and get_function_info().
Within each of the forms of code block that the public classes
represent, most of the required information is in the same form and is
accessed in the same way, with classes having the distinction that
functions defined at the top level are referred to as ``methods.''
Since the difference in nomenclature reflects a real semantic
distinction from functions defined outside of a class, the
implementation needs to maintain the distinction.
Hence, most of the functionality of the public classes can be
implemented in a common base class, SuiteInfoBase, with the
accessors for function and method information provided elsewhere.
Note that there is only one class which represents function and method
information; this parallels the use of the def statement to
define both types of elements.
Most of the accessor functions are declared in SuiteInfoBase
and do not need to be overriden by subclasses. More importantly, the
extraction of most information from a parse tree is handled through a
method called by the SuiteInfoBase constructor. The example
code for most of the classes is clear when read alongside the formal
grammar, but the method which recursively creates new information
objects requires further examination. Here is the relevant part of
the SuiteInfoBase definition from `example.py':
```text
class SuiteInfoBase:
_docstring = ''
_name = ''

def __init__(self, tree = None):
self._class_info = {}
self._function_info = {}
if tree:
self._extract_info(tree)

def _extract_info(self, tree):
# extract docstring
if len(tree) == 2:
found, vars = match(DOCSTRING_STMT_PATTERN[1], tree[1])
else:
found, vars = match(DOCSTRING_STMT_PATTERN, tree[3])
if found:
self._docstring = eval(vars['docstring'])
# discover inner definitions
for node in tree[1:]:
found, vars = match(COMPOUND_STMT_PATTERN, node)
if found:
cstmt = vars['compound']
if cstmt[0] == symbol.funcdef:
name = cstmt[2][1]
self._function_info[name] = FunctionInfo(cstmt)
elif cstmt[0] == symbol.classdef:
name = cstmt[2][1]
self._class_info[name] = ClassInfo(cstmt)
```
After initializing some internal state, the constructor calls the
_extract_info() method. This method performs the bulk of the
information extraction which takes place in the entire example. The
extraction has two distinct phases: the location of the docstring for
the parse tree passed in, and the discovery of additional definitions
within the code block represented by the parse tree.
The initial if test determines whether the nested suite is of
the ``short form'' or the ``long form.'' The short form is used when
the code block is on the same line as the definition of the code
block, as in
```text
def square(x): "Square an argument."; return x ** 2
```
while the long form uses an indented block and allows nested
definitions:
```text
def make_power(exp):
"Make a function that raises an argument to the exponent `exp'."
def raiser(x, y=exp):
return x ** y
return raiser
```
When the short form is used, the code block may contain a docstring as
the first, and possibly only, small_stmt element. The
extraction of such a docstring is slightly different and requires only
a portion of the complete pattern used in the more common case. As
implemented, the docstring will only be found if there is only
one small_stmt node in the simple_stmt node.
Since most functions and methods which use the short form do not
provide a docstring, this may be considered sufficient. The
extraction of the docstring proceeds using the match() function
as described above, and the value of the docstring is stored as an
attribute of the SuiteInfoBase object.
After docstring extraction, a simple definition discovery
algorithm operates on the stmt nodes of the
suite node. The special case of the short form is not
tested; since there are no stmt nodes in the short form,
the algorithm will silently skip the single simple_stmt
node and correctly not discover any nested definitions.
Each statement in the code block is categorized as
a class definition, function or method definition, or
something else. For the definition statements, the name of the
element defined is extracted and a representation object
appropriate to the definition is created with the defining subtree
passed as an argument to the constructor. The repesentation objects
are stored in instance variables and may be retrieved by name using
the appropriate accessor methods.
The public classes provide any accessors required which are more
specific than those provided by the SuiteInfoBase class, but
the real extraction algorithm remains common to all forms of code
blocks. A high-level function can be used to extract the complete set
of information from a source file. (See file `example.py'.)
```text
def get_docs(fileName):
source = open(fileName).read()
import os
basename = os.path.basename(os.path.splitext(fileName)[0])
import parser
ast = parser.suite(source)
tup = parser.ast2tuple(ast)
return ModuleInfo(tup, basename)
```
This provides an easy-to-use interface to the documentation of a
module. If information is required which is not extracted by the code
of this example, the code may be extended at clearly defined points to
provide additional capabilities.
See Also:
symbol (useful constants representing internal nodes of the parse tree)
token (useful constants representing leaf nodes of the parse tree and
functions for testing node values)
---
node50.html
node47.html
node48.html
node1.html
node270.html
guido@python.org


Truth Value Testing

node6.html
node4.html
node4.html
node1.html
node270.html
---
## 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.)
---
guido@python.org


3.14 Standard Module symbol

node51.html
node27.html
node49.html
node1.html
node270.html
---
# 3.14 Standard Module symbol
This module provides constants which represent the numeric values of
internal nodes of the parse tree. Unlike most Python constants, these
use lower-case names. Refer to the file `Grammar/Grammar' in the
Python distribution for the defintions of the names in the context of
the language grammar. The specific numeric values which the names map
to may change between Python versions.
This module also provides one additional data object:
See Also:
parser (second example uses this module)
---
guido@python.org


3.15 Standard Module token

node52.html
node27.html
node50.html
node1.html
node270.html
---
# 3.15 Standard Module token
This module provides constants which represent the numeric values of
leaf nodes of the parse tree (terminal tokens). Refer to the file
`Grammar/Grammar' in the Python distribution for the defintions
of the names in the context of the language grammar. The specific
numeric values which the names map to may change between Python
versions.
This module also provides one data object and some functions. The
functions mirror definitions in the Python C header files.
See Also:
parser (second example uses this module)
---
guido@python.org


3.16 Standard Module keyword

node53.html
node27.html
node51.html
node1.html
node270.html
---
# 3.16 Standard Module keyword
This module allows a Python program to determine if a string is a
keyword. A single function is provided:
---
guido@python.org


3.17 Standard Module code

node54.html
node27.html
node52.html
node1.html
node270.html
---
# 3.17 Standard Module code
The code module defines operations pertaining to Python code
objects.
The code module defines the following functions:
%
---
guido@python.org


3.18 Standard Module pprint

node55.html
node27.html
node53.html
node1.html
node270.html
---
# 3.18 Standard Module pprint
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:
The PrettyPrinter class supports several derivative functions:
One more support function is also defined:
---
- PrettyPrinter Objects (node55.html#SECTION0041810000000000000000)
---
node55.html
node27.html
node53.html
node1.html
node270.html
guido@python.org


PrettyPrinter Objects

node56.html
node54.html
node54.html
node1.html
node270.html
---
## PrettyPrinter Objects
PrettyPrinter instances (returned by PrettyPrinter() above)
have the following methods.
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.
---
guido@python.org


3.19 Standard Module dis

node57.html
node27.html
node55.html
node1.html
node270.html
---
# 3.19 Standard Module dis
The dis module supports the analysis of Python byte code by
disassembling it. Since there is no Python assembler, this module
defines the Python assembly language. The Python byte code which
this module takes as an input is defined in the file
`Include/opcode.h' and used by the compiler and the interpreter.
Example: Given the function myfunc
```text
def myfunc(alist):
return len(alist)
```
the following command can be used to get the disassembly of myfunc():
```text
>>> dis.dis(myfunc)
0 SET_LINENO 1

3 SET_LINENO 2
6 LOAD_GLOBAL 0 (len)
9 LOAD_FAST 0 (alist)
12 CALL_FUNCTION 1
15 RETURN_VALUE
16 LOAD_CONST 0 (None)
19 RETURN_VALUE
```
The dis module defines the following functions:
---
- Python Byte Code Instructions (node57.html#SECTION0041910000000000000000)
---
node57.html
node27.html
node55.html
node1.html
node270.html
guido@python.org


Python Byte Code Instructions

node58.html
node56.html
node56.html
node1.html
node270.html
---
## Python Byte Code Instructions
The Python compiler currently generates the following byte code
instructions.
Unary Operations take the top of the stack, apply the operation, and
push the result back on the stack.
Binary operations remove the top of the stack (TOS) and the second top-most
stack item (TOS1) from the stack. They perform the operation, and put the
result back on the stack.
The slice opcodes take up to three parameters.
Slice assignment needs even an additional parameter. As any statement,
they put nothing on the stack.
All of the following opcodes expect arguments. An argument is two
bytes, with the more significant byte last.
---
node58.html
node56.html
node56.html
node1.html
node270.html
guido@python.org


3.20 Standard Module site

node59.html
node27.html
node57.html
node1.html
node270.html
---
# 3.20 Standard Module site
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 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 Mac or Windows) or it uses
first `lib/pythonversion/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 inspected for path
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.
For example, suppose sys.prefix and sys.exec_prefix are
set to `/usr/local'. The Python , library is then
installed in `/usr/local/lib/python,'. Suppose this has a
subdirectory `/usr/local/python,/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:
```text
# foo package configuration

foo
bar
bletch
```
and `bar.pth' contains:
```text
# bar package configuration

bar
```
Then the following directories are added to sys.path, in this
order:
```text
/usr/local/python1.5/site-packages/bar
/usr/local/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,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,sitecustomize is still attempted.
---
node59.html
node27.html
node57.html
node1.html
node270.html
guido@python.org


3.21 Standard Module user

node60.html
node27.html
node58.html
node1.html
node270.html
---
# 3.21 Standard Module user
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
```text
import user
```
The user module looks for a file `.pythonrc.py' in the user's
home directory and if it can be opened, exececutes 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:
```text
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 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:
site (site-wide customization mechanism)
---
node60.html
node27.html
node58.html
node1.html
node270.html
guido@python.org


Boolean Operations

node7.html
node4.html
node5.html
node1.html
node270.html
---
## Boolean Operations
These are the Boolean operations, ordered by ascending priority:
Operation | Result | Notes
,
Notes:
---
guido@python.org


Built-in Module __builtin__

node61.html
node27.html
node59.html
node1.html
node270.html
---
# Built-in Module __builtin__
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 2.3 (node26.html#builtinfuncs), ``Built-in
Functions.''
---
guido@python.org


Built-in Module __main__

node62.html
node27.html
node60.html
node1.html
node270.html
---
# Built-in Module __main__
This module represents the (otherwise anonymous) scope in which the
interpreter's main program executes -- commands read either from
standard input or from a script file.
---
guido@python.org


4 String Services

node63.html
lib.html
node61.html
node1.html
node270.html
---
# 4 String Services
The modules described in this chapter provide a wide range of string
manipulation operations. Here's an overview:
---
- 4.1 Standard Module string (node63.html#SECTION005100000000000000000)
4.2 Built-in Module re (node64.html#SECTION005200000000000000000)
- Regular Expression Syntax (node65.html#SECTION005210000000000000000)
Module Contents (node66.html#SECTION005220000000000000000)
Regular Expression Objects (node67.html#SECTION005230000000000000000)
Match Objects (node68.html#SECTION005240000000000000000)
4.3 Built-in Module regex (node69.html#SECTION005300000000000000000)
- Regular Expressions (node70.html#SECTION005310000000000000000)
Module Contents (node71.html#SECTION005320000000000000000)
4.4 Standard Module regsub (node72.html#SECTION005400000000000000000)
4.5 Built-in Module struct (node73.html#SECTION005500000000000000000)
4.6 Standard Module StringIO (node74.html#SECTION005600000000000000000)
4.7 Built-in Module soundex (node75.html#SECTION005700000000000000000)
---
guido@python.org