12.1.1 The Formatter Interface

module-formatter.html | module-formatter.html | formatter-impls.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
12.1 formatter (module-formatter.html)
Up:
12.1 formatter (module-formatter.html)
Next:
12.1.2 Formatter Implementations (formatter-impls.html)
---
## 12.1.1 The Formatter Interface
Interfaces to create formatters are dependent on the specific
formatter class being instantiated. The interfaces described below
are the required interfaces which all formatters must support once
initialized.
One data element is defined at the module level:
The following attributes are defined for formatter instance objects:


20.4.3 FORMS Objects

form-objects.html | module-fl.html | module-fl-constants.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
20.4.2 Form Objects (form-objects.html)
Up:
20.4 fl (module-fl.html)
Next:
20.5 FL (module-fl-constants.html)
---
## 20.4.3 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:


3.4.1 Example

module-fpectl.html | module-fpectl.html | node43.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
3.4 fpectl (module-fpectl.html)
Up:
3.4 fpectl (module-fpectl.html)
Next:
3.4.2 Limitations and other (node43.html)
---
## 3.4.1 Example
The following example demonstrates how to start up and test operation of
the fpectl module.
```text

>>> import fpectl
>>> import fpetest
>>> fpectl.turnon_sigfpe()
>>> fpetest.test()
overflow PASS
FloatingPointError: Overflow

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


Front Matter

lib.html | lib.html | contents.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
Python Library Reference (lib.html)
Up:
Python Library Reference (lib.html)
Next:
---
# Front Matter
Copyright © 2001, 2002, 2003 Python Software Foundation.
All rights reserved.
Copyright © 2000 BeOpen.com.
All rights reserved.
Copyright © 1995-2000 Corporation for National Research Initiatives.
All rights reserved.
Copyright © 1991-1995 Stichting Mathematisch Centrum.
All rights reserved.
See the end of this document for complete license and permissions
information.
### Abstract:
Python is an extensible, interpreted, object-oriented programming
language. It supports a wide range of applications, from simple text
processing scripts to interactive Web browsers.
While the Python Reference Manual (../ref/ref.html)
describes the exact syntax and semantics of the language, it does not
describe the standard library that is distributed with the language,
and which greatly enhances its immediate usability. This library
contains built-in modules (written in C) that provide access to system
functionality such as file I/O that would otherwise be inaccessible to
Python programmers, as well as modules written in Python that provide
standardized solutions for many problems that occur in everyday
programming. Some of these modules are explicitly designed to
encourage and enhance the portability of Python programs.
This library reference manual documents Python's standard library, as
well as many optional library modules (which may or may not be
available, depending on whether the underlying platform supports them
and on the configuration choices made at compile time). It also
documents the standard types of the language and its built-in
functions and exceptions, many of which are not or incompletely
documented in the Reference Manual.
This manual assumes basic knowledge about the Python language. For an
informal introduction to Python, see the
Python Tutorial (../tut/tut.html); the
Python Reference Manual (../ref/ref.html) remains the
highest authority on syntactic and semantic questions. Finally, the
manual entitled Extending and Embedding
the Python Interpreter (../ext/ext.html) describes how to add new extensions to Python
and how to embed it in other applications.


11.5.16 FTPHandler Objects

file-handler-objects.html | module-urllib2.html | cacheftp-handler-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
11.5.15 FileHandler Objects (file-handler-objects.html)
Up:
11.5 urllib2 (module-urllib2.html)
Next:
11.5.17 CacheFTPHandler Objects (cacheftp-handler-objects.html)
---
## 11.5.16 FTPHandler Objects


11.7.1 FTP Objects

module-ftplib.html | module-ftplib.html | module-gopherlib.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
11.7 ftplib (module-ftplib.html)
Up:
11.7 ftplib (module-ftplib.html)
Next:
11.8 gopherlib (module-gopherlib.html)
---
## 11.7.1 FTP Objects
Several methods are available in two flavors: one for handling text
files and another for binary files. These are named for the command
which is used followed by "lines" for the text version or
"binary" for the binary version.
FTP instances have the following methods:


Index

modindex.html | lib.html | about.html | Python Library Reference | contents.html | modindex.html
Previous:
Module Index (modindex.html)
Up:
Python Library Reference (lib.html)
Next:
About this document ... (about.html)
---
## Index
---
Symbols (#letter-Symbols) |
_ (#letter-_) |
a (#letter-a) |
b (#letter-b) |
c (#letter-c) |
d (#letter-d) |
e (#letter-e) |
f (#letter-f) |
g (#letter-g) |
h (#letter-h) |
i (#letter-i) |
j (#letter-j) |
k (#letter-k) |
l (#letter-l) |
m (#letter-m) |
n (#letter-n) |
o (#letter-o) |
p (#letter-p) |
q (#letter-q) |
r (#letter-r) |
s (#letter-s) |
t (#letter-t) |
u (#letter-u) |
v (#letter-v) |
w (#letter-w) |
x (#letter-x) |
y (#letter-y) |
z (#letter-z)
---
## Symbols
---
## _ (underscore)
---
## A
---
## B
---
## C
---
## D
---
## E
---
## F
---
## G
---
## H
---
## I
---
## J
---
## K
---
## L
---
## M
---
## N
---
## O
---
## P
---
## Q
---
## R
---
## S
---
## T
---
## U
---
## V
---
## W
---
## X
---
## Y
---
## Z


11.5.18 GopherHandler Objects

cacheftp-handler-objects.html | module-urllib2.html | unknown-handler-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
11.5.17 CacheFTPHandler Objects (cacheftp-handler-objects.html)
Up:
11.5 urllib2 (module-urllib2.html)
Next:
11.5.19 UnknownHandler Objects (unknown-handler-objects.html)
---
## 11.5.18 GopherHandler Objects


22.2.1 Registry Handle Objects

module--winreg.html | module--winreg.html | module-winsound.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
22.2 _winreg - Windows (module--winreg.html)
Up:
22.2 _winreg - Windows (module--winreg.html)
Next:
22.3 winsound (module-winsound.html)
---
## 22.2.1 Registry Handle Objects
This object wraps a Windows HKEY object, automatically closing it when
the object is destroyed. To guarantee cleanup, you can call either
the Close() method on the object, or the
CloseKey() function.
All registry functions in this module return one of these objects.
All registry functions in this module which accept a handle object
also accept an integer, however, use of the handle object is
encouraged.
Handle objects provide semantics for __nonzero__() - thus
```text

if handle:
print "Yes"
```
will print `Yes` if the handle is currently valid (has not been
closed or detached).
The object also support comparison semantics, so handle
objects will compare true if they both reference the same
underlying Windows handle value.
Handle objects can be converted to an integer (eg, using the
builtin int() function, in which case the underlying
Windows handle value is returned. You can also use the
Detach() method to return the integer handle, and
also disconnect the Windows handle from the handle object.


10.9.3 Example Usage

module-hotshot.stats.html | module-hotshot.html | module-timeit.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
10.9.2 Using hotshot data (module-hotshot.stats.html)
Up:
10.9 hotshot (module-hotshot.html)
Next:
10.10 timeit (module-timeit.html)
---
## 10.9.3 Example Usage
Note that this example runs the python ``benchmark'' pystones. It can
take some time to run, and will produce large output files.


10.9.1 Profile Objects

module-hotshot.html | module-hotshot.html | module-hotshot.stats.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
10.9 hotshot (module-hotshot.html)
Up:
10.9 hotshot (module-hotshot.html)
Next:
10.9.2 Using hotshot data (module-hotshot.stats.html)
---
## 10.9.1 Profile Objects
Profile objects have the following methods:


13.3.1 HTMLParser Objects

module-htmllib.html | module-htmllib.html | module-htmlentitydefs.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
13.3 htmllib (module-htmllib.html)
Up:
13.3 htmllib (module-htmllib.html)
Next:
13.4 htmlentitydefs (module-htmlentitydefs.html)
---
## 13.3.1 HTMLParser Objects
In addition to tag methods, the HTMLParser class provides some
additional methods and instance variables for use within tag methods.


13.1.1 Example HTML Parser Application

module-HTMLParser.html | module-HTMLParser.html | module-sgmllib.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
13.1 HTMLParser (module-HTMLParser.html)
Up:
13.1 HTMLParser (module-HTMLParser.html)
Next:
13.2 sgmllib (module-sgmllib.html)
---
## 13.1.1 Example HTML Parser Application
As a basic example, below is a very basic HTML parser that uses the
HTMLParser class to print out tags as they are encountered:


11.5.8 HTTPBasicAuthHandler Objects

abstract-basic-auth-handler.html | module-urllib2.html | proxy-basic-auth-handler.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
11.5.7 AbstractBasicAuthHandler Objects (abstract-basic-auth-handler.html)
Up:
11.5 urllib2 (module-urllib2.html)
Next:
11.5.9 ProxyBasicAuthHandler Objects (proxy-basic-auth-handler.html)
---
## 11.5.8 HTTPBasicAuthHandler Objects


11.5.11 HTTPDigestAuthHandler Objects

abstract-digest-auth-handler.html | module-urllib2.html | proxy-digest-auth-handler.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
11.5.10 AbstractDigestAuthHandler Objects (abstract-digest-auth-handler.html)
Up:
11.5 urllib2 (module-urllib2.html)
Next:
11.5.12 ProxyDigestAuthHandler Objects (proxy-digest-auth-handler.html)
---
## 11.5.11 HTTPDigestAuthHandler Objects


11.5.13 HTTPHandler Objects

proxy-digest-auth-handler.html | module-urllib2.html | https-handler-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
11.5.12 ProxyDigestAuthHandler Objects (proxy-digest-auth-handler.html)
Up:
11.5 urllib2 (module-urllib2.html)
Next:
11.5.14 HTTPSHandler Objects (https-handler-objects.html)
---
## 11.5.13 HTTPHandler Objects


11.5.6 HTTPPasswordMgr Objects

proxy-handler.html | module-urllib2.html | abstract-basic-auth-handler.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
11.5.5 ProxyHandler Objects (proxy-handler.html)
Up:
11.5 urllib2 (module-urllib2.html)
Next:
11.5.7 AbstractBasicAuthHandler Objects (abstract-basic-auth-handler.html)
---
## 11.5.6 HTTPPasswordMgr Objects
These methods are available on HTTPPasswordMgr and
HTTPPasswordMgrWithDefaultRealm objects.


11.5.4 HTTPRedirectHandler Objects

base-handler-objects.html | module-urllib2.html | proxy-handler.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
11.5.3 BaseHandler Objects (base-handler-objects.html)
Up:
11.5 urllib2 (module-urllib2.html)
Next:
11.5.5 ProxyHandler Objects (proxy-handler.html)
---
## 11.5.4 HTTPRedirectHandler Objects
Note:
Some HTTP redirections require action from this module's client
code. If this is the case, HTTPError is raised. See
RFC 2616 (http://www.faqs.org/rfcs/rfc2616.html) for details of the precise meanings of the various
redirection codes.


11.6.1 HTTPConnection Objects

module-httplib.html | module-httplib.html | httpresponse-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
11.6 httplib (module-httplib.html)
Up:
11.6 httplib (module-httplib.html)
Next:
11.6.2 HTTPResponse Objects (httpresponse-objects.html)
---
## 11.6.1 HTTPConnection Objects
HTTPConnection instances have the following methods:


11.6.3 Examples

httpresponse-objects.html | module-httplib.html | module-ftplib.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
11.6.2 HTTPResponse Objects (httpresponse-objects.html)
Up:
11.6 httplib (module-httplib.html)
Next:
11.7 ftplib (module-ftplib.html)
---
## 11.6.3 Examples
Here is an example session that uses the "GET" method:
```text

>>> import httplib
>>> conn = httplib.HTTPConnection("www.python.org")
>>> conn.request("GET", "/index.html")
>>> r1 = conn.getresponse()
>>> print r1.status, r1.reason
200 OK
>>> data1 = r1.read()
>>> conn.request("GET", "/parrot.spam")
>>> r2 = conn.getresponse()
>>> print r2.status, r2.reason
404 Not Found
>>> data2 = r2.read()
>>> conn.close()
```
Here is an example session that shows how to "POST" requests:


11.6.2 HTTPResponse Objects

httpconnection-objects.html | module-httplib.html | httplib-examples.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
11.6.1 HTTPConnection Objects (httpconnection-objects.html)
Up:
11.6 httplib (module-httplib.html)
Next:
11.6.3 Examples (httplib-examples.html)
---
## 11.6.2 HTTPResponse Objects
HTTPResponse instances have the following methods and attributes:


11.5.14 HTTPSHandler Objects

http-handler-objects.html | module-urllib2.html | file-handler-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
11.5.13 HTTPHandler Objects (http-handler-objects.html)
Up:
11.5 urllib2 (module-urllib2.html)
Next:
11.5.15 FileHandler Objects (file-handler-objects.html)
---
## 11.5.14 HTTPSHandler Objects


16.5 Idle

pen-rawpen-objects.html | tkinter.html | node663.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
16.4.1 Pen and RawPen (pen-rawpen-objects.html)
Up:
16. Graphical User Interfaces (tkinter.html)
Next:
16.5.1 Menus (node663.html)
---
# 16.5 Idle
Idle is the Python IDE built with the Tkinter (module-Tkinter.html) GUI toolkit.
IDLE has the following features:
- coded in 100% pure Python, using the Tkinter (module-Tkinter.html) GUI toolkit
- cross-platform: works on Windows and Unix (on Mac OS, there are
currently problems with Tcl/Tk)
- multi-window text editor with multiple undo, Python colorizing
and many other features, e.g. smart indent and call tips
- Python shell window (a.k.a. interactive interpreter)
- debugger (not complete, but you can set breakpoints, view and step)


11.10.2 IMAP4 Example

imap4-objects.html | module-imaplib.html | module-nntplib.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
11.10.1 IMAP4 Objects (imap4-objects.html)
Up:
11.10 imaplib (module-imaplib.html)
Next:
11.11 nntplib (module-nntplib.html)
---
## 11.10.2 IMAP4 Example
Here is a minimal example (without error checking) that opens a
mailbox and retrieves and prints all messages:


11.10.1 IMAP4 Objects

module-imaplib.html | module-imaplib.html | imap4-example.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
11.10 imaplib (module-imaplib.html)
Up:
11.10 imaplib (module-imaplib.html)
Next:
11.10.2 IMAP4 Example (imap4-example.html)
---
## 11.10.1 IMAP4 Objects
All IMAP4rev1 commands are represented by methods of the same name,
either upper-case or lower-case.
All arguments to commands are converted to strings, except for
"AUTHENTICATE", and the last argument to "APPEND" which is
passed as an IMAP4 literal. If necessary (the string contains IMAP4
protocol-sensitive characters and isn't enclosed with either
parentheses or double quotes) each string is quoted. However, the
password argument to the "LOGIN" command is always quoted.
If you want to avoid having an argument string quoted
(eg: the flags argument to "STORE") then enclose the string in
parentheses (eg: `r'(\Deleted)'`).
Each command returns a tuple: `( type , [ data ,
...])` where type is usually `'OK'` or `'NO'`,
and data is either the text from the command response, or
mandated results from the command. Each data
is either a string, or a tuple. If a tuple, then the first part
is the header of the response, and the second part contains
the data (ie: 'literal' value).
An IMAP4 instance has the following methods:
Instances of IMAP4_SSL have just one additional method:
The following attributes are defined on instances of IMAP4:


set-example.html | module-sets.html | module-itertools.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
5.12.2 Example (set-example.html)
Up:
5.12 sets (module-sets.html)
Next:
5.13 itertools (module-itertools.html)
---
## 5.12.3 Protocol for automatic conversion to immutable
Sets can only contain immutable elements. For convenience, mutable
Set objects are automatically copied to an ImmutableSet
before being added as a set element.
The mechanism is to always add a hashable element, or if it is not
hashable, the element is checked to see if it has an
__as_immutable__() method which returns an immutable equivalent.
Since Set objects have a __as_immutable__() method
returning an instance of ImmutableSet, it is possible to
construct sets of sets.
A similar mechanism is needed by the __contains__() and
remove() methods which need to hash an element to check
for membership in a set. Those methods check an element for hashability
and, if not, check for a __as_temporarily_immutable__() method
which returns the element wrapped by a class that provides temporary
methods for __hash__(), __eq__(), and __ne__().
The alternate mechanism spares the need to build a separate copy of
the original mutable object.
Set objects implement the __as_temporarily_immutable__()
method which returns the Set object wrapped by a new class
_TemporarilyImmutableSet.


13.12.2 IncrementalParser Objects

xmlreader-objects.html | module-xml.sax.xmlreader.html | locator-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
13.12.1 XMLReader Objects (xmlreader-objects.html)
Up:
13.12 xml.sax.xmlreader (module-xml.sax.xmlreader.html)
Next:
13.12.3 Locator Objects (locator-objects.html)
---
## 13.12.2 IncrementalParser Objects
Instances of IncrementalParser offer the following additional
methods:


Python Library Reference

../index.html | front.html | Python Library Reference | contents.html | modindex.html | genindex.html
Up:
Python Documentation Index (../index.html)
Next:
Front Matter (front.html)
---
# Python Library Reference
Guido van Rossum
Fred L. Drake, Jr., editor
PythonLabs
Email: python-docs@python.org
Release 2.3
July 29, 2003


13.12.4 InputSource Objects

locator-objects.html | module-xml.sax.xmlreader.html | attributes-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
13.12.3 Locator Objects (locator-objects.html)
Up:
13.12 xml.sax.xmlreader (module-xml.sax.xmlreader.html)
Next:
13.12.5 The Attributes Interface (attributes-objects.html)
---
## 13.12.4 InputSource Objects


3.11.3 Classes and functions

inspect-source.html | module-inspect.html | inspect-stack.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
3.11.2 Retrieving source code (inspect-source.html)
Up:
3.11 inspect (module-inspect.html)
Next:
3.11.4 The interpreter stack (inspect-stack.html)
---
## 3.11.3 Classes and functions


3.11.2 Retrieving source code

inspect-types.html | module-inspect.html | inspect-classes-functions.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
3.11.1 Types and members (inspect-types.html)
Up:
3.11 inspect (module-inspect.html)
Next:
3.11.3 Classes and functions (inspect-classes-functions.html)
---
## 3.11.2 Retrieving source code


3.11.4 The interpreter stack

inspect-classes-functions.html | module-inspect.html | module-traceback.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
3.11.3 Classes and functions (inspect-classes-functions.html)
Up:
3.11 inspect (module-inspect.html)
Next:
3.12 traceback (module-traceback.html)
---
## 3.11.4 The interpreter stack
When the following functions return ``frame records,'' each record
is a tuple of six items: the frame object, the filename,
the line number of the current line, the function name, a list of
lines of context from the source code, and the index of the current
line within that list.
The optional context argument specifies the number of lines of
context to return, which are centered around the current line.
Warning:
Keeping references to frame objects, as found in
the first element of the frame records these functions return, can
cause your program to create reference cycles. Once a reference cycle
has been created, the lifespan of all objects which can be accessed
from the objects which form the cycle can become much longer even if
Python's optional cycle detector is enabled. If such cycles must be
created, it is important to ensure they are explicitly broken to avoid
the delayed destruction of objects and increased memory consumption
which occurs.
Stackframes stored directly or indirectly in local variables can
easily cause reference cycles. Though the cycle detector will catch
these, destruction of the frames (and local variables) can be made
deterministic by removing the cycle in a finally clause.
This is also important if the cycle detector was disabled when Python
was compiled or using gc.disable(). For example:


3.11.1 Types and members

module-inspect.html | module-inspect.html | inspect-source.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
3.11 inspect (module-inspect.html)
Up:
3.11 inspect (module-inspect.html)
Next:
3.11.2 Retrieving source code (inspect-source.html)
---
## 3.11.1 Types and members
The getmembers() function retrieves the members
of an object such as a class or module.
The nine functions whose names begin with ``is'' are mainly
provided as convenient choices for the second argument to
getmembers(). They also help you determine when
you can expect to find the following special attributes:
Note:
(1): Changed in version 2.2:
im_class used to refer to the class that
defined the method.


11. Internet Protocols and Support

node397.html | lib.html | module-webbrowser.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
10.10.2 Examples (node397.html)
Up:
Python Library Reference (lib.html)
Next:
11.1 webbrowser (module-webbrowser.html)
---
# 11. Internet Protocols and Support
The modules described in this chapter implement Internet protocols and
support for related technology. They are all implemented in Python.
Most of these modules require the presence of the system-dependent
module socket (module-socket.html), which is currently
supported on most popular platforms. Here is an overview:


3.23.1 Interactive Interpreter Objects

module-code.html | module-code.html | console-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
3.23 code (module-code.html)
Up:
3.23 code (module-code.html)
Next:
3.23.2 Interactive Console Objects (console-objects.html)
---
## 3.23.1 Interactive Interpreter Objects


1. Introduction

contents.html | lib.html | builtin.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
Up:
Python Library Reference (lib.html)
Next:
2. Built-In Objects (builtin.html)
---
# 1. Introduction
The ``Python library'' contains several different kinds of components.
It contains data types that would normally be considered part of the
``core'' of a language, such as numbers and lists. For these types,
the Python language core defines the form of literals and places some
constraints on their semantics, but does not fully define the
semantics. (On the other hand, the language core does define
syntactic properties like the spelling and priorities of operators.)
The library also contains built-in functions and exceptions --
objects that can be used by all Python code without the need of an
import statement. Some of these are defined by the core
language, but many are not essential for the core semantics and are
only described here.
The bulk of the library, however, consists of a collection of modules.
There are many ways to dissect this collection. Some modules are
written in C and built in to the Python interpreter; others are
written in Python and imported in source form. Some modules provide
interfaces that are highly specific to Python, like printing a stack
trace; some provide interfaces that are specific to particular
operating systems, such as access to specific hardware; others provide
interfaces that are
specific to a particular application domain, like the World Wide Web.
Some modules are available in all versions and ports of Python; others
are only available when the underlying system supports or requires
them; yet others are available only when a particular configuration
option was chosen at the time when Python was compiled and installed.
This manual is organized ``from the inside out:'' it first describes
the built-in data types, then the built-in functions and exceptions,
and finally the modules, grouped in chapters of related modules. The
ordering of the chapters as well as the ordering of the modules within
each chapter is roughly from most relevant to least important.
This means that if you start reading this manual from the start, and
skip to the next chapter when you get bored, you will get a reasonable
overview of the available modules and application areas that are
supported by the Python library. Of course, you don't have to
read it like a novel -- you can also browse the table of contents (in
front of the manual), or look for a specific function, module or term
in the index (in the back). And finally, if you enjoy learning about
random subjects, you choose a random page number (see module
random (module-random.html)) and read a section or two. Regardless of the
order in which you read the sections of this manual, it helps to start
with chapter 2 (builtin.html#builtin), ``Built-in Types, Exceptions and
Functions,'' as the remainder of the manual assumes familiarity with
this material.
Let the show begin!


5.13.2 Examples

itertools-functions.html | module-itertools.html | module-ConfigParser.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
5.13.1 Itertool functions (itertools-functions.html)
Up:
5.13 itertools (module-itertools.html)
Next:
5.14 ConfigParser (module-ConfigParser.html)
---
## 5.13.2 Examples
The following examples show common uses for each tool and
demonstrate ways they can be combined.
```text

>>> amounts = [120.15, 764.05, 823.14]
>>> for checknum, amount in izip(count(1200), amounts):
... print 'Check %d is for $%.2f' % (checknum, amount)
...
Check 1200 is for $120.15
Check 1201 is for $764.05
Check 1202 is for $823.14

>>> import operator
>>> for cube in imap(operator.pow, xrange(1,4), repeat(3)):
... print cube
...
1
8
27

>>> reportlines = ['EuroPython', 'Roster', '', 'alex', '', 'laura',
'', 'martin', '', 'walter', '', 'samuele']
>>> for name in islice(reportlines, 3, None, 2):
... print name.title()
...
Alex
Laura
Martin
Walter
Samuele
```
This section has further examples of how itertools can be combined.
Note that enumerate() and iteritems() already
have highly efficient implementations in Python. They are only
included here to illustrate how higher level tools can be created
from building blocks.


5.13.1 Itertool functions

module-itertools.html | module-itertools.html | itertools-example.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
5.13 itertools (module-itertools.html)
Up:
5.13 itertools (module-itertools.html)
Next:
5.13.2 Examples (itertools-example.html)
---
## 5.13.1 Itertool functions
The following module functions all construct and return iterators.
Some provide streams of infinite length, so they should only be accessed
by functions or loops that truncate the stream.


18. Python Language Services

module-Bastion.html | lib.html | module-parser.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
17.2 Bastion (module-Bastion.html)
Up:
Python Library Reference (lib.html)
Next:
18.1 parser (module-parser.html)
---
# 18. Python Language Services
Python provides a number of modules to assist in working with the
Python language. These module support tokenizing, parsing, syntax
analysis, bytecode disassembly, and various other facilities.
These modules include:


5.3.3 Re-using old test code

organizing-tests.html | module-unittest.html | unittest-contents.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
5.3.2 Organizing test code (organizing-tests.html)
Up:
5.3 unittest (module-unittest.html)
Next:
5.3.4 Classes and functions (unittest-contents.html)
---
## 5.3.3 Re-using old test code
Some users will find that they have existing test code that they would
like to run from PyUnit, without converting every old test function to
a TestCase subclass.
For this reason, PyUnit provides a FunctionTestCase class.
This subclass of TestCase can be used to wrap an existing test
function. Set-up and tear-down functions can also optionally be
wrapped.
Given the following test function:
```text

def testSomething():
something = makeSomething()
assert something.name is not None
# ...
```
one can create an equivalent test case instance as follows:
```text

testcase = unittest.FunctionTestCase(testSomething)
```
If there are additional set-up and tear-down methods that should be
called as part of the test case's operation, they can also be provided:
```text

testcase = unittest.FunctionTestCase(testSomething,
setUp=makeSomethingDB,
tearDown=deleteSomethingDB)
```
Note:
PyUnit supports the use of AssertionError
as an indicator of test failure, but does not recommend it. Future
versions may treat AssertionError differently.


Python Library Reference


6.26.3 Access to message catalogs

embedding-locale.html | module-locale.html | module-gettext.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
6.26.2 For extension writers (embedding-locale.html)
Up:
6.26 locale (module-locale.html)
Next:
6.27 gettext (module-gettext.html)
---
## 6.26.3 Access to message catalogs
The locale module exposes the C library's gettext interface on systems
that provide this interface. It consists of the functions
gettext(), dgettext(), dcgettext(),
textdomain(), and bindtextdomain(). These are
similar to the same functions in the gettext (module-gettext.html) module, but use
the C library's binary format for message catalogs, and the C
library's search algorithms for locating message catalogs.


13.12.3 Locator Objects

incremental-parser-objects.html | module-xml.sax.xmlreader.html | input-source-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
13.12.2 IncrementalParser Objects (incremental-parser-objects.html)
Up:
13.12 xml.sax.xmlreader (module-xml.sax.xmlreader.html)
Next:
13.12.4 InputSource Objects (input-source-objects.html)
---
## 13.12.3 Locator Objects
Instances of Locator provide these methods:


7.5.1 Lock Objects

module-threading.html | module-threading.html | rlock-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
7.5 threading (module-threading.html)
Up:
7.5 threading (module-threading.html)
Next:
7.5.2 RLock Objects (rlock-objects.html)
---
## 7.5.1 Lock Objects
A primitive lock is a synchronization primitive that is not owned
by a particular thread when locked. In Python, it is currently
the lowest level synchronization primitive available, implemented
directly by the thread (module-thread.html) extension module.
A primitive lock is in one of two states, ``locked'' or ``unlocked''.
It is created in the unlocked state. It has two basic methods,
acquire() and release(). When the state is
unlocked, acquire() changes the state to locked and returns
immediately. When the state is locked, acquire() blocks
until a call to release() in another thread changes it to
unlocked, then the acquire() call resets it to locked and
returns. The release() method should only be called in the
locked state; it changes the state to unlocked and returns
immediately. When more than one thread is blocked in
acquire() waiting for the state to turn to unlocked, only one
thread proceeds when a release() call resets the state to
unlocked; which one of the waiting threads proceeds is not defined,
and may vary across implementations.
All methods are executed atomically.


12.4.1 Mailbox Objects

module-mailbox.html | module-mailbox.html | module-mhlib.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
12.4 mailbox (module-mailbox.html)
Up:
12.4 mailbox (module-mailbox.html)
Next:
12.5 mhlib (module-mhlib.html)
---
## 12.4.1 Mailbox Objects
All implementations of mailbox objects are iterable objects, and
have one externally visible method. This method is used by iterators
created from mailbox objects and may also be used directly.


13. Structured Markup Processing Tools

node549.html | lib.html | module-HTMLParser.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
12.20.5 Examples (node549.html)
Up:
Python Library Reference (lib.html)
Next:
13.1 HTMLParser (module-HTMLParser.html)
---
# 13. Structured Markup Processing Tools
Python supports a variety of modules to work with various forms of
structured data markup. This includes modules to work with the
Standard Generalized Markup Language (SGML) and the Hypertext Markup
Language (HTML), and several interfaces for working with the
Extensible Markup Language (XML).
It is important to note that modules in the xml package
require that there be at least one SAX-compliant XML parser available.
Starting with Python 2.3, the Expat parser is included with Python, so
the xml.parsers.expat (module-xml.parsers.expat.html) module will always be available.
You may still want to be aware of the PyXML add-on
package (http://pyxml.sourceforge.net/); that package provides an
extended set of XML libraries for Python.
The documentation for the xml.dom and xml.sax
packages are the definition of the Python bindings for the DOM and SAX
interfaces.
HTMLParser (module-HTMLParser.html) | A simple parser that can handle HTML and XHTML.
sgmllib (module-sgmllib.html) | Only as much of an SGML parser as needed to parse HTML.
htmllib (module-htmllib.html) | A parser for HTML documents.
htmlentitydefs (module-htmlentitydefs.html) | Definitions of HTML general entities.
xml.parsers.expat (module-xml.parsers.expat.html) | An interface to the Expat non-validating XML parser.
xml.dom (module-xml.dom.html) | Document Object Model API for Python.
xml.dom.minidom (module-xml.dom.minidom.html) | Lightweight Document Object Model (DOM) implementation.
xml.dom.pulldom (module-xml.dom.pulldom.html) | Support for building partial DOM trees from SAX events.
xml.sax (module-xml.sax.html) | Package containing SAX2 base classes and convenience
functions.
xml.sax.handler (module-xml.sax.handler.html) | Base classes for SAX event handlers.
xml.sax.saxutils (module-xml.sax.saxutils.html) | Convenience functions and classes for use with SAX.
xml.sax.xmlreader (module-xml.sax.xmlreader.html) | Interface which SAX-compliant XML parsers must implement.
xmllib (module-xmllib.html) | A parser for XML documents.


4.2.5 Match Objects

re-objects.html | module-re.html | node108.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
4.2.4 Regular Expression Objects (re-objects.html)
Up:
4.2 re (module-re.html)
Next:
4.2.6 Examples (node108.html)
---
## 4.2.5 Match Objects
MatchObject instances support the following methods and
attributes:


4.2.2 Matching vs Searching

re-syntax.html | module-re.html | node105.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
4.2.1 Regular Expression Syntax (re-syntax.html)
Up:
4.2 re (module-re.html)
Next:
4.2.3 Module Contents (node105.html)
---
## 4.2.2 Matching vs Searching
Python offers two different primitive operations based on regular
expressions: match and search. If you are accustomed to Perl's
semantics, the search operation is what you're looking for. See the
search() function and corresponding method of compiled
regular expression objects.
Note that match may differ from search using a regular expression
beginning with "^":
"^" matches only at the
start of the string, or in MULTILINE mode also immediately
following a newline. The ``match'' operation succeeds only if the
pattern matches at the start of the string regardless of mode, or at
the starting position given by the optional pos argument
regardless of whether a newline precedes it.
```text

re.compile("a").match("ba", 1) # succeeds
re.compile("^a").search("ba", 1) # fails; 'a' not at start
re.compile("^a").search("\na", 1) # fails; 'a' not at start
re.compile("^a", re.M).search("\na", 1) # succeeds
re.compile("^a", re.M).search("ba", 1) # fails; no preceding \n
```


12.11.1 Message Objects

module-rfc822.html | module-rfc822.html | addresslist-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
12.11 rfc822 (module-rfc822.html)
Up:
12.11 rfc822 (module-rfc822.html)
Next:
12.11.2 AddressList Objects (addresslist-objects.html)
---
## 12.11.1 Message Objects
A Message instance has the following methods:
Message instances also support a limited mapping interface.
In particular: `m [name]` is like
`m .getheader(name)` but raises KeyError if
there is no matching header; and `len( m )`,
`m .get( name [ , default ] )`,
`m .has_key( name )`, `m .keys()`,
`m .values()` `m .items()`, and
`m .setdefault( name [ , default ] )` act as
expected, with the one difference that setdefault() uses
an empty string as the default value. Message instances
also support the mapping writable interface `m [name] =
value` and `del m [name]`. Message objects do not
support the clear(), copy(), popitem(), or
update() methods of the mapping interface. (Support for
get() and setdefault() was only added in Python
2.2.)
Finally, Message instances have some public instance variables:


12.5.2 Folder Objects

mh-objects.html | module-mhlib.html | mh-message-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
12.5.1 MH Objects (mh-objects.html)
Up:
12.5 mhlib (module-mhlib.html)
Next:
12.5.3 Message Objects (mh-message-objects.html)
---
## 12.5.2 Folder Objects
Folder instances represent open folders and have the following
methods:


12.5.3 Message Objects

mh-folder-objects.html | module-mhlib.html | module-mimetools.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
12.5.2 Folder Objects (mh-folder-objects.html)
Up:
12.5 mhlib (module-mhlib.html)
Next:
12.6 mimetools (module-mimetools.html)
---
## 12.5.3 Message Objects
The Message class adds one method to those of
mimetools.Message:


12.5.1 MH Objects

module-mhlib.html | module-mhlib.html | mh-folder-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
12.5 mhlib (module-mhlib.html)
Up:
12.5 mhlib (module-mhlib.html)
Next:
12.5.2 Folder Objects (mh-folder-objects.html)
---
## 12.5.1 MH Objects
MH instances have the following methods:


module-mimetools.html | module-mimetools.html | module-mimetypes.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
12.6 mimetools (module-mimetools.html)
Up:
12.6 mimetools (module-mimetools.html)
Next:
12.7 mimetypes (module-mimetypes.html)
---
## 12.6.1 Additional Methods of Message Objects
The Message class defines the following methods in
addition to the rfc822.Message methods:


12.7.1 MimeTypes Objects

module-mimetypes.html | module-mimetypes.html | module-MimeWriter.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
12.7 mimetypes (module-mimetypes.html)
Up:
12.7 mimetypes (module-mimetypes.html)
Next:
12.8 MimeWriter (module-MimeWriter.html)
---
## 12.7.1 MimeTypes Objects
MimeTypes instances provide an interface which is very like
that of the mimetypes (module-mimetypes.html) module.


12.8.1 MimeWriter Objects

module-MimeWriter.html | module-MimeWriter.html | module-mimify.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
12.8 MimeWriter (module-MimeWriter.html)
Up:
12.8 MimeWriter (module-MimeWriter.html)
Next:
12.9 mimify (module-mimify.html)
---
## 12.8.1 MimeWriter Objects
MimeWriter instances have the following methods:


13.7.3 minidom and the DOM standard

dom-example.html | module-xml.dom.minidom.html | module-xml.dom.pulldom.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
13.7.2 DOM Example (dom-example.html)
Up:
13.7 xml.dom.minidom (module-xml.dom.minidom.html)
Next:
13.8 xml.dom.pulldom (module-xml.dom.pulldom.html)
---
## 13.7.3 minidom and the DOM standard
The xml.dom.minidom (module-xml.dom.minidom.html) module is essentially a DOM
1.0-compatible DOM with some DOM 2 features (primarily namespace
features).
Usage of the DOM interface in Python is straight-forward. The
following mapping rules apply:
- Interfaces are accessed through instance objects. Applications
should not instantiate the classes themselves; they should use
the creator functions available on the Document object.
Derived interfaces support all operations (and attributes) from
the base interfaces, plus any new operations.
- Operations are used as methods. Since the DOM uses only
in parameters, the arguments are passed in normal
order (from left to right). There are no optional
arguments. void operations return `None`.
- IDL attributes map to instance attributes. For compatibility
with the OMG IDL language mapping for Python, an attribute
`foo` can also be accessed through accessor methods
_get_foo() and _set_foo(). readonly
attributes must not be changed; this is not enforced at
runtime.
- The types `short int`, `unsigned int`, `unsigned
long long`, and `boolean` all map to Python integer
objects.
- The type `DOMString` maps to Python strings.
xml.dom.minidom (module-xml.dom.minidom.html) supports either byte or Unicode
strings, but will normally produce Unicode strings. Values
of type `DOMString` may also be `None` where allowed
to have the IDL `null` value by the DOM specification from
the W3C.
- const declarations map to variables in their
respective scope
(e.g. `xml.dom.minidom.Node.PROCESSING_INSTRUCTION_NODE`);
they must not be changed.
- `DOMException` is currently not supported in
xml.dom.minidom (module-xml.dom.minidom.html). Instead,
xml.dom.minidom (module-xml.dom.minidom.html) uses standard Python exceptions such
as TypeError and AttributeError.
- NodeList objects are implemented using Python's built-in
list type. Starting with Python 2.2, these objects provide the
interface defined in the DOM specification, but with earlier
versions of Python they do not support the official API. They
are, however, much more ``Pythonic'' than the interface defined
in the W3C recommendations.
The following interfaces have no implementation in
xml.dom.minidom (module-xml.dom.minidom.html):
- DOMTimeStamp
- DocumentType (added in Python 2.1)
- DOMImplementation (added in Python 2.1)
- CharacterData
- CDATASection
- Notation
- Entity
- EntityReference
- DocumentFragment


5.3.1 Minimal example

module-unittest.html | module-unittest.html | organizing-tests.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
5.3 unittest (module-unittest.html)
Up:
5.3 unittest (module-unittest.html)
Next:
5.3.2 Organizing test code (organizing-tests.html)
---
## 5.3.1 Minimal example
The unittest module provides a rich set of tools for
constructing and running tests. This section demonstrates that a
small subset of the tools suffice to meet the needs of most users.
Here is a short script to test three functions from the
random (module-random.html) module:
```text

import random
import unittest

class TestSequenceFunctions(unittest.TestCase):

def setUp(self):
self.seq = range(10)

def testshuffle(self):
# make sure the shuffled sequence does not lose any elements
random.shuffle(self.seq)
self.seq.sort()
self.assertEqual(self.seq, range(10))

def testchoice(self):
element = random.choice(self.seq)
self.assert_(element in self.seq)

def testsample(self):
self.assertRaises(ValueError, random.sample, self.seq, 20)
for element in random.sample(self.seq, 5):
self.assert_(element in self.seq)

if __name__ == '__main__':
unittest.main()
```
A testcase is created by subclassing `unittest.TestCase`.
The three individual tests are defined with methods whose names start with
the letters `test`. This naming convention informs the test runner
about which methods represent tests.
The crux of each test is a call to assertEqual() to
check for an expected result; assert_() to verify a condition;
or assertRaises() to verify that an expected exception gets
raised. These methods are used instead of the assert statement
so the test runner can accumulate all test results and produce a report.
When a setUp() method is defined, the test runner will run that
method prior to each test. Likewise, if a tearDown() method is
defined, the test runner will invoke that method after each test. In the
example, setUp() was used to create a fresh sequence for each test.
The final block shows a simple way to run the tests. `unittest.main()`
provides a command line interface to the test script. When run from the
command line, the above script produces an output that looks like this:
```text

...
----------------------------------------------------------------------
Ran 3 tests in 0.000s

OK
```
Instead of `unittest.main()`, there are other ways to run the tests
with a finer level of control, less terse output, and no requirement to be
run from the command line. For example, the last two lines may be replaced
with:
```text

suite = unittest.TestSuite()
suite.addTest(unittest.makeSuite(TestSequenceFunctions))
unittest.TextTestRunner(verbosity=2).run(suite)
```
Running the revised script from the interpreter or another script
produces the following output:
```text

testchoice (__main__.TestSequenceFunctions) ... ok
testsample (__main__.TestSequenceFunctions) ... ok
testshuffle (__main__.TestSequenceFunctions) ... ok

----------------------------------------------------------------------
Ran 3 tests in 0.110s

OK
```
The above examples show the most commonly used unittest features
which are sufficient to meet many everyday testing needs. The remainder
of the documentation explores the full feature set from first principles.


5. Miscellaneous Services

module-stringprep.html | lib.html | module-pydoc.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
4.11 stringprep (module-stringprep.html)
Up:
Python Library Reference (lib.html)
Next:
5.1 pydoc (module-pydoc.html)
---
# 5. Miscellaneous Services
The modules described in this chapter provide miscellaneous services
that are available in all Python versions. Here's an overview:


14.11.2 Mixer Device Objects

ossaudio-device-objects.html | module-ossaudiodev.html | crypto.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
14.11.1 Audio Device Objects (ossaudio-device-objects.html)
Up:
14.11 ossaudiodev (module-ossaudiodev.html)
Next:
15. Cryptographic Services (crypto.html)
---
## 14.11.2 Mixer Device Objects
File-like interface
Mixer interface


14. Multimedia Services

xml-namespace.html | lib.html | module-audioop.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
13.13.1 XML Namespaces (xml-namespace.html)
Up:
Python Library Reference (lib.html)
Next:
14.1 audioop (module-audioop.html)
---
# 14. Multimedia Services
The modules described in this chapter implement various algorithms or
interfaces that are mainly useful for multimedia applications. They
are available at the discretion of the installation. Here's an overview:


Module Index

node753.html | lib.html | genindex.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
C.2 Terms and conditions (node753.html)
Up:
Python Library Reference (lib.html)
Next:
---
## Module Index
This index only lists modules documented in this manual.
The Global Module
Index (../modindex.html) lists all modules that are documented in this set
of manuals.
Some module names are followed by an annotation indicating what
platform they are available on.


22.2 _winreg - Windows registry access

msvcrt-other.html | node735.html | handle-object.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
22.1.3 Other Functions (msvcrt-other.html)
Up:
22. MS Windows Specific (node735.html)
Next:
22.2.1 Registry Handle Objects (handle-object.html)
---
# 22.2 _winreg -
Windows registry access
Availability: Windows.
New in version 2.0.
These functions expose the Windows registry API to Python. Instead of
using an integer as the registry handle, a handle object is used to
ensure that the handles are closed correctly, even if the programmer
neglects to explicitly close them.
This module exposes a very low-level interface to the Windows
registry; it is expected that in the future a new `winreg`
module will be created offering a higher-level interface to the
registry API.
This module offers the following functions:


module-imageop.html | mmedia.html | module-sunau.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
14.2 imageop (module-imageop.html)
Up:
14. Multimedia Services (mmedia.html)
Next:
14.4 sunau (module-sunau.html)
---
# 14.3 aifc --
Read and write AIFF and AIFC files
This module provides support for reading and writing AIFF and AIFF-C
files. AIFF is Audio Interchange File Format, a format for storing
digital audio samples in a file. AIFF-C is a newer version of the
format that includes the ability to compress the audio data.
Caveat: Some operations may only work under IRIX; these will
raise ImportError when attempting to import the
cl module, which is only available on IRIX.
Audio files have a number of parameters that describe the audio data.
The sampling rate or frame rate is the number of times per second the
sound is sampled. The number of channels indicate if the audio is
mono, stereo, or quadro. Each frame consists of one sample per
channel. The sample size is the size in bytes of each sample. Thus a
frame consists of nchannels*samplesize bytes, and a
second's worth of audio consists of
nchannels*samplesize*framerate bytes.
For example, CD quality audio has a sample size of two bytes (16
bits), uses two channels (stereo) and has a frame rate of 44,100
frames/second. This gives a frame size of 4 bytes (2*2), and a
second's worth occupies 2*2*44100 bytes (176,400 bytes).
Module aifc defines the following function:
Objects returned by open() when a file is opened for
reading have the following methods:
Objects returned by open() when a file is opened for
writing have all the above methods, except for readframes() and
setpos(). In addition the following methods exist. The
get*() methods can only be called after the corresponding
set*() methods have been called. Before the first
writeframes() or writeframesraw(), all parameters
except for the number of frames must be filled in.


al-port-objects.html | sgi.html | module-cd.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
20.1.2 Port Objects (al-port-objects.html)
Up:
20. SGI IRIX Specific (sgi.html)
Next:
20.3 cd (module-cd.html)
---
# 20.2 AL --
Constants used with the al module
Availability: IRIX.
This module defines symbolic constants needed to use the built-in
module al (module-al.html) (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:


20.1 al -- Audio functions on the SGI

sgi.html | sgi.html | al-config-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
20. SGI IRIX Specific (sgi.html)
Up:
20. SGI IRIX Specific (sgi.html)
Next:
20.1.1 Configuration Objects (al-config-objects.html)
---
# 20.1 al --
Audio functions on the SGI
Availability: IRIX.
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 (module-al-constants.html), 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:


module-mmap.html | someos.html | module-dbhash.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
7.9 mmap (module-mmap.html)
Up:
7. Optional Operating System (someos.html)
Next:
7.11 dbhash (module-dbhash.html)
---
# 7.10 anydbm --
Generic access to DBM-style databases
anydbm is a generic interface to variants of the DBM
database -- dbhash (module-dbhash.html)(requires
bsddb (module-bsddb.html)),
gdbm (module-gdbm.html), or
dbm (module-dbm.html). If none of these modules is
installed, the slow-but-simple implementation in module
dumbdbm (module-dumbdbm.html)will be used.
The object returned by open() supports most of the same
functionality as dictionaries; keys and their corresponding values can
be stored, retrieved, and deleted, and the has_key() and
keys() methods are available. Keys and values must always be
strings.


node162.html | misc.html | module-sets.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
5.10.1 Theory (node162.html)
Up:
5. Miscellaneous Services (misc.html)
Next:
5.12 sets (module-sets.html)
---
# 5.11 array --
Efficient arrays of numeric values
This module defines an object type which can efficiently represent
an array of basic values: characters, integers, floating point
numbers. Arraysare sequence types and behave very much
like lists, except that the type of objects stored in them is
constrained. The type is specified at object creation time by using a
type code, which is a single character. The following type
codes are defined:
The actual representation of values is determined by the machine
architecture (strictly speaking, by the C implementation). The actual
size can be accessed through the itemsize attribute. The values
stored for `'L'` and `'I'` items will be represented as
Python long integers when retrieved, because Python's plain integer
type cannot represent the full range of C's unsigned (long) integers.
The module defines the following type:
Array objects support the ordinary sequence operations of
indexing, slicing, concatenation, and multiplication. When using
slice assignment, the assigned value must be an array object with the
same type code; in all other cases, TypeError is raised.
Array objects also implement the buffer interface, and may be used
wherever buffer objects are supported.
The following data items and methods are also supported:
When an array object is printed or converted to a string, it is
represented as `array( typecode , initializer )`. The
initializer is omitted if the array is empty, otherwise it is a
string if the typecode is `'c'`, otherwise it is a list of
numbers. The string is guaranteed to be able to be converted back to
an array with the same type and value using reverse quotes
(````), so long as the array() function has been
imported using `from array import array`. Examples:
```text

array('l')
array('c', 'hello world')
array('u', u'hello \textbackslash u2641')
array('l', [1, 2, 3, 4, 5])
array('d', [1.0, 2.0, 3.14])
```


asyncore-example.html | internet.html | node485.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
11.23.1 asyncore Example basic (asyncore-example.html)
Up:
11. Internet Protocols and (internet.html)
Next:
11.24.1 asynchat - Auxiliary (node485.html)
---
# 11.24 asynchat --
Asynchronous socket command/response handler
This module builds on the asyncore (module-asyncore.html) infrastructure,
simplifying asynchronous clients and servers and making it easier to
handle protocols whose elements are terminated by arbitrary strings, or
are of variable length. asynchat (module-asynchat.html) defines the abstract class
async_chat that you subclass, providing implementations of the
collect_incoming_data() and found_terminator()
methods. It uses the same asynchronous loop as asyncore (module-asyncore.html), and
the two types of channel, asyncore.dispatcher and
asynchat.async_chat, can freely be mixed in the channel map.
Typically an asyncore.dispatcher server channel generates new
asynchat.async_chat channel objects as it receives incoming
connection requests.


node481.html | internet.html | asyncore-example.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
11.22.2 DocCGIXMLRPCRequestHandler (node481.html)
Up:
11. Internet Protocols and (internet.html)
Next:
11.23.1 asyncore Example basic (asyncore-example.html)
---
# 11.23 asyncore --
Asynchronous socket handler
This module provides the basic infrastructure for writing asynchronous
socket service clients and servers.
There are only two ways to have a program on a single processor do
``more than one thing at a time.'' Multi-threaded programming is the
simplest and most popular way to do it, but there is another very
different technique, that lets you have nearly all the advantages of
multi-threading, without actually using multiple threads. It's really
only practical if your program is largely I/O bound. If your program
is processor bound, then pre-emptive scheduled threads are probably what
you really need. Network servers are rarely processor bound, however.
If your operating system supports the select() system call
in its I/O library (and nearly all do), then you can use it to juggle
multiple communication channels at once; doing other work while your
I/O is taking place in the ``background.'' Although this strategy can
seem strange and complex, especially at first, it is in many ways
easier to understand and control than multi-threaded programming.
The asyncore module solves many of the difficult problems for
you, making the task of building sophisticated high-performance
network servers and clients a snap. For ``conversational'' applications
and protocols the companion asynchat (module-asynchat.html) module is invaluable.
The basic idea behind both modules is to create one or more network
channels, instances of class asyncore.dispatcher and
asynchat.async_chat. Creating the channels adds them to a global
map, used by the loop() function if you do not provide it
with your own map.
Once the initial channel(s) is(are) created, calling the loop()
function activates channel service, which continues until the last
channel (including any that have been added to the map during asynchronous
service) is closed.
Thus, the set of channel events is larger than the basic socket events.
The full set of methods that can be overridden in your subclass follows:
In addition, each channel delegates or extends many of the socket methods.
Most of these are nearly identical to their socket partners.


3.5 atexit -- Exit handlers

node43.html | python.html | atexit-example.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
3.4.2 Limitations and other (node43.html)
Up:
3. Python Runtime Services (python.html)
Next:
3.5.1 atexit Example (atexit-example.html)
---
# 3.5 atexit --
Exit handlers
New in version 2.0.
The atexit module defines a single function to register
cleanup functions. Functions thus registered are automatically
executed upon normal interpreter termination.
Note: the functions registered via this module are not called when the program is killed by a
signal, when a Python fatal internal error is detected, or when
os._exit() is called.
This is an alternate interface to the functionality provided by the
`sys.exitfunc` variable.
Note: This module is unlikely to work correctly when used with other code
that sets `sys.exitfunc`. In particular, other core Python modules are
free to use atexit without the programmer's knowledge. Authors who
use `sys.exitfunc` should convert their code to use
atexit instead. The simplest way to convert code that sets
`sys.exitfunc` is to import atexit and register the function
that had been bound to `sys.exitfunc`.
See Also:


mmedia.html | mmedia.html | module-imageop.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
14. Multimedia Services (mmedia.html)
Up:
14. Multimedia Services (mmedia.html)
Next:
14.2 imageop (module-imageop.html)
---
# 14.1 audioop --
Manipulate raw audio data
The audioop module contains some useful operations on sound
fragments. It operates on sound fragments consisting of signed
integer samples 8, 16 or 32 bits wide, stored in Python strings. This
is the same format as used by the al (module-al.html) and sunaudiodev (module-sunaudiodev.html)
modules. All scalar items are integers, unless specified otherwise.
This module provides support for u-LAW and Intel/DVI ADPCM encodings.
A few of the more complicated operations only take 16-bit samples,
otherwise the sample size (in bytes) is always a parameter of the
operation.
The module defines the following variables and functions:
Note that operations such as mul() or max() make
no distinction between mono and stereo fragments, i.e. all samples
are treated equal. If this is a problem the stereo fragment should be
split into two mono fragments first and recombined later. Here is an
example of how to do that:
```text

def mul_stereo(sample, width, lfactor, rfactor):
lsample = audioop.tomono(sample, width, 1, 0)
rsample = audioop.tomono(sample, width, 0, 1)
lsample = audioop.mul(sample, width, lfactor)
rsample = audioop.mul(sample, width, rfactor)
lsample = audioop.tostereo(lsample, width, 1, 0)
rsample = audioop.tostereo(rsample, width, 0, 1)
return audioop.add(lsample, rsample, width)
```
If you use the ADPCM coder to build network packets and you want your
protocol to be stateless (i.e. to be able to tolerate packet loss)
you should not only transmit the data but also the state. Note that
you should send the initial state (the one you passed to
lin2adpcm()) along to the decoder, not the final state (as
returned by the coder). If you want to use struct.struct()
to store the state in binary you can code the first element (the
predicted value) in 16 bits and the second (the delta index) in 8.
The ADPCM coders have never been tried against other ADPCM coders,
only against themselves. It could well be that I misinterpreted the
standards in which case they will not be interoperable with the
respective standards.
The find*() routines might look a bit funny at first sight.
They are primarily meant to do echo cancellation. A reasonably
fast way to do this is to pick the most energetic piece of the output
sample, locate that in the input sample and subtract the whole output
sample from the input sample:


addresslist-objects.html | netdata.html | module-binascii.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
12.11.2 AddressList Objects (addresslist-objects.html)
Up:
12. Internet Data Handling (netdata.html)
Next:
12.13 binascii (module-binascii.html)
---
# 12.12 base64 --
Encode and decode MIME base64 data
This module performs base64 encoding and decoding of arbitrary binary
strings into text strings that can be safely sent by email or included
as part of an HTTP POST request. The
encoding scheme is defined in RFC 1521 (http://www.faqs.org/rfcs/rfc1521.html) (MIME
(Multipurpose Internet Mail Extensions) Part One: Mechanisms for
Specifying and Describing the Format of Internet Message Bodies,
section 5.2, ``Base64 Content-Transfer-Encoding'') and is used for
MIME email and various other Internet-related applications; it is not
the same as the output produced by the uuencode program.
For example, the string `'www.python.org'` is encoded as the
string `'d3d3LnB5dGhvbi5vcmc=\n'`.


module-SocketServer.html | internet.html | module-SimpleHTTPServer.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
11.15 SocketServer (module-SocketServer.html)
Up:
11. Internet Protocols and (internet.html)
Next:
11.17 SimpleHTTPServer (module-SimpleHTTPServer.html)
---
# 11.16 BaseHTTPServer --
Basic HTTP server
This module defines two classes for implementing HTTP servers
(Web servers). Usually, this module isn't used directly, but is used
as a basis for building functioning Web servers. See the
SimpleHTTPServerand
CGIHTTPServer (module-CGIHTTPServer.html)modules.
The first class, HTTPServer, is a
SocketServer.TCPServer subclass. It creates and listens at the
HTTP socket, dispatching the requests to a handler. Code to create and
run the server looks like this:
```text

def run(server_class=BaseHTTPServer.HTTPServer,
handler_class=BaseHTTPServer.BaseHTTPRequestHandler):
server_address = ('', 8000)
httpd = server_class(server_address, handler_class)
httpd.serve_forever()
```
BaseHTTPRequestHandler has the following instance variables:
BaseHTTPRequestHandler has the following class variables:
A BaseHTTPRequestHandler instance has the following methods:


node678.html | restricted.html | language.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
17.1.3 An example (node678.html)
Up:
17. Restricted Execution (restricted.html)
Next:
18. Python Language Services (language.html)
---
# 17.2 Bastion --
Restricting access to objects
Changed in version 2.3:
Disabled module.
Warning:
The documentation has been left in place to help in reading old code
that uses the module.
According to the dictionary, a bastion is ``a fortified area or
position'', or ``something that is considered a stronghold.'' It's a
suitable name for this module, which provides a way to forbid access
to certain attributes of an object. It must always be used with the
rexec (module-rexec.html) module, in order to allow restricted-mode programs
access to certain safe attributes of an object, while denying access
to other, unsafe attributes.


module-base64.html | netdata.html | module-binhex.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
12.12 base64 (module-base64.html)
Up:
12. Internet Data Handling (netdata.html)
Next:
12.14 binhex (module-binhex.html)
---
# 12.13 binascii --
Convert between binary and ASCII
The binascii module contains a number of methods to convert
between binary and various ASCII-encoded binary
representations. Normally, you will not use these functions directly
but use wrapper modules like uu (module-uu.html)or
binhex (module-binhex.html)instead, this module solely
exists because bit-manipulation of large amounts of data is slow in
Python.
The binascii module defines the following functions:


module-binascii.html | netdata.html | binhex-notes.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
12.13 binascii (module-binascii.html)
Up:
12. Internet Data Handling (netdata.html)
Next:
12.14.1 Notes (binhex-notes.html)
---
# 12.14 binhex --
Encode and decode binhex4 files
This module encodes and decodes files in binhex4 format, a format
allowing representation of Macintosh files in ASCII. On the Macintosh,
both forks of a file and the finder information are encoded (or
decoded), on other platforms only the data fork is handled.
The binhex module defines the following functions:
The following exception is also defined:
See Also:


5.9 bisect -- Array bisection algorithm

module-whrandom.html | misc.html | bisect-example.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
5.8 whrandom (module-whrandom.html)
Up:
5. Miscellaneous Services (misc.html)
Next:
5.9.1 Examples (bisect-example.html)
---
# 5.9 bisect --
Array bisection algorithm
This module provides support for maintaining a list in sorted order
without having to sort the list after each insertion. For long lists
of items with expensive comparison operations, this can be an
improvement over the more common approach. The module is called
bisect because it uses a basic bisection algorithm to do its
work. The source code may be most useful as a working example of the
algorithm (the boundary conditions are already right!).
The following functions are provided:


module-whichdb.html | someos.html | bsddb-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
7.12 whichdb (module-whichdb.html)
Up:
7. Optional Operating System (someos.html)
Next:
7.13.1 Hash, BTree and (bsddb-objects.html)
---
# 7.13 bsddb --
Interface to Berkeley DB library
Availability: Unix, Windows.
The bsddb module provides an interface to the Berkeley DB
library. Users can create hash, btree or record based library files
using the appropriate open call. Bsddb objects behave generally like
dictionaries. Keys and values must be strings, however, so to use
other objects as keys or to store other kinds of objects the user must
serialize them somehow, typically using marshal.dumps or pickle.dumps.
Starting with Python 2.3 the bsddb module requires the
Berkeley DB library version 3.1 or later (it is known to work with 3.1
thru 4.1 at the time of this writing).
See Also:
The following is a description of the legacy bsddb interface
compatible with the old python bsddb module. For details about the more
modern Db and DbEnv object oriented interface see the above mentioned
pybsddb URL.
The bsddb module defines the following functions that create
objects that access the appropriate type of Berkeley DB file. The
first two arguments of each function are the same. For ease of
portability, only the first two arguments should be used in most
instances.
See Also:
Note:
Beginning in 2.3 some Unix versions of Python may have a bsddb185
module. This is present only to allow backwards compatibility with
systems which ship with the old Berkeley DB 1.85 database library. The
bsddb185 module should never be used directly in new code.


3.30 __builtin__ -- Built-in functions

module-user.html | python.html | module-main.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
3.29 user (module-user.html)
Up:
3. Python Runtime Services (python.html)
Next:
3.31 __main__ (module-main.html)
---
# 3.30 __builtin__ --
Built-in functions


module-gzip.html | someos.html | node337.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
7.16 gzip (module-gzip.html)
Up:
7. Optional Operating System (someos.html)
Next:
7.17.1 (De)compression of files (node337.html)
---
# 7.17 bz2 --
Compression compatible with bzip2
New in version 2.3.
This module provides a comprehensive interface for the bz2 compression library.
It implements a complete file interface, one-shot (de)compression functions,
and types for sequential (de)compression.
Here is a resume of the features offered by the bz2 module:
- BZ2File class implements a complete file interface, including
readline(), readlines(),
writelines(), seek(), etc;
- BZ2File class implements emulated seek() support;
- BZ2File class implements universal newline support;
- BZ2File class offers an optimized line iteration using
the readahead algorithm borrowed from file objects;
- Sequential (de)compression supported by BZ2Compressor and
BZ2Decompressor classes;
- One-shot (de)compression supported by compress() and
decompress() functions;
- Thread safety uses individual locking mechanism;
- Complete inline documentation;


module-xreadlines.html | misc.html | module-cmd.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
5.16 xreadlines (module-xreadlines.html)
Up:
5. Miscellaneous Services (misc.html)
Next:
5.18 cmd (module-cmd.html)
---
# 5.17 calendar --
General calendar-related functions
This module allows you to output calendars like the Unix
cal program, and provides additional useful functions
related to the calendar. By default, these calendars have Monday as
the first day of the week, and Sunday as the last (the European
convention). Use setfirstweekday() to set the first day of the
week to Sunday (6) or to any other weekday. Parameters that specify
dates are given as integers.
Most of these functions rely on the datetime module which
uses an idealized calendar, the current Gregorian calendar indefinitely
extended in both directions. This matches the definition of the
"proleptic Gregorian" calendar in Dershowitz and Reingold's book
"Calendrical Calculations", where it's the base calendar for all
computations.


20.3 cd -- CD-ROM access on SGI systems

module-al-constants.html | sgi.html | player-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
20.2 AL (module-al-constants.html)
Up:
20. SGI IRIX Specific (sgi.html)
Next:
20.3.1 Player Objects (player-objects.html)
---
# 20.3 cd --
CD-ROM access on SGI systems
Availability: IRIX.
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 open() and creates a parser to parse the data
from the CD with createparser(). The object returned by
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():


browser-controllers.html | internet.html | cgi-intro.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
11.1.1 Browser Controller Objects (browser-controllers.html)
Up:
11. Internet Protocols and (internet.html)
Next:
11.2.1 Introduction (cgi-intro.html)
---
# 11.2 cgi --
Common Gateway Interface support.
Support module for Common Gateway Interface (CGI) scripts.
This module defines a number of utilities for use by CGI scripts
written in Python.


module-SimpleHTTPServer.html | internet.html | module-Cookie.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
11.17 SimpleHTTPServer (module-SimpleHTTPServer.html)
Up:
11. Internet Protocols and (internet.html)
Next:
11.19 Cookie (module-Cookie.html)
---
# 11.18 CGIHTTPServer --
CGI-capable HTTP request handler
The CGIHTTPServer module defines a request-handler class,
interface compatible with
BaseHTTPServer.BaseHTTPRequestHandler and inherits behavior
from SimpleHTTPServer.SimpleHTTPRequestHandler but can also
run CGI scripts.
Note:
This module can run CGI scripts on Unix and Windows systems;
on Mac OS it will only be able to run Python scripts within the same
process as itself.
The CGIHTTPServer module defines the following class:
The CGIHTTPRequestHandler defines the following data member:
The CGIHTTPRequestHandler defines the following methods:
Note that CGI scripts will be run with UID of user nobody, for security
reasons. Problems with the CGI script will be translated to error 403.
For example usage, see the implementation of the test()
function.


node411.html | internet.html | module-urllib.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
11.2.10 Common problems and (node411.html)
Up:
11. Internet Protocols and (internet.html)
Next:
11.4 urllib (module-urllib.html)
---
# 11.3 cgitb --
Traceback manager for CGI scripts
New in version 2.2.
The cgitb module provides a special exception handler for Python
scripts. (It's name is a bit misleading. It was originally designed to
display extensive traceback information in HTML for CGI scripts. It was
later generalized to also display this information in plain text.) After
this module is activated, if an uncaught exception occurs, a detailed,
formatted report will be displayed. The report
includes a traceback showing excerpts of the source code for each level,
as well as the values of the arguments and local variables to currently
running functions, to help you debug the problem. Optionally, you can
save this information to a file instead of sending it to the browser.
To enable this feature, simply add one line to the top of your CGI script:
```text

import cgitb; cgitb.enable()
```
The options to the enable() function control whether the
report is displayed in the browser and whether the report is logged
to a file for later analysis.


14.6 chunk -- Read IFF chunked data

Wave-write-objects.html | mmedia.html | module-colorsys.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
14.5.2 Wave_write Objects (Wave-write-objects.html)
Up:
14. Multimedia Services (mmedia.html)
Next:
14.7 colorsys (module-colorsys.html)
---
# 14.6 chunk --
Read IFF chunked data
This module provides an interface for reading files that use EA IFF 85
chunks.14.1 (#foot59264) This format is used
in at least the AudioInterchange File Format
(AIFF/AIFF-C) and the RealMedia File
Format(RMFF). The WAVE audio file format is closely
related and can also be read using this module.
A chunk has the following structure:
The ID is a 4-byte string which identifies the type of chunk.
The size field (a 32-bit value, encoded using big-endian byte order)
gives the size of the chunk data, not including the 8-byte header.
Usually an IFF-type file consists of one or more chunks. The proposed
usage of the Chunk class defined here is to instantiate an
instance at the start of each chunk and read from the instance until
it reaches the end, after which a new instance can be instantiated.
At the end of the file, creating a new instance will fail with a
EOFError exception.
A Chunk object supports the following methods:
The remaining methods will raise IOError if called after
the close() method has been called.


module-math.html | misc.html | module-random.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
5.5 math (module-math.html)
Up:
5. Miscellaneous Services (misc.html)
Next:
5.7 random (module-random.html)
---
# 5.6 cmath --
Mathematical functions for complex numbers
This module is always available. It provides access to mathematical
functions for complex numbers. The functions are:
The module also defines two mathematical constants:
Note that the selection of functions is similar, but not identical, to
that in module math (module-math.html). The reason for having
two modules is that some users aren't interested in complex numbers,
and perhaps don't even know what they are. They would rather have
`math.sqrt(-1)` raise an exception than return a complex number.
Also note that the functions defined in cmath always return a
complex number, even if the answer can be expressed as a real number
(in which case the complex number has an imaginary part of zero).
A note on branch cuts: They are curves along which the given function
fails to be continuous. They are a necessary feature of many complex
functions. It is assumed that if you need to compute with complex
functions, you will understand about branch cuts. Consult almost any
(not too elementary) book on complex variables for enlightenment. For
information of the proper choice of branch cuts for numerical
purposes, a good reference should be the following:


module-calendar.html | misc.html | Cmd-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
5.17 calendar (module-calendar.html)
Up:
5. Miscellaneous Services (misc.html)
Next:
5.18.1 Cmd Objects (Cmd-objects.html)
---
# 5.18 cmd --
Support for line-oriented command interpreters
The Cmd class provides a simple framework for writing
line-oriented command interpreters. These are often useful for
test harnesses, administrative tools, and prototypes that will
later be wrapped in a more sophisticated interface.


3.23 code -- Interpreter base classes

module-pkgutil.html | python.html | interpreter-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
3.22 pkgutil (module-pkgutil.html)
Up:
3. Python Runtime Services (python.html)
Next:
3.23.1 Interactive Interpreter Objects (interpreter-objects.html)
---
# 3.23 code --
Interpreter base classes
The `code` module provides facilities to implement
read-eval-print loops in Python. Two classes and convenience
functions are included which can be used to build applications which
provide an interactive interpreter prompt.


module-textwrap.html | strings.html | node120.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
4.8 textwrap (module-textwrap.html)
Up:
4. String Services (strings.html)
Next:
4.9.1 Codec Base Classes (node120.html)
---
# 4.9 codecs --
Codec registry and base classes
This module defines base classes for standard Python codecs (encoders
and decoders) and provides access to the internal Python codec
registry which manages the codec and error handling lookup process.
It defines the following functions:
To simplify access to the various codecs, the module provides these
additional functions which use lookup() for the codec
lookup:
To simplify working with encoded files or stream, the module
also defines these utility functions:
The module also provides the following constants which are useful
for reading and writing to platform dependent files:
See Also:


3.24 codeop -- Compile Python code

console-objects.html | python.html | module-pprint.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
3.23.2 Interactive Console Objects (console-objects.html)
Up:
3. Python Runtime Services (python.html)
Next:
3.25 pprint (module-pprint.html)
---
# 3.24 codeop --
Compile Python code
The codeop module provides utilities upon which the Python
read-eval-print loop can be emulated, as is done in the
code (module-code.html) module. As a result, you probably don't want to use
the module directly; if you want to include such a loop in your
program you probably want to use the code (module-code.html) module instead.
There are two parts to this job:
1. Being able to tell if a line of input completes a Python
statement: in short, telling whether to print
``> > >` or ``...`' next.
2. Remembering which future statements the user has entered, so
subsequent input can be compiled with these in effect.
The codeop module provides a way of doing each of these
things, and a way of doing them both.
To do just the former:
A note on version compatibility: the Compile and
CommandCompiler are new in Python 2.2. If you want to enable
the future-tracking features of 2.2 but also retain compatibility with
2.1 and earlier versions of Python you can either write
```text

try:
from codeop import CommandCompiler
compile_command = CommandCompiler()
del CommandCompiler
except ImportError:
from codeop import compile_command
```
which is a low-impact change, but introduces possibly unwanted global
state into your program, or you can write:
```text

try:
from codeop import CommandCompiler
except ImportError:
def CommandCompiler():
from codeop import compile_command
return compile_command
```


module-chunk.html | mmedia.html | module-rgbimg.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
14.6 chunk (module-chunk.html)
Up:
14. Multimedia Services (mmedia.html)
Next:
14.8 rgbimg (module-rgbimg.html)
---
# 14.7 colorsys --
Conversions between color systems
The colorsys module defines bidirectional conversions of
color values between colors expressed in the RGB (Red Green Blue)
color space used in computer monitors and three other coordinate
systems: YIQ, HLS (Hue Lightness Saturation) and HSV (Hue Saturation
Value). Coordinates in all of these color spaces are floating point
values. In the YIQ space, the Y coordinate is between 0 and 1, but
the I and Q coordinates can be positive or negative. In all other
spaces, the coordinates are all between 0 and 1.
More information about color spaces can be found at
http://www.inforamp.net/%7epoynton/ColorFAQ.html.
The colorsys module defines the following functions:
Example:


module-syslog.html | unix.html | module-pdb.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
8.17 syslog (module-syslog.html)
Up:
8. Unix Specific Services (unix.html)
Next:
9. The Python Debugger (module-pdb.html)
---
# 8.18 commands --
Utilities for running commands
Availability: Unix.
The commands module contains wrapper functions for
os.popen() which take a system command as a string and
return any output generated by the command and, optionally, the exit
status.
The commands module defines the following functions:
Example:
```text

>>> import commands
>>> commands.getstatusoutput('ls /bin/ls')
(0, '/bin/ls')
>>> commands.getstatusoutput('cat /bin/junk')
(256, 'cat: /bin/junk: No such file or directory')
>>> commands.getstatusoutput('/bin/junk')
(256, 'sh: /bin/junk: not found')
>>> commands.getoutput('ls /bin/ls')
'/bin/ls'
>>> commands.getstatus('/bin/ls')
'-rwxr-xr-x 1 root 13352 Oct 14 1994 /bin/ls'
```


module-pycompile.html | language.html | module-dis.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
18.8 py_compile (module-pycompile.html)
Up:
18. Python Language Services (language.html)
Next:
18.10 dis (module-dis.html)
---
# 18.9 compileall --
Byte-compile Python libraries
This module provides some utility functions to support installing
Python libraries. These functions compile Python source files in a
directory tree, allowing users without permission to write to the
libraries to take advantage of cached byte-code files.
The source file for this module may also be used as a script to
compile Python sources in directories named on the command line or in
`sys.path`.


19.3.1 AST Nodes

node705.html | node705.html | node707.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
19.3 Python Abstract Syntax (node705.html)
Up:
19.3 Python Abstract Syntax (node705.html)
Next:
19.3.2 Assignment nodes (node707.html)
---
## 19.3.1 AST Nodes
The compiler.ast module is generated from a text file that
describes each node type and its elements. Each node type is
represented as a class that inherits from the abstract base class
compiler.ast.Node and defines a set of named attributes for
child nodes.
All Node objects offer the following methods:
Two examples illustrate the general structure of Node
classes. The while statement is defined by the following
grammar production:
```text

while_stmt: "while" expression ":" suite
["else" ":" suite]
```
The While node has three attributes: test,
body, and else_. (If the natural name for an
attribute is also a Python reserved word, it can't be used as an
attribute name. An underscore is appended to the word to make it a
legal identifier, hence else_ instead of else.)
The if statement is more complicated because it can include
several tests.
```text

if_stmt: 'if' test ':' suite ('elif' test ':' suite)* ['else' ':' suite]
```
The If node only defines two attributes: tests and
else_. The tests attribute is a sequence of test
expression, consequent body pairs. There is one pair for each
if/elif clause. The first element of the pair is
the test expression. The second elements is a Stmt node that
contains the code to execute if the test is true.
The getChildren() method of If returns a flat list of
child nodes. If there are three if/elif clauses
and no else clause, then getChildren() will return
a list of six elements: the first test expression, the first
Stmt, the second text expression, etc.
The following table lists each of the Node subclasses defined
in compiler.ast and each of the public attributes available
on their instances. The values of most of the attributes are
themselves Node instances or sequences of instances. When the
value is something other than an instance, the type is noted in the
comment. The attributes are listed in the order in which they are
returned by getChildren() and getChildNodes().


19.1 The basic interface

compiler.html | compiler.html | node704.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
19. Python compiler package (compiler.html)
Up:
19. Python compiler package (compiler.html)
Next:
19.2 Limitations (node704.html)
---
# 19.1 The basic interface
The top-level of the package defines four functions. If you import
compiler, you will get these functions and a collection of
modules contained in the package.
The compiler package contains the following modules:
ast (module-compiler.ast.html), consts, future,
misc, pyassem, pycodegen, symbols,
transformer, and visitor (module-compiler.visitor.html).


19.4 Using Visitors to Walk ASTs

node708.html | compiler.html | node710.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
19.3.3 Examples (node708.html)
Up:
19. Python compiler package (compiler.html)
Next:
19.5 Bytecode Generation (node710.html)
---
# 19.4 Using Visitors to Walk ASTs
The visitor pattern is ... The compiler (module-compiler.html) package uses a
variant on the visitor pattern that takes advantage of Python's
introspection features to elminiate the need for much of the visitor's
infrastructure.
The classes being visited do not need to be programmed to accept
visitors. The visitor need only define visit methods for classes it
is specifically interested in; a default visit method can handle the
rest.
XXX The magic visit() method for visitors.
ASTVisitor objects have the following methods:
XXX describe extra arguments


itertools-example.html | misc.html | RawConfigParser-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
5.13.2 Examples (itertools-example.html)
Up:
5. Miscellaneous Services (misc.html)
Next:
5.14.1 RawConfigParser Objects (RawConfigParser-objects.html)
---
# 5.14 ConfigParser --
Configuration file parser
This module defines the class ConfigParser.
The ConfigParser class implements a basic configuration file
parser language which provides a structure similar to what you would
find on Microsoft Windows INI files. You can use this to write Python
programs which can be customized by end users easily.
Warning:
This library does not interpret or write the value-type
prefixes used in the Windows Registry extended version of INI syntax.
The configuration file consists of sections, led by a
"[section]" header and followed by "name: value" entries,
with continuations in the style of RFC 822 (http://www.faqs.org/rfcs/rfc822.html); "name=value" is
also accepted. Note that leading whitespace is removed from values.
The optional values can contain format strings which refer to other
values in the same section, or values in a special
`DEFAULT` section. Additional defaults can be provided on
initialization and retrieval. Lines beginning with "#" or
";" are ignored and may be used to provide comments.
For example:
```text

[My Section]
foodir: %(dir)s/whatever
dir=frob
```
would resolve the "%(dir)s" to the value of
"dir" ("frob" in this case). All reference expansions are
done on demand.
Default values can be specified by passing them into the
ConfigParser constructor as a dictionary. Additional defaults
may be passed into the get() method which will override all
others.
See Also:


11.19 Cookie -- HTTP state management

module-CGIHTTPServer.html | internet.html | cookie-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
11.18 CGIHTTPServer (module-CGIHTTPServer.html)
Up:
11. Internet Protocols and (internet.html)
Next:
11.19.1 Cookie Objects (cookie-objects.html)
---
# 11.19 Cookie --
HTTP state management
The Cookie module defines classes for abstracting the concept of
cookies, an HTTP state management mechanism. It supports both simple
string-only cookies, and provides an abstraction for having any serializable
data-type as cookie value.
The module formerly strictly applied the parsing rules described in in
the RFC 2109 (http://www.faqs.org/rfcs/rfc2109.html) and RFC 2068 (http://www.faqs.org/rfcs/rfc2068.html) specifications. It has since been discovered
that MSIE 3.0x doesn't follow the character rules outlined in those
specs. As a result, the parsing rules used are a bit less strict.
A further security note is warranted. For backwards compatibility,
the Cookie module exports a class named Cookie which
is just an alias for SmartCookie. This is probably a mistake
and will likely be removed in a future version. You should not use
the Cookie class in your applications, for the same reason why
you should not use the SerialCookie class.
See Also:


node75.html | python.html | module-marshal.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
3.17.2 Example (node75.html)
Up:
3. Python Runtime Services (python.html)
Next:
3.19 marshal (module-marshal.html)
---
# 3.18 copy --
Shallow and deep copy operations
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.
The deepcopy() function avoids these problems by:
- keeping a ``memo'' dictionary of objects already copied during the current
copying pass; and
- letting user-defined classes override the copying operation or the
set of components copied.
This version does not copy types like module, class, function, method,
stack trace, stack frame, file, socket, window, array, or 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 (module-pickle.html)for information on these
methods. The copy module does not use the
copy_reg (module-copyreg.html) registration module.
In order for a class to define its own copy implementation, it can
define special methods __copy__() and
__deepcopy__(). The former is called to implement the
shallow copy operation; no additional arguments are passed. The
latter is called to implement the deep copy operation; it is passed
one argument, the memo dictionary. If the __deepcopy__()
implementation needs to make a deep copy of a component, it should
call the deepcopy() function with the component as first
argument and the memo dictionary as second argument.


module-cPickle.html | python.html | module-shelve.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
3.15 cPickle (module-cPickle.html)
Up:
3. Python Runtime Services (python.html)
Next:
3.17 shelve (module-shelve.html)
---
# 3.16 copy_reg --
Register pickle support functions
The copy_reg module provides support for the
pickle (module-pickle.html)and
cPickle (module-cPickle.html)modules. The
copy (module-copy.html)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.