10.3 Instant Users Manual

node383.html | profile.html | node385.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
10.2 How Is This (node383.html)
Up:
10. The Python Profiler (profile.html)
Next:
10.4 What Is Deterministic (node385.html)
---
# 10.3 Instant Users Manual
This section is provided for users that ``don't want to read the
manual.'' It provides a very brief overview, and allows a user to
rapidly perform profiling on an existing application.
To profile an application with a main entry point of "foo()", you
would add the following to your module:
```text

import profile
profile.run('foo()')
```
The above action would cause "foo()" to be run, and a series of
informative lines (the profile) to be printed. The above approach is
most useful when working with the interpreter. If you would like to
save the results of a profile into a file for later examination, you
can supply a file name as the second argument to the run()
function:
```text

import profile
profile.run('foo()', 'fooprof')
```
The file profile.py can also be invoked as
a script to profile another script. For example:
```text

python /usr/local/lib/python1.5/profile.py myscript.py
```
When you wish to review the profile, you should use the methods in the
pstats module. Typically you would load the statistics data as
follows:
```text

import pstats
p = pstats.Stats('fooprof')
```
The class Stats (the above code just created an instance of
this class) has a variety of methods for manipulating and printing the
data that was just read into "p". When you ran
profile.run() above, what was printed was the result of three
method calls:
```text

p.strip_dirs().sort_stats(-1).print_stats()
```
The first method removed the extraneous path from all the module
names. The second method sorted all the entries according to the
standard module/line/name string that is printed (this is to comply
with the semantics of the old profiler). The third method printed out
all the statistics. You might try the following sort calls:
```text

p.sort_stats('name')
p.print_stats()
```
The first call will actually sort the list by function name, and the
second call will print out the statistics. The following are some
interesting calls to experiment with:
```text

p.sort_stats('cumulative').print_stats(10)
```
This sorts the profile by cumulative time in a function, and then only
prints the ten most significant lines. If you want to understand what
algorithms are taking time, the above line is what you would use.
If you were looking to see what functions were looping a lot, and
taking a lot of time, you would do:
```text

p.sort_stats('time').print_stats(10)
```
to sort according to time spent within each function, and then print
the statistics for the top ten functions.
You might also try:
```text

p.sort_stats('file').print_stats('__init__')
```
This will sort all the statistics by file name, and then print out
statistics for only the class init methods ('cause they are spelled
with "__init__" in them). As one final example, you could try:
```text

p.sort_stats('time', 'cum').print_stats(.5, 'init')
```
This line sorts statistics with a primary key of time, and a secondary
key of cumulative time, and then prints out some of the statistics.
To be specific, the list is first culled down to 50% (re: ".5")
of its original size, then only lines containing `init` are
maintained, and that sub-sub-list is printed.
If you wondered what functions called the above functions, you could
now ("p" is still sorted according to the last criteria) do:
```text

p.print_callers(.5, 'init')
```
and you would get a list of callers for each of the listed functions.
If you want more functionality, you're going to have to read the
manual, or guess what the following functions do:
```text

p.print_callees()
p.add('fooprof')
```
Invoked as a script, the pstats module is a statistics
browser for reading and examining profile dumps. It has a simple
line-oriented interface (implemented using cmd (module-cmd.html)) and
interactive help.


10.6 Limitations

profile-stats.html | profile.html | profile-calibration.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
10.5.1 The Stats Class (profile-stats.html)
Up:
10. The Python Profiler (profile.html)
Next:
10.7 Calibration (profile-calibration.html)
---
# 10.6 Limitations
There are two fundamental limitations on this profiler. The first is
that it relies on the Python interpreter to dispatch call,
return, and exception events. Compiled C code does not
get interpreted, and hence is ``invisible'' to the profiler. All time
spent in C code (including built-in functions) will be charged to the
Python function that invoked the C code. If the C code calls out
to some native Python code, then those calls will be profiled
properly.
The second limitation has to do with accuracy of timing information.
There is a fundamental problem with deterministic profilers involving
accuracy. The most obvious restriction is that the underlying ``clock''
is only ticking at a rate (typically) of about .001 seconds. Hence no
measurements will be more accurate that that underlying clock. If
enough measurements are taken, then the ``error'' will tend to average
out. Unfortunately, removing this first error induces a second source
of error...
The second problem is that it ``takes a while'' from when an event is
dispatched until the profiler's call to get the time actually
gets the state of the clock. Similarly, there is a certain lag
when exiting the profiler event handler from the time that the clock's
value was obtained (and then squirreled away), until the user's code
is once again executing. As a result, functions that are called many
times, or call many functions, will typically accumulate this error.
The error that accumulates in this fashion is typically less than the
accuracy of the clock (less than one clock tick), but it
can accumulate and become very significant. This profiler
provides a means of calibrating itself for a given platform so that
this error can be probabilistically (on the average) removed.
After the profiler is calibrated, it will be more accurate (in a least
square sense), but it will sometimes produce negative numbers (when
call counts are exceptionally low, and the gods of probability work
against you :-). ) Do not be alarmed by negative numbers in
the profile. They should only appear if you have calibrated
your profiler, and the results are actually better than without
calibration.


10.5.1 The Stats Class

module-profile.html | module-profile.html | profile-limits.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
10.5 Reference Manual (module-profile.html)
Up:
10.5 Reference Manual (module-profile.html)
Next:
10.6 Limitations (profile-limits.html)
---
## 10.5.1 The Stats Class
Stats objects have the following methods:


10. The Python Profiler

debugger-hooks.html | lib.html | node382.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
9.2 How It Works (debugger-hooks.html)
Up:
Python Library Reference (lib.html)
Next:
10.1 Introduction to the (node382.html)
---
# 10. The Python Profiler
Copyright © 1994, by InfoSeek Corporation, all rights reserved.
Written by James Roskind.10.1 (#foot39983)
Permission to use, copy, modify, and distribute this Python software
and its associated documentation for any purpose (subject to the
restriction in the following sentence) without fee is hereby granted,
provided that the above copyright notice appears in all copies, and
that both that copyright notice and this permission notice appear in
supporting documentation, and that the name of InfoSeek not be used in
advertising or publicity pertaining to distribution of the software
without specific, written prior permission. This permission is
explicitly restricted to the copying and modification of the software
to remain in Python, compiled Python, or other languages (such as C)
wherein the modified or derived code is exclusively imported into a
Python module.
INFOSEEK CORPORATION DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS
SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
FITNESS. IN NO EVENT SHALL INFOSEEK CORPORATION BE LIABLE FOR ANY
SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER
RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF
CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
The profiler was written after only programming in Python for 3 weeks.
As a result, it is probably clumsy code, but I don't know for sure yet
'cause I'm a beginner :-). I did work hard to make the code run fast,
so that profiling would be a reasonable thing to do. I tried not to
repeat code fragments, but I'm sure I did some stuff in really awkward
ways at times. Please send suggestions for improvements to:
jar@netscape.com. I won't promise any support. ...but
I'd appreciate the feedback.
---
#### Footnotes
... Roskind.10.1 (profile.html#tex2html49): Updated and converted to LATEX by Guido van Rossum. The references to
the old profiler are left in the text, although it no longer exists.


11.20.6 ProtocolError Objects

fault-objects.html | module-xmlrpclib.html | node474.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
11.20.5 Fault Objects (fault-objects.html)
Up:
11.20 xmlrpclib (module-xmlrpclib.html)
Next:
11.20.7 Convenience Functions (node474.html)
---
## 11.20.6 ProtocolError Objects
A ProtocolError object describes a protocol error in the
underlying transport layer (such as a 404 `not found' error if the
server named by the URI does not exist). It has the following
members:


11.5.9 ProxyBasicAuthHandler Objects

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


11.5.12 ProxyDigestAuthHandler Objects

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


11.5.5 ProxyHandler Objects

http-redirect-handler.html | module-urllib2.html | http-password-mgr.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
11.5.4 HTTPRedirectHandler Objects (http-redirect-handler.html)
Up:
11.5 urllib2 (module-urllib2.html)
Next:
11.5.6 HTTPPasswordMgr Objects (http-password-mgr.html)
---
## 11.5.5 ProxyHandler Objects


18.7.1 Class Descriptor Objects

module-pyclbr.html | module-pyclbr.html | module-pycompile.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
18.7 pyclbr (module-pyclbr.html)
Up:
18.7 pyclbr (module-pyclbr.html)
Next:
18.8 py_compile (module-pycompile.html)
---
## 18.7.1 Class Descriptor Objects
The class descriptor objects used as values in the dictionary returned
by readmodule() provide the following data members:


3. Python Runtime Services

node33.html | lib.html | module-sys.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
2.4 Built-in Constants (node33.html)
Up:
Python Library Reference (lib.html)
Next:
3.1 sys (module-sys.html)
---
# 3. Python Runtime Services
The modules described in this chapter provide a wide range of services
related to the Python interpreter and its interaction with its
environment. Here's an overview:


7.18.2 PyZipFile Objects

zipfile-objects.html | module-zipfile.html | zipinfo-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
7.18.1 ZipFile Objects (zipfile-objects.html)
Up:
7.18 zipfile (module-zipfile.html)
Next:
7.18.3 ZipInfo Objects (zipinfo-objects.html)
---
## 7.18.2 PyZipFile Objects
The PyZipFile constructor takes the same parameters as the
ZipFile constructor. Instances have one method in addition to
those of ZipFile objects.


7.8.1 Queue Objects

module-Queue.html | module-Queue.html | module-mmap.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
7.8 Queue (module-Queue.html)
Up:
7.8 Queue (module-Queue.html)
Next:
7.9 mmap (module-mmap.html)
---
## 7.8.1 Queue Objects
Class Queue implements queue objects and has the methods
described below. This class can be derived from in order to implement
other queue organizations (e.g. stack) but the inheritable interface
is not described here. See the source code for details. The public
methods are:


5.14.1 RawConfigParser Objects

module-ConfigParser.html | module-ConfigParser.html | ConfigParser-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
5.14 ConfigParser (module-ConfigParser.html)
Up:
5.14 ConfigParser (module-ConfigParser.html)
Next:
5.14.2 ConfigParser Objects (ConfigParser-objects.html)
---
## 5.14.1 RawConfigParser Objects
RawConfigParser instances have the following methods:


4.2.4 Regular Expression Objects

node105.html | module-re.html | match-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
4.2.3 Module Contents (node105.html)
Up:
4.2 re (module-re.html)
Next:
4.2.5 Match Objects (match-objects.html)
---
## 4.2.4 Regular Expression Objects
Compiled regular expression objects support the following methods and
attributes:


4.2.1 Regular Expression Syntax

module-re.html | module-re.html | matching-searching.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
4.2 re (module-re.html)
Up:
4.2 re (module-re.html)
Next:
4.2.2 Matching vs Searching (matching-searching.html)
---
## 4.2.1 Regular Expression Syntax
A regular expression (or RE) specifies a set of strings that matches
it; the functions in this module let you check if a particular string
matches a given regular expression (or if a given regular expression
matches a particular string, which comes down to the same thing).
Regular expressions can be concatenated to form new regular
expressions; if A and B are both regular expressions,
then AB is also a regular expression. If a string p
matches A and another string q matches B, the string pq
will match AB if A and B do no specify boundary
conditions that are no longer satisfied by pq. Thus, complex
expressions can easily be constructed from simpler primitive
expressions like the ones described here. For details of the theory
and implementation of regular expressions, consult the Friedl book
referenced above, or almost any textbook about compiler construction.
A brief explanation of the format of regular expressions follows. For
further information and a gentler presentation, consult the Regular
Expression HOWTO, accessible from http://www.python.org/doc/howto/.
Regular expressions can contain both special and ordinary characters.
Most ordinary characters, like "A", "a", or
"0", are the simplest regular expressions; they simply match
themselves. You can concatenate ordinary characters, so last
matches the string `'last'`. (In the rest of this section, we'll
write RE's in this special style, usually without quotes, and
strings to be matched `'in single quotes'`.)
Some characters, like "|" or "(", are special.
Special characters either stand for classes of ordinary characters, or
affect how the regular expressions around them are interpreted.
The special characters are:
The special sequences consist of "\" and a character from the
list below. If the ordinary character is not on the list, then the
resulting RE will match the second character. For example,
\$ matches the character "$".
Most of the standard escapes supported by Python string literals are
also accepted by the regular expression parser:
```text

\a \b \f \n
\r \t \v \x
\\
```
Octal escapes are included in a limited form: If the first digit is a
0, or if there are three octal digits, it is considered an octal
escape. Otherwise, it is a group reference.


7.20.1 Example

module-readline.html | module-readline.html | module-rlcompleter.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
7.20 readline (module-readline.html)
Up:
7.20 readline (module-readline.html)
Next:
7.21 rlcompleter (module-rlcompleter.html)
---
## 7.20.1 Example
The following example demonstrates how to use the
readline module's history reading and writing functions to
automatically load and save a history file named .pyhist from
the user's home directory. The code below would normally be executed
automatically during interactive sessions from the user's
PYTHONSTARTUP file.


5.4.3 Running tests Using regrtest.py

writing-tests.html | module-test.html | module-math.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
5.4.2 Writing Unit Tests (writing-tests.html)
Up:
5.4 test (module-test.html)
Next:
5.5 math (module-math.html)
---
## 5.4.3 Running tests Using regrtest.py
regrtest.py is the script used to drive Python's regression test
suite.
Running the script by itself automatically starts running all
regression tests in the test package.
It does this by finding all modules in the package whose name starts with
`test_`, importing them, and executing the function test_main
if present.
The names of tests to execute may also be passed to the script.
Specifying a single regression test (`python regrtest.py test_spam.py`)
will minimize output and only print whether the test passed or failed and thus
minimize output.
Running regrtest.py directly allows what resources are
available for tests to use to be set.
You do this by using the `-u` command-line option.
Run `python regrtest.py -uall` to turn on all resources;
specifying `all` as an option for `-u` enables all possible
resources.
If all but one resource is desired (a more common case), a
comma-separated list of resources that are not desired may be listed after
`all`.
The command `python regrtest.py -uall,-audio,-largefile` will run
regrtest.py with all resources except the audio and largefile
resources.
For a list of all resources and more command-line options, run
`python regrtest.py -h`.


B. Reporting Bugs

node749.html | lib.html | node751.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
A.6 SGI-specific Extension modules (node749.html)
Up:
Python Library Reference (lib.html)
Next:
C. History and License (node751.html)
---
# B. Reporting Bugs
Python is a mature programming language which has established a
reputation for stability. In order to maintain this reputation, the
developers would like to know of any deficiencies you find in Python
or its documentation.
Before submitting a report, you will be required to log into SourceForge;
this will make it possible for the developers to contact you
for additional information if needed. It is not possible to submit a
bug report anonymously.
All bug reports should be submitted via the Python Bug Tracker on
SourceForge (http://sourceforge.net/bugs/?group_id=5470). The
bug tracker offers a Web form which allows pertinent information to be
entered and submitted to the developers.
The first step in filing a report is to determine whether the problem
has already been reported. The advantage in doing so, aside from
saving the developers time, is that you learn what has been done to
fix it; it may be that the problem has already been fixed for the next
release, or additional information is needed (in which case you are
welcome to provide it if you can!). To do this, search the bug
database using the search box near the bottom of the page.
If the problem you're reporting is not already in the bug tracker, go
back to the Python Bug Tracker
(http://sourceforge.net/bugs/?group_id=5470). Select the
``Submit a Bug'' link at the top of the page to open the bug reporting
form.
The submission form has a number of fields. The only fields that are
required are the ``Summary'' and ``Details'' fields. For the summary,
enter a very short description of the problem; less than ten
words is good. In the Details field, describe the problem in detail,
including what you expected to happen and what did happen. Be sure to
include the version of Python you used, whether any extension modules
were involved, and what hardware and software platform you were using
(including version information as appropriate).
The only other field that you may want to set is the ``Category''
field, which allows you to place the bug report into a broad category
(such as ``Documentation'' or ``Library'').
Each bug report will be assigned to a developer who will determine
what needs to be done to correct the problem. You will
receive an update each time action is taken on the bug.
See Also:


3.26.1 Repr Objects

module-repr.html | module-repr.html | subclassing-reprs.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
3.26 repr (module-repr.html)
Up:
3.26 repr (module-repr.html)
Next:
3.26.2 Subclassing Repr Objects (subclassing-reprs.html)
---
## 3.26.1 Repr Objects
Repr instances provide several members which can be used to
provide size limits for the representations of different object types,
and methods which format specific object types.


11.5.1 Request Objects

module-urllib2.html | module-urllib2.html | opener-director-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
11.5 urllib2 (module-urllib2.html)
Up:
11.5 urllib2 (module-urllib2.html)
Next:
11.5.2 OpenerDirector Objects (opener-director-objects.html)
---
## 11.5.1 Request Objects
The following methods describe all of Request's public interface,
and so all must be overridden in subclasses.


17. Restricted Execution

other-gui-packages.html | lib.html | module-rexec.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
16.6 Other Graphical User (other-gui-packages.html)
Up:
Python Library Reference (lib.html)
Next:
17.1 rexec (module-rexec.html)
---
# 17. Restricted Execution
Warning:
In Python 2.3 these modules have been disabled due to various known
and not readily fixable security holes. The modules are still
documented here to help in reading old code that uses the
rexec and Bastion modules.
Restricted execution is the basic framework in Python that allows
for the segregation of trusted and untrusted code. The framework is based on the
notion that trusted Python code (a supervisor) can create a
``padded cell' (or environment) with limited permissions, and run the
untrusted code within this cell. The untrusted code cannot break out
of its cell, and can only interact with sensitive system resources
through interfaces defined and managed by the trusted code. The term
``restricted execution'' is favored over ``safe-Python''
since true safety is hard to define, and is determined by the way the
restricted environment is created. Note that the restricted
environments can be nested, with inner cells creating subcells of
lesser, but never greater, privilege.
An interesting aspect of Python's restricted execution model is that
the interfaces presented to untrusted code usually have the same names
as those presented to trusted code. Therefore no special interfaces
need to be learned to write code designed to run in a restricted
environment. And because the exact nature of the padded cell is
determined by the supervisor, different restrictions can be imposed,
depending on the application. For example, it might be deemed
``safe'' for untrusted code to read any file within a specified
directory, but never to write a file. In this case, the supervisor
may redefine the built-in open() function so that it raises
an exception whenever the mode parameter is `'w'`. It
might also perform a chroot()-like operation on the
filename parameter, such that root is always relative to some
safe ``sandbox'' area of the filesystem. In this case, the untrusted
code would still see an built-in open() function in its
environment, with the same calling interface. The semantics would be
identical too, with IOErrors being raised when the
supervisor determined that an unallowable parameter is being used.
The Python run-time determines whether a particular code block is
executing in restricted execution mode based on the identity of the
`__builtins__` object in its global variables: if this is (the
dictionary of) the standard __builtin__ (module-builtin.html) module,
the code is deemed to be unrestricted, else it is deemed to be
restricted.
Python code executing in restricted mode faces a number of limitations
that are designed to prevent it from escaping from the padded cell.
For instance, the function object attribute func_globals and
the class and instance object attribute __dict__ are
unavailable.
Two modules provide the framework for setting up restricted execution
environments:
rexec (module-rexec.html) | Basic restricted execution framework.
Bastion (module-Bastion.html) | Providing restricted access to objects.


17.1.2 Defining restricted environments

rexec-objects.html | module-rexec.html | node678.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
17.1.1 RExec Objects (rexec-objects.html)
Up:
17.1 rexec (module-rexec.html)
Next:
17.1.3 An example (node678.html)
---
## 17.1.2 Defining restricted environments
The RExec class has the following class attributes, which are
used by the __init__() method. Changing them on an existing
instance won't have any effect; instead, create a subclass of
RExec and assign them new values in the class definition.
Instances of the new class will then use those new values. All these
attributes are tuples of strings.


17.1.1 RExec Objects

module-rexec.html | module-rexec.html | rexec-extension.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
17.1 rexec (module-rexec.html)
Up:
17.1 rexec (module-rexec.html)
Next:
17.1.2 Defining restricted environments (rexec-extension.html)
---
## 17.1.1 RExec Objects
RExec instances support the following methods:
Methods whose names begin with "s_" are similar to the functions
beginning with "r_", but the code will be granted access to
restricted versions of the standard I/O streams `sys.stdin`,
`sys.stderr`, and `sys.stdout`.
RExec objects must also support various methods which will be
implicitly called by code executing in the restricted environment.
Overriding these methods in a subclass is used to change the policies
enforced by a restricted environment.
And their equivalents with access to restricted standard I/O streams:


7.5.2 RLock Objects

lock-objects.html | module-threading.html | condition-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
7.5.1 Lock Objects (lock-objects.html)
Up:
7.5 threading (module-threading.html)
Next:
7.5.3 Condition Objects (condition-objects.html)
---
## 7.5.2 RLock Objects
A reentrant lock is a synchronization primitive that may be
acquired multiple times by the same thread. Internally, it uses
the concepts of ``owning thread'' and ``recursion level'' in
addition to the locked/unlocked state used by primitive locks. In
the locked state, some thread owns the lock; in the unlocked
state, no thread owns it.
To lock the lock, a thread calls its acquire() method; this
returns once the thread owns the lock. To unlock the lock, a
thread calls its release() method.
acquire()/release() call pairs may be nested; only
the final release() (the release() of the outermost
pair) resets the lock to unlocked and allows another thread blocked in
acquire() to proceed.


13.10.4 ErrorHandler Objects

entity-resolver-objects.html | module-xml.sax.handler.html | module-xml.sax.saxutils.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
13.10.3 EntityResolver Objects (entity-resolver-objects.html)
Up:
13.10 xml.sax.handler (module-xml.sax.handler.html)
Next:
13.11 xml.sax.saxutils (module-xml.sax.saxutils.html)
---
## 13.10.4 ErrorHandler Objects
Objects with this interface are used to receive error and warning
information from the XMLReader. If you create an object that
implements this interface, then register the object with your
XMLReader, the parser will call the methods in your object to
report all warnings and errors. There are three levels of errors
available: warnings, (possibly) recoverable errors, and unrecoverable
errors. All methods take a SAXParseException as the only
parameter. Errors and warnings may be converted to an exception by
raising the passed-in exception object.


13.9.1 SAXException Objects

module-xml.sax.html | module-xml.sax.html | module-xml.sax.handler.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
13.9 xml.sax (module-xml.sax.html)
Up:
13.9 xml.sax (module-xml.sax.html)
Next:
13.10 xml.sax.handler (module-xml.sax.handler.html)
---
## 13.9.1 SAXException Objects
The SAXException exception class supports the following
methods:


6.11.1 Scheduler Objects

module-sched.html | module-sched.html | module-mutex.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
6.11 sched (module-sched.html)
Up:
6.11 sched (module-sched.html)
Next:
6.12 mutex (module-mutex.html)
---
## 6.11.1 Scheduler Objects
scheduler instances have the following methods:


7.5.4.1 Semaphore Example

semaphore-objects.html | semaphore-objects.html | event-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
7.5.4 Semaphore Objects (semaphore-objects.html)
Up:
7.5.4 Semaphore Objects (semaphore-objects.html)
Next:
7.5.5 Event Objects (event-objects.html)
---
### 7.5.4.1 Semaphore Example
Semaphores are often used to guard resources with limited capacity, for
example, a database server. In any situation where the size of the resource
size is fixed, you should use a bounded semaphore. Before spawning any
worker threads, your main thread would initialize the semaphore:
```text

maxconnections = 5
...
pool_sema = BoundedSemaphore(value=maxconnections)
```
Once spawned, worker threads call the semaphore's acquire and release
methods when they need to connect to the server:
```text

pool_sema.acquire()
conn = connectdb()
... use connection ...
conn.close()
pool_sema.release()
```
The use of a bounded semaphore reduces the chance that a programming error
which causes the semaphore to be released more than it's acquired will go
undetected.


7.5.4 Semaphore Objects

condition-objects.html | module-threading.html | semaphore-examples.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
7.5.3 Condition Objects (condition-objects.html)
Up:
7.5 threading (module-threading.html)
Next:
7.5.4.1 Semaphore Example (semaphore-examples.html)
---
## 7.5.4 Semaphore Objects
This is one of the oldest synchronization primitives in the history of
computer science, invented by the early Dutch computer scientist
Edsger W. Dijkstra (he used P() and V() instead of
acquire() and release()).
A semaphore manages an internal counter which is decremented by each
acquire() call and incremented by each release()
call. The counter can never go below zero; when acquire()
finds that it is zero, it blocks, waiting until some other thread
calls release().


4.4.1 SequenceMatcher Objects

module-difflib.html | module-difflib.html | sequencematcher-examples.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
4.4 difflib (module-difflib.html)
Up:
4.4 difflib (module-difflib.html)
Next:
4.4.2 SequenceMatcher Examples (sequencematcher-examples.html)
---
## 4.4.1 SequenceMatcher Objects
The SequenceMatcher class has this constructor:
SequenceMatcher objects have the following methods:
SequenceMatcher computes and caches detailed information about
the second sequence, so if you want to compare one sequence against
many sequences, use set_seq2() to set the commonly used
sequence once and call set_seq1() repeatedly, once for each
of the other sequences.
The three methods that return the ratio of matching to total characters
can give different results due to differing levels of approximation,
although quick_ratio() and real_quick_ratio() are always
at least as large as ratio():
```text

>>> s = SequenceMatcher(None, "abcd", "bcde")
>>> s.ratio()
0.75
>>> s.quick_ratio()
0.75
>>> s.real_quick_ratio()
1.0
```


4.4.2 SequenceMatcher Examples

sequence-matcher.html | module-difflib.html | differ-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
4.4.1 SequenceMatcher Objects (sequence-matcher.html)
Up:
4.4 difflib (module-difflib.html)
Next:
4.4.3 Differ Objects (differ-objects.html)
---
## 4.4.2 SequenceMatcher Examples
This example compares two strings, considering blanks to be ``junk:''
```text

>>> s = SequenceMatcher(lambda x: x == " ",
... "private Thread currentThread;",
... "private volatile Thread currentThread;")
```
ratio() returns a float in [0, 1], measuring the similarity
of the sequences. As a rule of thumb, a ratio() value over
0.6 means the sequences are close matches:
```text

>>> print round(s.ratio(), 3)
0.866
```
If you're only interested in where the sequences match,
get_matching_blocks() is handy:
```text

>>> for block in s.get_matching_blocks():
... print "a[%d] and b[%d] match for %d elements" % block
a[0] and b[0] match for 8 elements
a[8] and b[17] match for 6 elements
a[14] and b[23] match for 15 elements
a[29] and b[38] match for 0 elements
```
Note that the last tuple returned by get_matching_blocks() is
always a dummy, `(len( a ), len( b ), 0)`, and this is
the only case in which the last tuple element (number of elements
matched) is `0`.
If you want to know how to change the first sequence into the second,
use get_opcodes():
```text

>>> for opcode in s.get_opcodes():
... print "%6s a[%d:%d] b[%d:%d]" % opcode
equal a[0:8] b[0:8]
insert a[8:8] b[8:17]
equal a[8:14] b[17:23]
equal a[14:29] b[23:38]
```
See also the function get_close_matches() in this module,
which shows how simple code building on SequenceMatcher can be
used to do useful work.


11.20.1 ServerProxy Objects

module-xmlrpclib.html | module-xmlrpclib.html | boolean-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
11.20 xmlrpclib (module-xmlrpclib.html)
Up:
11.20 xmlrpclib (module-xmlrpclib.html)
Next:
11.20.2 Boolean Objects (boolean-objects.html)
---
## 11.20.1 ServerProxy Objects
A ServerProxy instance has a method corresponding to
each remote procedure call accepted by the XML-RPC server. Calling
the method performs an RPC, dispatched by both name and argument
signature (e.g. the same method name can be overloaded with multiple
argument signatures). The RPC finishes by returning a value, which
may be either returned data in a conformant type or a Fault or
ProtocolError object indicating an error.
Servers that support the XML introspection API support some common
methods grouped under the reserved system member:
Introspection methods are currently supported by servers written in
PHP, C and Microsoft .NET. Partial introspection support is included
in recent updates to UserLand Frontier. Introspection support for
Perl, Python and Java is available at the XML-RPC Hacks page.


5.12.2 Example

set-objects.html | module-sets.html | immutable-transforms.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
5.12.1 Set Objects (set-objects.html)
Up:
5.12 sets (module-sets.html)
Next:
5.12.3 Protocol for automatic (immutable-transforms.html)
---
## 5.12.2 Example
```text

>>> from sets import Set
>>> engineers = Set(['John', 'Jane', 'Jack', 'Janice'])
>>> programmers = Set(['Jack', 'Sam', 'Susan', 'Janice'])
>>> management = Set(['Jane', 'Jack', 'Susan', 'Zack'])
>>> employees = engineers | programmers | management # union
>>> engineering_management = engineers & programmers # intersection
>>> fulltime_management = management - engineers - programmers # difference
>>> engineers.add('Marvin') # add element
>>> print engineers
Set(['Jane', 'Marvin', 'Janice', 'John', 'Jack'])
>>> employees.issuperset(engineers) # superset test
False
>>> employees.update(engineers) # update from another set
>>> employees.issuperset(engineers)
True
>>> for group in [engineers, programmers, management, employees]:
... group.discard('Susan') # unconditionally remove element
... print group
...
Set(['Jane', 'Marvin', 'Janice', 'John', 'Jack'])
Set(['Janice', 'Jack', 'Sam'])
Set(['Jane', 'Zack', 'Jack'])
Set(['Jack', 'Sam', 'Jane', 'Marvin', 'Janice', 'John', 'Zack'])
```


5.12.1 Set Objects

module-sets.html | module-sets.html | set-example.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
5.12 sets (module-sets.html)
Up:
5.12 sets (module-sets.html)
Next:
5.12.2 Example (set-example.html)
---
## 5.12.1 Set Objects
Instances of Set and ImmutableSet both provide
the following operations:
In addition, both Set and ImmutableSet
support set to set comparisons. Two sets are equal if and only if
every element of each set is contained in the other (each is a subset
of the other).
A set is less than another set if and only if the first set is a proper
subset of the second set (is a subset, but is not equal).
A set is greater than another set if and only if the first set is a proper
superset of the second set (is a superset, but is not equal).
The subset and equality comparisons do not generalize to a complete
ordering function. For example, any two disjoint sets are not equal and
are not subsets of each other, so none of the following are true:
`a < b`, `a == b`, or `a > b`.
Accordingly, sets do not implement the __cmp__ method.
Since sets only define partial ordering (subset relationships), the output
of the list.sort() method is undefined for lists of sets.
The following table lists operations available in ImmutableSet
but not found in Set:
The following table lists operations available in Set
but not found in ImmutableSet:


20. SGI IRIX Specific Services

node710.html | lib.html | module-al.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
19.5 Bytecode Generation (node710.html)
Up:
Python Library Reference (lib.html)
Next:
20.1 al (module-al.html)
---
# 20. SGI IRIX Specific Services
The modules described in this chapter provide interfaces to features
that are unique to SGI's IRIX operating system (versions 4 and 5).


5.19.2 shlex Objects

node180.html | module-shlex.html | shlex-parsing-rules.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
5.19.1 Module Contents (node180.html)
Up:
5.19 shlex (module-shlex.html)
Next:
5.19.3 Parsing Rules (shlex-parsing-rules.html)
---
## 5.19.2 shlex Objects
A shlex instance has the following methods:
Instances of shlex subclasses have some public instance
variables which either control lexical analysis or can be used for
debugging:


5.19.3 Parsing Rules

shlex-objects.html | module-shlex.html | allos.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
5.19.2 shlex Objects (shlex-objects.html)
Up:
5.19 shlex (module-shlex.html)
Next:
6. Generic Operating System (allos.html)
---
## 5.19.3 Parsing Rules
When operating in non-POSIX mode, shlex will try to obey to
the following rules.
- Quote characters are not recognized within words
(`Do"Not"Separate` is parsed as the single word
`Do"Not"Separate`);
- Escape characters are not recognized;
- Enclosing characters in quotes preserve the literal value of
all characters within the quotes;
- Closing quotes separate words (`"Do"Separate` is parsed
as `"Do"` and `Separate`);
- If whitespace_split is `False`, any character not
declared to be a word character, whitespace, or a quote will be
returned as a single-character token. If it is `True`,
shlex will only split words in whitespaces;
- EOF is signaled with an empty string (`''`);
- It's not possible to parse empty strings, even if quoted.
When operating in POSIX mode, shlex will try to obey to the
following parsing rules.
- Quotes are stripped out, and do not separate words
(`"Do"Not"Separate"` is parsed as the single word
`DoNotSeparate`);
- Non-quoted escape characters (e.g. "\")
preserve the literal value of the next character that follows;
- Enclosing characters in quotes which are not part of
escapedquotes (e.g. "'") preserve the literal
value of all characters within the quotes;
- Enclosing characters in quotes which are part of
escapedquotes (e.g. """) preserves the literal
value of all characters within the quotes, with the exception of
the characters mentioned in escape. The escape characters
retain its special meaning only when followed by the quote in use,
or the escape character itself. Otherwise the escape character
will be considered a normal character.
- EOF is signaled with a `None` value;
- Quoted empty strings (`''`) are allowed;


6.25.1 Example

module-shutil.html | module-shutil.html | module-locale.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
6.25 shutil (module-shutil.html)
Up:
6.25 shutil (module-shutil.html)
Next:
6.26 locale (module-locale.html)
---
## 6.25.1 Example
This example is the implementation of the copytree()
function, described above, with the docstring omitted. It
demonstrates many of the other functions provided by this module.


11.21.1 SimpleXMLRPCServer Objects

module-SimpleXMLRPCServer.html | module-SimpleXMLRPCServer.html | node478.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
11.21 SimpleXMLRPCServer (module-SimpleXMLRPCServer.html)
Up:
11.21 SimpleXMLRPCServer (module-SimpleXMLRPCServer.html)
Next:
11.21.2 CGIXMLRPCRequestHandler (node478.html)
---
## 11.21.1 SimpleXMLRPCServer Objects
The SimpleXMLRPCServer class is based on
SocketServer.TCPServer and provides a means of creating
simple, stand alone XML-RPC servers.
Example:
```text

class MyFuncs:
def div(self, x, y) : return div(x,y)

server = SimpleXMLRPCServer(("localhost", 8000))
server.register_function(pow)
server.register_function(lambda x,y: x+y, 'add')
server.register_introspection_functions()
server.register_instance(MyFuncs())
server.serve_forever()
```


11.12.2 SMTP Example

SMTP-objects.html | module-smtplib.html | module-telnetlib.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
11.12.1 SMTP Objects (SMTP-objects.html)
Up:
11.12 smtplib (module-smtplib.html)
Next:
11.13 telnetlib (module-telnetlib.html)
---
## 11.12.2 SMTP Example
This example prompts the user for addresses needed in the message
envelope (`To' and `From' addresses), and the message to be
delivered. Note that the headers to be included with the message must
be included in the message as entered; this example doesn't do any
processing of the RFC 822 (http://www.faqs.org/rfcs/rfc822.html) headers. In particular, the `To' and
`From' addresses must be included in the message headers explicitly.


11.12.1 SMTP Objects

module-smtplib.html | module-smtplib.html | SMTP-example.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
11.12 smtplib (module-smtplib.html)
Up:
11.12 smtplib (module-smtplib.html)
Next:
11.12.2 SMTP Example (SMTP-example.html)
---
## 11.12.1 SMTP Objects
An SMTP instance has the following methods:
Low-level methods corresponding to the standard SMTP/ESMTP commands
"HELP", "RSET", "NOOP", "MAIL", "RCPT", and
"DATA" are also supported. Normally these do not need to be
called directly, so they are not documented here. For details,
consult the module code.


7.2.3 Example

ssl-objects.html | module-socket.html | module-select.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
7.2.2 SSL Objects (ssl-objects.html)
Up:
7.2 socket (module-socket.html)
Next:
7.3 select (module-select.html)
---
## 7.2.3 Example
Here are four minimal example programs using the TCP/IP protocol: a
server that echoes all data that it receives back (servicing only one
client), and a client using it. Note that a server must perform the
sequence socket(), bind(), listen(),
accept() (possibly repeating the accept() to service
more than one client), while a client only needs the sequence
socket(), connect(). Also note that the server
does not send()/recv() on the
socket it is listening on but on the new socket returned by
accept().
The first two examples support IPv4 only.
```text

# Echo server program
import socket

HOST = '' # Symbolic name meaning the local host
PORT = 50007 # Arbitrary non-privileged port
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
s.listen(1)
conn, addr = s.accept()
print 'Connected by', addr
while 1:
data = conn.recv(1024)
if not data: break
conn.send(data)
conn.close()
```
```text

# Echo client program
import socket

HOST = 'daring.cwi.nl' # The remote host
PORT = 50007 # The same port as used by the server
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))
s.send('Hello, world')
data = s.recv(1024)
s.close()
print 'Received', `data`
```
The next two examples are identical to the above two, but support both
IPv4 and IPv6.
The server side will listen to the first address family available
(it should listen to both instead).
On most of IPv6-ready systems, IPv6 will take precedence
and the server may not accept IPv4 traffic.
The client side will try to connect to the all addresses returned as a result
of the name resolution, and sends traffic to the first one connected
successfully.
```text

# Echo server program
import socket
import sys

HOST = '' # Symbolic name meaning the local host
PORT = 50007 # Arbitrary non-privileged port
s = None
for res in socket.getaddrinfo(HOST, PORT, socket.AF_UNSPEC, socket.SOCK_STREAM, 0, socket.AI_PASSIVE):
af, socktype, proto, canonname, sa = res
try:
s = socket.socket(af, socktype, proto)
except socket.error, msg:
s = None
continue
try:
s.bind(sa)
s.listen(1)
except socket.error, msg:
s.close()
s = None
continue
break
if s is None:
print 'could not open socket'
sys.exit(1)
conn, addr = s.accept()
print 'Connected by', addr
while 1:
data = conn.recv(1024)
if not data: break
conn.send(data)
conn.close()
```


7.2.1 Socket Objects

module-socket.html | module-socket.html | ssl-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
7.2 socket (module-socket.html)
Up:
7.2 socket (module-socket.html)
Next:
7.2.2 SSL Objects (ssl-objects.html)
---
## 7.2.1 Socket Objects
Socket objects have the following methods. Except for
makefile() these correspond to Unix system calls
applicable to sockets.
Some notes on socket blocking and timeouts: A socket object can be in
one of three modes: blocking, non-blocking, or timeout. Sockets are
always created in blocking mode. In blocking mode, operations block
until complete. In non-blocking mode, operations fail (with an error
that is unfortunately system-dependent) if they cannot be completed
immediately. In timeout mode, operations fail if they cannot be
completed within the timeout specified for the socket. The
setblocking() method is simply a shorthand for certain
settimeout() calls.
Timeout mode internally sets the socket in non-blocking mode. The
blocking and timeout modes are shared between file descriptors and
socket objects that refer to the same network endpoint. A consequence
of this is that file objects returned by the makefile()
method should only be used when the socket is in blocking mode; in
timeout or non-blocking mode file operations that cannot be completed
immediately will fail.
Note that there are no methods read() or write();
use recv() and send() without flags argument
instead.


7. Optional Operating System Services

node301.html | lib.html | module-signal.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
6.28.8.1 Basic example - (node301.html)
Up:
Python Library Reference (lib.html)
Next:
7.1 signal (module-signal.html)
---
# 7. Optional Operating System Services
The modules described in this chapter provide interfaces to operating
system features that are available on selected operating systems only.
The interfaces are generally modeled after the Unix or C
interfaces but they are available on some other systems as well
(e.g. Windows or NT). Here's an overview:


2.2.10 Special Attributes

typesinternal.html | types.html | module-exceptions.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
2.2.9.10 Internal Objects (typesinternal.html)
Up:
2.2 Built-in Types (types.html)
Next:
2.3 Built-in Exceptions (module-exceptions.html)
---
## 2.2.10 Special Attributes
The implementation adds a few special read-only attributes to several
object types, where they are relevant:


7.2.2 SSL Objects

socket-objects.html | module-socket.html | socket-example.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
7.2.1 Socket Objects (socket-objects.html)
Up:
7.2 socket (module-socket.html)
Next:
7.2.3 Example (socket-example.html)
---
## 7.2.2 SSL Objects
SSL objects have the following methods.


4.9.1.3 StreamReader Objects

stream-writer-objects.html | node120.html | stream-reader-writer.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
4.9.1.2 StreamWriter Objects (stream-writer-objects.html)
Up:
4.9.1 Codec Base Classes (node120.html)
Next:
4.9.1.4 StreamReaderWriter Objects (stream-reader-writer.html)
---
### 4.9.1.3 StreamReader Objects
The StreamReader class is a subclass of Codec and
defines the following methods which every stream reader must define in
order to be compatible to the Python codec registry.
In addition to the above methods, the StreamReader must also
inherit all other methods and attribute from the underlying stream.
The next two base classes are included for convenience. They are not
needed by the codec registry, but may provide useful in practice.


4.9.1.4 StreamReaderWriter Objects

stream-reader-objects.html | node120.html | stream-recoder-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
4.9.1.3 StreamReader Objects (stream-reader-objects.html)
Up:
4.9.1 Codec Base Classes (node120.html)
Next:
4.9.1.5 StreamRecoder Objects (stream-recoder-objects.html)
---
### 4.9.1.4 StreamReaderWriter Objects
The StreamReaderWriter allows wrapping streams which work in
both read and write modes.
The design is such that one can use the factory functions returned by
the lookup() function to construct the instance.
StreamReaderWriter instances define the combined interfaces of
StreamReader and StreamWriter classes. They inherit
all other methods and attribute from the underlying stream.


4.9.1.5 StreamRecoder Objects

stream-reader-writer.html | node120.html | node126.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
4.9.1.4 StreamReaderWriter Objects (stream-reader-writer.html)
Up:
4.9.1 Codec Base Classes (node120.html)
Next:
4.9.2 Standard Encodings (node126.html)
---
### 4.9.1.5 StreamRecoder Objects
The StreamRecoder provide a frontend - backend view of
encoding data which is sometimes useful when dealing with different
encoding environments.
The design is such that one can use the factory functions returned by
the lookup() function to construct the instance.
StreamRecoder instances define the combined interfaces of
StreamReader and StreamWriter classes. They inherit
all other methods and attribute from the underlying stream.


4.9.1.2 StreamWriter Objects

codec-objects.html | node120.html | stream-reader-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
4.9.1.1 Codec Objects (codec-objects.html)
Up:
4.9.1 Codec Base Classes (node120.html)
Next:
4.9.1.3 StreamReader Objects (stream-reader-objects.html)
---
### 4.9.1.2 StreamWriter Objects
The StreamWriter class is a subclass of Codec and
defines the following methods which every stream writer must define in
order to be compatible to the Python codec registry.
In addition to the above methods, the StreamWriter must also
inherit all other methods and attribute from the underlying stream.


2.2.6.1 String Methods

typesseq.html | typesseq.html | typesseq-strings.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
2.2.6 Sequence Types (typesseq.html)
Up:
2.2.6 Sequence Types (typesseq.html)
Next:
2.2.6.2 String Formatting Operations (typesseq-strings.html)
---
### 2.2.6.1 String Methods
These are the string methods which both 8-bit strings and Unicode
objects support:


4. String Services

module-future.html | lib.html | module-string.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
3.32 __future__ (module-future.html)
Up:
Python Library Reference (lib.html)
Next:
4.1 string (module-string.html)
---
# 4. String Services
The modules described in this chapter provide a wide range of string
manipulation operations. Here's an overview:
string (module-string.html) | Common string operations.
re (module-re.html) | Regular expression search and match operations with a
Perl-style expression syntax.
struct (module-struct.html) | Interpret strings as packed binary data.
difflib (module-difflib.html) | Helpers for computing differences between objects.
fpformat (module-fpformat.html) | General floating point formatting functions.
StringIO (module-StringIO.html) | Read and write strings as if they were files.
cStringIO (module-cStringIO.html) | Faster version of StringIO, but not
subclassable.
textwrap (module-textwrap.html) | Text wrapping and filling
codecs (module-codecs.html) | Encode and decode data and streams.
encodings.idna (module-encodings.idna.html) | Internationalized Domain Names implementation
unicodedata (module-unicodedata.html) | Access the Unicode Database.
stringprep (module-stringprep.html) | String preparation, as per RFC 3453


3.26.2 Subclassing Repr Objects

Repr-objects.html | module-repr.html | module-new.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
3.26.1 Repr Objects (Repr-objects.html)
Up:
3.26 repr (module-repr.html)
Next:
3.27 new (module-new.html)
---
## 3.26.2 Subclassing Repr Objects
The use of dynamic dispatching by Repr.repr1() allows
subclasses of Repr to add support for additional built-in
object types or to modify the handling of types already supported.
This example shows how special support for file objects could be
added:


21. SunOS Specific Services

module-jpeg.html | lib.html | module-sunaudiodev.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
20.12 jpeg (module-jpeg.html)
Up:
Python Library Reference (lib.html)
Next:
21.1 sunaudiodev (module-sunaudiodev.html)
---
# 21. SunOS Specific Services
The modules described in this chapter provide interfaces to features
that are unique to the SunOS operating system (versions 4 and 5; the
latter is also known as Solaris version 2).


7.19.3 Examples

tarinfo-objects.html | module-tarfile.html | module-readline.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
7.19.2 TarInfo Objects (tarinfo-objects.html)
Up:
7.19 tarfile (module-tarfile.html)
Next:
7.20 readline (module-readline.html)
---
## 7.19.3 Examples
How to create an uncompressed tar archive from a list of filenames:
```text

import tarfile
tar = tarfile.open("sample.tar", "w")
for name in ["foo", "bar", "quux"]:
tar.add(name)
tar.close()
```
How to read a gzip compressed tar archive and display some member information:
```text

import tarfile
tar = tarfile.open("sample.tar.gz", "r:gz")
for tarinfo in tar:
print tarinfo.name, "is", tarinfo.size, "bytes in size and is",
if tarinfo.isreg():
print "a regular file."
elif tarinfo.isdir():
print "a directory."
else:
print "something else."
tar.close()
```
How to create a tar archive with faked information:
```text

import tarfile
tar = tarfile.open("sample.tar.gz", "w:gz")
for name in namelist:
tarinfo = tar.gettarinfo(name, "fakeproj-1.0/" + name)
tarinfo.uid = 123
tarinfo.gid = 456
tarinfo.uname = "johndoe"
tarinfo.gname = "fake"
tar.addfile(tarinfo, file(name))
tar.close()
```


7.19.1 TarFile Objects

module-tarfile.html | module-tarfile.html | tarinfo-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
7.19 tarfile (module-tarfile.html)
Up:
7.19 tarfile (module-tarfile.html)
Next:
7.19.2 TarInfo Objects (tarinfo-objects.html)
---
## 7.19.1 TarFile Objects
The TarFile object provides an interface to a tar archive. A tar
archive is a sequence of blocks. An archive member (a stored file) is made up
of a header block followed by data blocks. It is possible, to store a file in a
tar archive several times. Each archive member is represented by a
TarInfo object, see TarInfo Objects (section
7.19.2 (tarinfo-objects.html#tarinfo-objects)) for details.


7.19.2 TarInfo Objects

tarfile-objects.html | module-tarfile.html | tar-examples.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
7.19.1 TarFile Objects (tarfile-objects.html)
Up:
7.19 tarfile (module-tarfile.html)
Next:
7.19.3 Examples (tar-examples.html)
---
## 7.19.2 TarInfo Objects
A TarInfo object represents one member in a TarFile. Aside from
storing all required attributes of a file (like file type, size, time,
permissions, owner etc.), it provides some useful methods to determine its
type. It does not contain the file's data itself.
TarInfo objects are returned by `TarFile`'s methods
`getmember()`, `getmembers()` and `gettarinfo()`.
A `TarInfo` object has the following public data attributes:
A TarInfo object also provides some convenient query methods:


11.13.2 Telnet Example

telnet-objects.html | module-telnetlib.html | module-urlparse.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
11.13.1 Telnet Objects (telnet-objects.html)
Up:
11.13 telnetlib (module-telnetlib.html)
Next:
11.14 urlparse (module-urlparse.html)
---
## 11.13.2 Telnet Example
A simple example illustrating typical use:


11.13.1 Telnet Objects

module-telnetlib.html | module-telnetlib.html | telnet-example.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
11.13 telnetlib (module-telnetlib.html)
Up:
11.13 telnetlib (module-telnetlib.html)
Next:
11.13.2 Telnet Example (telnet-example.html)
---
## 11.13.1 Telnet Objects
Telnet instances have the following methods:


8.13.1 Template Objects

module-pipes.html | module-pipes.html | module-posixfile.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
8.13 pipes (module-pipes.html)
Up:
8.13 pipes (module-pipes.html)
Next:
8.14 posixfile (module-posixfile.html)
---
## 8.13.1 Template Objects
Template objects following methods:


5.3.5 TestCase Objects

unittest-contents.html | module-unittest.html | testsuite-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
5.3.4 Classes and functions (unittest-contents.html)
Up:
5.3 unittest (module-unittest.html)
Next:
5.3.6 TestSuite Objects (testsuite-objects.html)
---
## 5.3.5 TestCase Objects
Each TestCase instance represents a single test, but each
concrete subclass may be used to define multiple tests -- the
concrete class represents a single test fixture. The fixture is
created and cleaned up for each test case.
TestCase instances provide three groups of methods: one group
used to run the test, another used by the test implementation to
check conditions and report failures, and some inquiry methods
allowing information about the test itself to be gathered.
Methods in the first group are:
The test code can use any of the following methods to check for and
report failures.
Testing frameworks can use the following methods to collect
information on the test:


5.3.8 TestLoader Objects

testresult-objects.html | module-unittest.html | unittest-error-info.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
5.3.7 TestResult Objects (testresult-objects.html)
Up:
5.3 unittest (module-unittest.html)
Next:
5.3.9 Getting Extended Error (unittest-error-info.html)
---
## 5.3.8 TestLoader Objects
The TestLoader class is used to create test suites from
classes and modules. Normally, there is no need to create an instance
of this class; the unittest (module-unittest.html) module provides an instance
that can be shared as the `defaultTestLoader` module attribute.
Using a subclass or instance would allow customization of some
configurable properties.
TestLoader objects have the following methods:
The following attributes of a TestLoader can be configured
either by subclassing or assignment on an instance:


5.3.7 TestResult Objects

testsuite-objects.html | module-unittest.html | testloader-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
5.3.6 TestSuite Objects (testsuite-objects.html)
Up:
5.3 unittest (module-unittest.html)
Next:
5.3.8 TestLoader Objects (testloader-objects.html)
---
## 5.3.7 TestResult Objects
A TestResult object stores the results of a set of tests. The
TestCase and TestSuite classes ensure that results are
properly stored; test authors do not need to worry about recording the
outcome of tests.
Testing frameworks built on top of unittest (module-unittest.html) may want
access to the TestResult object generated by running a set of
tests for reporting purposes; a TestResult instance is
returned by the TestRunner.run() method for this purpose.
Each instance holds the total number of tests run, and collections of
failures and errors that occurred among those test runs. The
collections contain tuples of `( testcase , traceback )`, where traceback is a string containing a
formatted version of the traceback for the exception.
TestResult instances have the following attributes that will
be of interest when inspecting the results of running a set of tests:
The following methods of the TestResult class are used to
maintain the internal data structures, and mmay be extended in
subclasses to support additional reporting requirements. This is
particularly useful in building tools which support interactive
reporting while tests are being run.
One additional method is available for TestResult objects:


5.3.6 TestSuite Objects

testcase-objects.html | module-unittest.html | testresult-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
5.3.5 TestCase Objects (testcase-objects.html)
Up:
5.3 unittest (module-unittest.html)
Next:
5.3.7 TestResult Objects (testresult-objects.html)
---
## 5.3.6 TestSuite Objects
TestSuite objects behave much like TestCase objects,
except they do not actually implement a test. Instead, they are used
to aggregate tests into groups that should be run together. Some
additional methods are available to add tests to TestSuite
instances:
The run() method is also slightly different:
In the typical usage of a TestSuite object, the run()
method is invoked by a TestRunner rather than by the end-user
test harness.


7.5.6 Thread Objects

event-objects.html | module-threading.html | timer-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
7.5.5 Event Objects (event-objects.html)
Up:
7.5 threading (module-threading.html)
Next:
7.5.7 Timer Objects (timer-objects.html)
---
## 7.5.6 Thread Objects
This class represents an activity that is run in a separate thread
of control. There are two ways to specify the activity: by
passing a callable object to the constructor, or by overriding the
run() method in a subclass. No other methods (except for the
constructor) should be overridden in a subclass. In other words,
only override the __init__() and run()
methods of this class.
Once a thread object is created, its activity must be started by
calling the thread's start() method. This invokes the
run() method in a separate thread of control.
Once the thread's activity is started, the thread is considered
'alive' and 'active' (these concepts are almost, but not quite
exactly, the same; their definition is intentionally somewhat
vague). It stops being alive and active when its run()
method terminates - either normally, or by raising an unhandled
exception. The isAlive() method tests whether the thread is
alive.
Other threads can call a thread's join() method. This blocks
the calling thread until the thread whose join() method is
called is terminated.
A thread has a name. The name can be passed to the constructor,
set with the setName() method, and retrieved with the
getName() method.
A thread can be flagged as a ``daemon thread''. The significance
of this flag is that the entire Python program exits when only
daemon threads are left. The initial value is inherited from the
creating thread. The flag can be set with the setDaemon()
method and retrieved with the isDaemon() method.
There is a ``main thread'' object; this corresponds to the
initial thread of control in the Python program. It is not a
daemon thread.
There is the possibility that ``dummy thread objects'' are
created. These are thread objects corresponding to ``alien
threads''. These are threads of control started outside the
threading module, such as directly from C code. Dummy thread objects
have limited functionality; they are always considered alive,
active, and daemonic, and cannot be join()ed. They are never
deleted, since it is impossible to detect the termination of alien
threads.


7.5.7 Timer Objects

thread-objects.html | module-threading.html | module-dummythread.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
7.5.6 Thread Objects (thread-objects.html)
Up:
7.5 threading (module-threading.html)
Next:
7.6 dummy_thread (module-dummythread.html)
---
## 7.5.7 Timer Objects
This class represents an action that should be run only after a
certain amount of time has passed -- a timer. Timer is a
subclass of Thread and as such also functions as an example of
creating custom threads.
Timers are started, as with threads, by calling their start()
method. The timer can be stopped (before its action has begun) by
calling the cancel() method. The interval the timer will
wait before executing its action may not be exactly the same as the
interval specified by the user.
For example:
```text

def hello():
print "hello, world"

t = Timer(30.0, hello)
t.start() # after 30 seconds, "hello, world" will be printed
```


16.1.4 Mapping Basic Tk into Tkinter

node634.html | module-Tkinter.html | node636.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
16.1.3 A (Very) Quick (node634.html)
Up:
16.1 Tkinter (module-Tkinter.html)
Next:
16.1.5 How Tk and (node636.html)
---
## 16.1.4 Mapping Basic Tk into Tkinter
Class commands in Tk correspond to class constructors in Tkinter.
```text

button .fred =====> fred = Button()
```
The master of an object is implicit in the new name given to it at
creation time. In Tkinter, masters are specified explicitly.
```text

button .panel.fred =====> fred = Button(panel)
```
The configuration options in Tk are given in lists of hyphened tags
followed by values. In Tkinter, options are specified as
keyword-arguments in the instance constructor, and keyword-args for
configure calls or as instance indices, in dictionary style, for
established instances. See section 16.1.6 (tkinter-setting-options.html#tkinter-setting-options) on
setting options.
```text

button .fred -fg red =====> fred = Button(panel, fg = "red")
.fred configure -fg red =====> fred["fg"] = red
OR ==> fred.config(fg = "red")
```
In Tk, to perform an action on a widget, use the widget name as a
command, and follow it with an action name, possibly with arguments
(options). In Tkinter, you call methods on the class instance to
invoke actions on the widget. The actions (methods) that a given
widget can perform are listed in the Tkinter.py module.
```text

.fred invoke =====> fred.invoke()
```
To give a widget to the packer (geometry manager), you call pack with
optional arguments. In Tkinter, the Pack class holds all this
functionality, and the various forms of the pack command are
implemented as methods. All widgets in Tkinter (module-Tkinter.html) are
subclassed from the Packer, and so inherit all the packing
methods. See the Tix (module-Tix.html) module documentation for additional
information on the Form geometry manager.
```text

pack .fred -side left =====> fred.pack(side = "left")
```


16.1.6.1 Setting Options

node637.html | node637.html | node639.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
16.1.6 Handy Reference (node637.html)
Up:
16.1.6 Handy Reference (node637.html)
Next:
16.1.6.2 The Packer (node639.html)
---
### 16.1.6.1 Setting Options
Options control things like the color and border width of a widget.
Options can be set in three ways:
At object creation time, using keyword arguments: :
```text

fred = Button(self, fg = "red", bg = "blue")
```
After object creation, treating the option name like a dictionary index: :
```text

fred["fg"] = "red"
fred["bg"] = "blue"
```
Use the config() method to update multiple attrs subesequent to
object creation: :
```text

fred.config(fg = "red", bg = "blue")
```
For a complete explanation of a given option and its behavior, see the
Tk man pages for the widget in question.
Note that the man pages list "STANDARD OPTIONS" and "WIDGET SPECIFIC
OPTIONS" for each widget. The former is a list of options that are
common to many widgets, the latter are the options that are
ideosyncratic to that particular widget. The Standard Options are
documented on the options(3) man page.
No distinction between standard and widget-specific options is made in
this document. Some options don't apply to some kinds of widgets.
Whether a given widget responds to a particular option depends on the
class of the widget; buttons have a `command` option, labels do not.
The options supported by a given widget are listed in that widget's
man page, or can be queried at runtime by calling the
config() method without arguments, or by calling the
keys() method on that widget. The return value of these
calls is a dictionary whose key is the name of the option as a string
(for example, `'relief'`) and whose values are 5-tuples.
Some options, like `bg` are synonyms for common options with long
names (`bg` is shorthand for "background"). Passing the
`config()` method the name of a shorthand option will return a
2-tuple, not 5-tuple. The 2-tuple passed back will contain the name of
the synonym and the ``real'' option (such as `('bg',
'background')`).
Example:
```text

>>> print fred.config()
{'relief' : ('relief', 'relief', 'Relief', 'raised', 'groove')}
```
Of course, the dictionary printed will include all the options
available and their values. This is meant only as an example.


16. Graphical User Interfaces with Tk

module-rotor.html | lib.html | module-Tkinter.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
15.5 rotor (module-rotor.html)
Up:
Python Library Reference (lib.html)
Next:
16.1 Tkinter (module-Tkinter.html)
---
# 16. Graphical User Interfaces with Tk
Tk/Tcl has long been an integral part of Python. It provides a robust
and platform independent windowing toolkit, that is available to
Python programmers using the Tkinter (module-Tkinter.html) module, and its
extension, the Tix (module-Tix.html) module.
The Tkinter (module-Tkinter.html) module is a thin object-oriented layer on top of
Tcl/Tk. To use Tkinter (module-Tkinter.html), you don't need to write Tcl code,
but you will need to consult the Tk documentation, and occasionally
the Tcl documentation. Tkinter (module-Tkinter.html) is a set of wrappers that
implement the Tk widgets as Python classes. In addition, the internal
module _tkinter provides a threadsafe mechanism which allows
Python and Tcl to interact.
Tk is not the only GUI for Python, but is however the most commonly
used one; see section #other-gui-modules, ``Other User Interface
Modules and Packages,'' for more information on other GUI toolkits for
Python.
Tkinter (module-Tkinter.html) | Interface to Tcl/Tk for graphical user interfaces
Tix (module-Tix.html) | Tk Extension Widgets for Tkinter
ScrolledText (module-ScrolledText.html) | Text widget with a vertical scroll bar.
turtle (module-turtle.html) | An environment for turtle graphics.


3.12.1 Traceback Example

module-traceback.html | module-traceback.html | module-linecache.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
3.12 traceback (module-traceback.html)
Up:
3.12 traceback (module-traceback.html)
Next:
3.13 linecache (module-linecache.html)
---
## 3.12.1 Traceback Example
This simple example implements a basic read-eval-print loop, similar
to (but less useful than) the standard Python interactive interpreter
loop. For a more complete implementation of the interpreter loop,
refer to the code (module-code.html) module.


2.2.1 Truth Value Testing

types.html | types.html | boolean.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
2.2 Built-in Types (types.html)
Up:
2.2 Built-in Types (types.html)
Next:
2.2.2 Boolean Operations (boolean.html)
---
## 2.2.1 Truth Value Testing
Any object can be tested for truth value, for use in an if or
while condition or as operand of the Boolean operations below.
The following values are considered false:
- `None`
- `False`
- zero of any numeric type, for example, `0`, `0L`,
`0.0`, `0j`.
- any empty sequence, for example, `''`, `()`, `[]`.
- any empty mapping, for example, `{}`.
- instances of user-defined classes, if the class defines a
__nonzero__() or __len__() method, when that
method returns the integer zero or bool value
`False`.2.5 (#foot3003)
All other values are considered true -- so objects of many types are
always true.
Operations and built-in functions that have a Boolean result always
return `0` or `False` for false and `1` or `True`
for true, unless otherwise stated. (Important exception: the Boolean
operations "or" and "and" always
return one of their operands.)


2.2.5 Iterator Types

bitstring-ops.html | types.html | typesseq.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
2.2.4.1 Bit-string Operations on (bitstring-ops.html)
Up:
2.2 Built-in Types (types.html)
Next:
2.2.6 Sequence Types (typesseq.html)
---
## 2.2.5 Iterator Types
New in version 2.2.
Python supports a concept of iteration over containers. This is
implemented using two distinct methods; these are used to allow
user-defined classes to support iteration. Sequences, described below
in more detail, always support the iteration methods.
One method needs to be defined for container objects to provide
iteration support:
The iterator objects themselves are required to support the following
two methods, which together form the iterator protocol:
Python defines several iterator objects to support iteration over
general and specific sequence types, dictionaries, and other more
specialized forms. The specific types are not important beyond their
implementation of the iterator protocol.
The intention of the protocol is that once an iterator's
next() method raises StopIteration, it will
continue to do so on subsequent calls. Implementations that
do not obey this property are deemed broken. (This constraint
was added in Python 2.3; in Python 2.2, various iterators are
broken according to this rule.)
Python's generators provide a convenient way to implement the
iterator protocol. If a container object's __iter__()
method is implemented as a generator, it will automatically
return an iterator object (technically, a generator object)
supplying the __iter__() and next() methods.


2.2 Built-in Types

built-in-funcs.html | builtin.html | truth.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
2.1 Built-in Functions (built-in-funcs.html)
Up:
2. Built-In Objects (builtin.html)
Next:
2.2.1 Truth Value Testing (truth.html)
---
# 2.2 Built-in Types
The following sections describe the standard types that are built into
the interpreter. Historically, Python's built-in types have differed
from user-defined types because it was not possible to use the built-in
types as the basis for object-oriented inheritance. With the 2.2
release this situation has started to change, although the intended
unification of user-defined and built-in types is as yet far from
complete.
The principal built-in types are numerics, sequences, mappings, files
classes, instances and exceptions.
Some operations are supported by several object types; in particular,
all objects can be compared, tested for truth value, and converted to
a string (with the `` ...`` notation). The latter
conversion is implicitly used when an object is written by the
print statement.
(Information on print statement (../ref/print.html)
and other language statements can be found in the
Python Reference Manual (../ref/ref.html) and the
Python Tutorial (../tut/tut.html).)


2.2.9.3 Functions

typesobjects.html | typesother.html | typesmethods.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
2.2.9.2 Classes and Class (typesobjects.html)
Up:
2.2.9 Other Built-in Types (typesother.html)
Next:
2.2.9.4 Methods (typesmethods.html)
---
### 2.2.9.3 Functions
Function objects are created by function definitions. The only
operation on a function object is to call it:
`func ( argument-list )`.
There are really two flavors of function objects: built-in functions
and user-defined functions. Both support the same operation (to call
the function), but the implementation is different, hence the
different object types.
The implementation adds two special read-only attributes:
`f .func_code` is a function's code
object (see below) and `f .func_globals` is
the dictionary used as the function's global namespace (this is the
same as `m .__dict__` where m is the module in which
the function f was defined).
Function objects also support getting and setting arbitrary
attributes, which can be used to, e.g. attach metadata to functions.
Regular attribute dot-notation is used to get and set such
attributes. Note that the current implementation only supports
function attributes on user-defined functions. Function attributes on
built-in functions may be supported in the future.
Functions have another special attribute `f .__dict__`
(a.k.a. `f .func_dict`) which contains the namespace used to
support function attributes. `__dict__` and `func_dict` can
be accessed directly or set to a dictionary object. A function's
dictionary cannot be deleted.


2.2.9.10 Internal Objects

node29.html | typesother.html | specialattrs.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
2.2.9.9 Boolean Values (node29.html)
Up:
2.2.9 Other Built-in Types (typesother.html)
Next:
2.2.10 Special Attributes (specialattrs.html)
---
### 2.2.9.10 Internal Objects
See the Python Reference Manual (../ref/ref.html) for this
information. It describes stack frame objects, traceback objects, and
slice objects.


2.2.7 Mapping Types

typesseq-mutable.html | types.html | bltin-file-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
2.2.6.4 Mutable Sequence Types (typesseq-mutable.html)
Up:
2.2 Built-in Types (types.html)
Next:
2.2.8 File Objects (bltin-file-objects.html)
---
## 2.2.7 Mapping Types
A mapping object maps immutable values to
arbitrary objects. Mappings are mutable objects. There is currently
only one standard mapping type, the dictionary. A dictionary's keys are
almost arbitrary values. Only values containing lists, dictionaries
or other mutable types (that are compared by value rather than by
object identity) may not be used as keys.
Numeric types used for keys obey the normal rules for numeric
comparison: if two numbers compare equal (e.g. `1` and
`1.0`) then they can be used interchangeably to index the same
dictionary entry.
Dictionaries are created by placing a comma-separated list of
`key : value` pairs within braces, for example:
`{'jack': 4098, 'sjoerd': 4127}` or
`{4098: 'jack', 4127: 'sjoerd'}`.
The following operations are defined on mappings (where a and
b are mappings, k is a key, and v and x are
arbitrary objects):
Notes:
(1): Raises a KeyError exception if k is not
in the map.
(2): New in version 2.2.
(3): Keys and values are listed in random order. If
items(), keys(), values(),
iteritems(), iterkeys(), and itervalues()
are called with no intervening modifications to the dictionary, the
lists will directly correspond. This allows the creation of
`( value , key )` pairs using zip():
"pairs = zip(a.values(), a.keys())". The same
relationship holds for the iterkeys() and
itervalues() methods: "pairs = zip(a.itervalues(),
a.iterkeys())" provides the same value for `pairs`.
Another way to create the same list is "pairs = [(v, k) for (k,
v) in a.iteritems()]".
(4): Never raises an exception if k is not in the map,
instead it returns x. x is optional; when x is not
provided and k is not in the map, `None` is returned.
(5): setdefault() is like get(), except
that if k is missing, x is both returned and inserted into
the dictionary as the value of k.
(6): popitem() is useful to destructively iterate
over a dictionary, as often used in set algorithms.
(7): fromkeys() is a class method that returns a
new dictionary. value defaults to `None`.
New in version 2.3.
(8): pop() raises a KeyError when no default
value is given and the key is not found.
New in version 2.3.


2.2.9.4 Methods

typesfunctions.html | typesother.html | bltin-code-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
2.2.9.3 Functions (typesfunctions.html)
Up:
2.2.9 Other Built-in Types (typesother.html)
Next:
2.2.9.5 Code Objects (bltin-code-objects.html)
---
### 2.2.9.4 Methods
Methods are functions that are called using the attribute notation.
There are two flavors: built-in methods (such as append() on
lists) and class instance methods. Built-in methods are described
with the types that support them.
The implementation adds two special read-only attributes to class
instance methods: `m .im_self` is the object on which the
method operates, and `m .im_func` is the function
implementing the method. Calling `m ( arg-1 , arg-2 , ..., arg-n )` is completely equivalent to
calling `m .im_func( m .im_self, arg-1 , arg-2 , ..., arg-n )`.
Class instance methods are either bound or unbound,
referring to whether the method was accessed through an instance or a
class, respectively. When a method is unbound, its `im_self`
attribute will be `None` and if called, an explicit `self`
object must be passed as the first argument. In this case,
`self` must be an instance of the unbound method's class (or a
subclass of that class), otherwise a `TypeError` is raised.
Like function objects, methods objects support getting
arbitrary attributes. However, since method attributes are actually
stored on the underlying function object (`meth.im_func`),
setting method attributes on either bound or unbound methods is
disallowed. Attempting to set a method attribute results in a
`TypeError` being raised. In order to set a method attribute,
you need to explicitly set it on the underlying function object:
```text

class C:
def method(self):
pass

c = C()
c.method.im_func.whoami = 'my name is c'
```
See the Python Reference Manual (../ref/ref.html) for more
information.


2.2.9.1 Modules

typesother.html | typesother.html | typesobjects.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
2.2.9 Other Built-in Types (typesother.html)
Up:
2.2.9 Other Built-in Types (typesother.html)
Next:
2.2.9.2 Classes and Class (typesobjects.html)
---
### 2.2.9.1 Modules
The only special operation on a module is attribute access:
`m . name`, where m is a module and name
accesses a name defined in m's symbol table. Module attributes
can be assigned to. (Note that the import statement is not,
strictly speaking, an operation on a module object; `import foo` does not require a module object named foo to exist,
rather it requires an (external) definition for a module named
foo somewhere.)
A special member of every module is __dict__.
This is the dictionary containing the module's symbol table.
Modifying this dictionary will actually change the module's symbol
table, but direct assignment to the __dict__ attribute is not
possible (you can write `m .__dict__['a'] = 1`, which
defines `m .a` to be `1`, but you can't write
`m .__dict__ = {}`).
Modules built into the interpreter are written like this:
`<module 'sys' (built-in)>`. If loaded from a file, they are
written as `<module 'os' from
'/usr/local/lib/python2.3/os.pyc'>`.


2.2.4 Numeric Types

comparisons.html | types.html | bitstring-ops.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
2.2.3 Comparisons (comparisons.html)
Up:
2.2 Built-in Types (types.html)
Next:
2.2.4.1 Bit-string Operations on (bitstring-ops.html)
---
## 2.2.4 Numeric Types
There are four distinct numeric types: plain integers,
long integers,
floating point numbers, and complex numbers.
In addition, Booleans are a subtype of plain integers.
Plain integers (also just called integers)
are implemented using long in C, which gives them at least 32
bits of precision. Long integers have unlimited precision. Floating
point numbers are implemented using double in C. All bets on
their precision are off unless you happen to know the machine you are
working with.
Complex numbers have a real and imaginary part, which are each
implemented using double in C. To extract these parts from
a complex number z, use `z .real` and `z .imag`.
Numbers are created by numeric literals or as the result of built-in
functions and operators. Unadorned integer literals (including hex
and octal numbers) yield plain integers unless the value they denote
is too large to be represented as a plain integer, in which case
they yield a long integer. Integer literals with an
"L" or "l" suffix yield long integers
("L" is preferred because "1l" looks too much like
eleven!). Numeric literals containing a decimal point or an exponent
sign yield floating point numbers. Appending "j" or
"J" to a numeric literal yields a complex number with a
zero real part. A complex numeric literal is the sum of a real and
an imaginary part.
Python fully supports mixed arithmetic: when a binary arithmetic
operator has operands of different numeric types, the operand with the
``narrower'' type is widened to that of the other, where plain
integer is narrower than long integer is narrower than floating point is
narrower than complex.
Comparisons between numbers of mixed type use the same rule.2.6 (#foot3022) The constructors int(), long(), float(),
and complex() can be used
to produce numbers of a specific type.
All numeric types (except complex) support the following operations,
sorted by ascending priority (operations in the same box have the same
priority; all numeric operations have a higher priority than
comparison operations):
Notes:
(1): For (plain or long) integer division, the result is an integer.
The result is always rounded towards minus infinity: 1/2 is 0,
(-1)/2 is -1, 1/(-2) is -1, and (-1)/(-2) is 0. Note that the result
is a long integer if either operand is a long integer, regardless of
the numeric value.
(2): Conversion from floating point to (long or plain) integer may round or
truncate as in C; see functions floor() and
ceil() in the math (module-math.html)module
for well-defined conversions.
(3): See section 2.1 (built-in-funcs.html#built-in-funcs), ``Built-in Functions,'' for a full
description.
(4): Complex floor division operator, modulo operator, and divmod().
Deprecated since release 2.3.
Instead convert to float using abs()
if appropriate.
---
#### Footnotes
... rule.2.6 (typesnumeric.html#tex2html7): As a consequence, the list `[1, 2]` is considered equal
to `[1.0, 2.0]`, and similarly for tuples.


2.2.9.2 Classes and Class Instances

typesmodules.html | typesother.html | typesfunctions.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
2.2.9.1 Modules (typesmodules.html)
Up:
2.2.9 Other Built-in Types (typesother.html)
Next:
2.2.9.3 Functions (typesfunctions.html)
---
### 2.2.9.2 Classes and Class Instances
See chapters 3 and 7 of the Python
Reference Manual (../ref/ref.html) for these.


2.2.9 Other Built-in Types

bltin-file-objects.html | types.html | typesmodules.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
2.2.8 File Objects (bltin-file-objects.html)
Up:
2.2 Built-in Types (types.html)
Next:
2.2.9.1 Modules (typesmodules.html)
---
## 2.2.9 Other Built-in Types
The interpreter supports several other kinds of objects.
Most of these support only one or two operations.


2.2.6.4 Mutable Sequence Types

typesseq-xrange.html | typesseq.html | typesmapping.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
2.2.6.3 XRange Type (typesseq-xrange.html)
Up:
2.2.6 Sequence Types (typesseq.html)
Next:
2.2.7 Mapping Types (typesmapping.html)
---
### 2.2.6.4 Mutable Sequence Types
List objects support additional operations that allow in-place
modification of the object.
Other mutable sequence types (when added to the language) should
also support these operations.
Strings and tuples are immutable sequence types: such objects cannot
be modified once created.
The following operations are defined on mutable sequence types (where
x is an arbitrary object):
Notes:
(1): t must have the same length as the slice it is
replacing.
(2): The C implementation of Python has historically accepted
multiple parameters and implicitly joined them into a tuple; this
no longer works in Python 2.0. Use of this misfeature has been
deprecated since Python 1.4.
(3): Raises an exception when x is not a list object. The
extend() method is experimental and not supported by
mutable sequence types other than lists.
(4): Raises ValueError when x is not found in
s. When a negative index is passed as the second or third parameter
to the index() method, the list length is added, as for slice
indices. If it is still negative, it is truncated to zero, as for
slice indices.
Changed in version 2.3:
Previously, index() didn't
have arguments for specifying start and stop positions.
(5): When a negative index is passed as the first parameter to
the insert() method, the list length is added, as for slice
indices. If it is still negative, it is truncated to zero, as for
slice indices.
Changed in version 2.3:
Previously, all negative indices
were truncated to zero.
(6): The pop() method is only supported by the list and
array types. The optional argument i defaults to `-1`,
so that by default the last item is removed and returned.
(7): The sort() and reverse() methods modify the
list in place for economy of space when sorting or reversing a large
list. To remind you that they operate by side effect, they don't return
the sorted or reversed list.
(8): The sort() method takes an optional argument
specifying a comparison function of two arguments (list items) which
should return a negative, zero or positive number depending on whether
the first argument is considered smaller than, equal to, or larger
than the second argument. Note that this slows the sorting process
down considerably; for example to sort a list in reverse order it is much
faster to call sort() followed by reverse()
than to use sort() with a comparison function that
reverses the ordering of the elements. Passing None as the
comparison function is semantically equivalent to calling
sort() with no comparison function.
Changed in version 2.3:
Support for `None` as an equivalent to omitting
cmpfunc was added.
As an example of using the cmpfunc argument to the
sort() method, consider sorting a list of sequences by the
second element of that list:
```text

def mycmp(a, b):
return cmp(a[1], b[1])

mylist.sort(mycmp)
```
A more time-efficient approach for reasonably-sized data structures can
often be used:
```text

tmplist = [(x[1], x) for x in mylist]
tmplist.sort()
mylist = [x for (key, x) in tmplist]
```
(9): Whether the sort() method is stable is not defined by
the language (a sort is stable if it guarantees not to change the
relative order of elements that compare equal). In the C
implementation of Python, sorts were stable only by accident through
Python 2.2. The C implementation of Python 2.3 introduced a stable
sort() method, but code that intends to be portable across
implementations and versions must not rely on stability.
(10): While a list is being sorted, the effect of attempting to
mutate, or even inspect, the list is undefined. The C implementation
of Python 2.3 makes the list appear empty for the duration, and raises
ValueError if it can detect that the list has been
mutated during a sort.


2.2.6.2 String Formatting Operations

string-methods.html | typesseq.html | typesseq-xrange.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
2.2.6.1 String Methods (string-methods.html)
Up:
2.2.6 Sequence Types (typesseq.html)
Next:
2.2.6.3 XRange Type (typesseq-xrange.html)
---
### 2.2.6.2 String Formatting Operations
String and Unicode objects have one unique built-in operation: the
`%` operator (modulo). This is also known as the string
formatting or interpolation operator. Given
`format % values` (where format is a string or
Unicode object), `%` conversion specifications in format
are replaced with zero or more elements of values. The effect
is similar to the using sprintf() in the C language. If
format is a Unicode object, or if any of the objects being
converted using the `%s` conversion are Unicode objects, the
result will also be a Unicode object.
If format requires a single argument, values may be a
single non-tuple object. 2.8 (#foot2196) Otherwise, values must be a tuple with
exactly the number of items specified by the format string, or a
single mapping object (for example, a dictionary).
A conversion specifier contains two or more characters and has the
following components, which must occur in this order:
1. The "%" character, which marks the start of the
specifier.
2. Mapping key (optional), consisting of a parenthesised sequence
of characters (for example, `(somename)`).
3. Conversion flags (optional), which affect the result of some
conversion types.
4. Minimum field width (optional). If specified as an
"*" (asterisk), the actual width is read from the
next element of the tuple in values, and the object to
convert comes after the minimum field width and optional
precision.
5. Precision (optional), given as a "." (dot) followed
by the precision. If specified as "*" (an
asterisk), the actual width is read from the next element of
the tuple in values, and the value to convert comes after
the precision.
6. Length modifier (optional).
7. Conversion type.
When the right argument is a dictionary (or other mapping type), then
the formats in the string must include a parenthesised mapping key into
that dictionary inserted immediately after the "%"
character. The mapping key selects the value to be formatted from the
mapping. For example:
```text

>>> print '%(language)s has %(#)03d quote types.' % \
{'language': "Python", "#": 2}
Python has 002 quote types.
```
In this case no `*` specifiers may occur in a format (since they
require a sequential parameter list).
The conversion flag characters are:
The length modifier may be `h`, `l`, and `L` may be
present, but are ignored as they are not necessary for Python.
The conversion types are:
Notes:
(1): The alternate form causes a leading zero ("0") to be
inserted between left-hand padding and the formatting of the
number if the leading character of the result is not already a
zero.
(2): The alternate form causes a leading `'0x'` or `'0X'`
(depending on whether the "x" or "X" format
was used) to be inserted between left-hand padding and the
formatting of the number if the leading character of the result is
not already a zero.
(3): The `%r` conversion was added in Python 2.0.
(4): If the object or format provided is a unicode string,
the resulting string will also be unicode.
Since Python strings have an explicit length, `%s` conversions
do not assume that `'\0'` is the end of the string.
For safety reasons, floating point precisions are clipped to 50;
`%f` conversions for numbers whose absolute value is over 1e25
are replaced by `%g` conversions.2.9 (#foot2303) All other errors raise exceptions.
Additional string operations are defined in standard modules
string (module-string.html)and
re (module-re.html).


2.2.6.3 XRange Type

typesseq-strings.html | typesseq.html | typesseq-mutable.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
2.2.6.2 String Formatting Operations (typesseq-strings.html)
Up:
2.2.6 Sequence Types (typesseq.html)
Next:
2.2.6.4 Mutable Sequence Types (typesseq-mutable.html)
---
### 2.2.6.3 XRange Type
The xrange type is an immutable sequence which is
commonly used for looping. The advantage of the xrange type is that an
xrange object will always take the same amount of memory, no matter the
size of the range it represents. There are no consistent performance
advantages.
XRange objects have very little behavior: they only support indexing,
iteration, and the len() function.