Branch merge

This commit is contained in:
Éric Araujo 2011-08-19 02:26:44 +02:00
commit cdb86f17bf
111 changed files with 1237 additions and 325 deletions

View File

@ -58,11 +58,14 @@ Glossary
bytecode
Python source code is compiled into bytecode, the internal representation
of a Python program in the interpreter. The bytecode is also cached in
``.pyc`` and ``.pyo`` files so that executing the same file is faster the
second time (recompilation from source to bytecode can be avoided). This
"intermediate language" is said to run on a :term:`virtual machine`
that executes the machine code corresponding to each bytecode.
of a Python program in the CPython interpreter. The bytecode is also
cached in ``.pyc`` and ``.pyo`` files so that executing the same file is
faster the second time (recompilation from source to bytecode can be
avoided). This "intermediate language" is said to run on a
:term:`virtual machine` that executes the machine code corresponding to
each bytecode. Do note that bytecodes are not expected to work between
different Python virtual machines, nor to be stable between Python
releases.
A list of bytecode instructions can be found in the documentation for
:ref:`the dis module <bytecodes>`.
@ -128,8 +131,9 @@ Glossary
def f(...):
...
See :ref:`the documentation for function definition <function>` for more
about decorators.
The same concept exists for classes, but is less commonly used there. See
the documentation for :ref:`function definitions <function>` and
:ref:`class definitions <class>` for more about decorators.
descriptor
Any *new-style* object which defines the methods :meth:`__get__`,
@ -165,8 +169,8 @@ Glossary
well-designed code improves its flexibility by allowing polymorphic
substitution. Duck-typing avoids tests using :func:`type` or
:func:`isinstance`. (Note, however, that duck-typing can be complemented
with :term:`abstract base class`\ es.) Instead, it typically employs
:func:`hasattr` tests or :term:`EAFP` programming.
with :term:`abstract base classes <abstract base class>`.) Instead, it
typically employs :func:`hasattr` tests or :term:`EAFP` programming.
EAFP
Easier to ask for forgiveness than permission. This common Python coding
@ -178,17 +182,34 @@ Glossary
expression
A piece of syntax which can be evaluated to some value. In other words,
an expression is an accumulation of expression elements like literals, names,
attribute access, operators or function calls which all return a value.
In contrast to many other languages, not all language constructs are expressions.
There are also :term:`statement`\s which cannot be used as expressions,
such as :keyword:`print` or :keyword:`if`. Assignments are also statements,
not expressions.
an expression is an accumulation of expression elements like literals,
names, attribute access, operators or function calls which all return a
value. In contrast to many other languages, not all language constructs
are expressions. There are also :term:`statement`\s which cannot be used
as expressions, such as :keyword:`print` or :keyword:`if`. Assignments
are also statements, not expressions.
extension module
A module written in C or C++, using Python's C API to interact with the
core and with user code.
file object
An object exposing a file-oriented API (with methods such as
:meth:`read()` or :meth:`write()`) to an underlying resource. Depending
on the way it was created, a file object can mediate access to a real
on-disk file or to another other type of storage or communication device
(for example standard input/output, in-memory buffers, sockets, pipes,
etc.). File objects are also called :dfn:`file-like objects` or
:dfn:`streams`.
There are actually three categories of file objects: raw binary files,
buffered binary files and text files. Their interfaces are defined in the
:mod:`io` module. The canonical way to create a file object is by using
the :func:`open` function.
file-like object
A synonym for :term:`file object`.
finder
An object that tries to find the :term:`loader` for a module. It must
implement a method named :meth:`find_module`. See :pep:`302` for
@ -335,7 +356,7 @@ Glossary
slowly. See also :term:`interactive`.
iterable
A container object capable of returning its members one at a
An object capable of returning its members one at a
time. Examples of iterables include all sequence types (such as
:class:`list`, :class:`str`, and :class:`tuple`) and some non-sequence
types like :class:`dict` and :class:`file` and objects of any classes you
@ -404,6 +425,12 @@ Glossary
the :term:`EAFP` approach and is characterized by the presence of many
:keyword:`if` statements.
In a multi-threaded environment, the LBYL approach can risk introducing a
race condition between "the looking" and "the leaping". For example, the
code, ``if key in mapping: return mapping[key]`` can fail if another
thread removes *key* from *mapping* after the test, but before the lookup.
This issue can be solved with locks or by using the EAFP approach.
list
A built-in Python :term:`sequence`. Despite its name it is more akin
to an array in other languages than to a linked list since access to
@ -424,7 +451,8 @@ Glossary
mapping
A container object that supports arbitrary key lookups and implements the
methods specified in the :class:`Mapping` or :class:`MutableMapping`
methods specified in the :class:`~collections.Mapping` or
:class:`~collections.MutableMapping`
:ref:`abstract base classes <collections-abstract-base-classes>`. Examples
include :class:`dict`, :class:`collections.defaultdict`,
:class:`collections.OrderedDict` and :class:`collections.Counter`.
@ -448,6 +476,14 @@ Glossary
its first :term:`argument` (which is usually called ``self``).
See :term:`function` and :term:`nested scope`.
method resolution order
Method Resolution Order is the order in which base classes are searched
for a member during lookup. See `The Python 2.3 Method Resolution Order
<http://www.python.org/download/releases/2.3/mro/>`_.
MRO
See :term:`method resolution order`.
mutable
Mutable objects can change their value but keep their :func:`id`. See
also :term:`immutable`.
@ -480,10 +516,11 @@ Glossary
nested scope
The ability to refer to a variable in an enclosing definition. For
instance, a function defined inside another function can refer to
variables in the outer function. Note that nested scopes work only for
reference and not for assignment which will always write to the innermost
scope. In contrast, local variables both read and write in the innermost
scope. Likewise, global variables read and write to the global namespace.
variables in the outer function. Note that nested scopes by default work
only for reference and not for assignment. Local variables both read and
write in the innermost scope. Likewise, global variables read and write
to the global namespace. The :keyword:`nonlocal` allows writing to outer
scopes.
new-style class
Any class which inherits from :class:`object`. This includes all built-in
@ -506,9 +543,9 @@ Glossary
:term:`argument`.
Python 3000
Nickname for the next major Python version, 3.0 (coined long ago
when the release of version 3 was something in the distant future.) This
is also abbreviated "Py3k".
Nickname for the Python 3.x release line (coined long ago when the release
of version 3 was something in the distant future.) This is also
abbreviated "Py3k".
Pythonic
An idea or piece of code which closely follows the most common idioms
@ -531,7 +568,7 @@ Glossary
object drops to zero, it is deallocated. Reference counting is
generally not visible to Python code, but it is a key element of the
:term:`CPython` implementation. The :mod:`sys` module defines a
:func:`getrefcount` function that programmers can call to return the
:func:`~sys.getrefcount` function that programmers can call to return the
reference count for a particular object.
__slots__
@ -567,7 +604,15 @@ Glossary
statement
A statement is part of a suite (a "block" of code). A statement is either
an :term:`expression` or a one of several constructs with a keyword, such
as :keyword:`if`, :keyword:`while` or :keyword:`print`.
as :keyword:`if`, :keyword:`while` or :keyword:`for`.
struct sequence
A tuple with named elements. Struct sequences expose an interface similiar
to :term:`named tuple` in that elements can either be accessed either by
index or as an attribute. However, they do not have any of the named tuple
methods like :meth:`~collections.somenamedtuple._make` or
:meth:`~collections.somenamedtuple._asdict`. Examples of struct sequences
include :data:`sys.float_info` and the return value of :func:`os.stat`.
triple-quoted string
A string which is bound by three instances of either a quotation mark

View File

@ -1,5 +1,7 @@
.. highlightlang:: c
.. _cporting-howto:
********************************
Porting Extension Modules to 3.0
********************************

View File

@ -14,6 +14,7 @@ Currently, the HOWTOs are:
:maxdepth: 1
advocacy.rst
pyporting.rst
cporting.rst
curses.rst
descriptor.rst

703
Doc/howto/pyporting.rst Normal file
View File

@ -0,0 +1,703 @@
.. _pyporting-howto:
*********************************
Porting Python 2 Code to Python 3
*********************************
:author: Brett Cannon
.. topic:: Abstract
With Python 3 being the future of Python while Python 2 is still in active
use, it is good to have your project available for both major releases of
Python. This guide is meant to help you choose which strategy works best
for your project to support both Python 2 & 3 along with how to execute
that strategy.
If you are looking to port an extension module instead of pure Python code,
please see :ref:`cporting-howto`.
Choosing a Strategy
===================
When a project makes the decision that it's time to support both Python 2 & 3,
a decision needs to be made as to how to go about accomplishing that goal.
The chosen strategy will depend on how large the project's existing
codebase is and how much divergence you want from your Python 2 codebase from
your Python 3 one (e.g., starting a new version with Python 3).
If your project is brand-new or does not have a large codebase, then you may
want to consider writing/porting :ref:`all of your code for Python 3
and use 3to2 <use_3to2>` to port your code for Python 2.
If you would prefer to maintain a codebase which is semantically **and**
syntactically compatible with Python 2 & 3 simultaneously, you can write
:ref:`use_same_source`. While this tends to lead to somewhat non-idiomatic
code, it does mean you keep a rapid development process for you, the developer.
Finally, you do have the option of :ref:`using 2to3 <use_2to3>` to translate
Python 2 code into Python 3 code (with some manual help). This can take the
form of branching your code and using 2to3 to start a Python 3 branch. You can
also have users perform the translation as installation time automatically so
that you only have to maintain a Python 2 codebase.
Regardless of which approach you choose, porting is not as hard or
time-consuming as you might initially think. You can also tackle the problem
piece-meal as a good portion of porting is simply updating your code to follow
current best practices in a Python 2/3 compatible way.
Universal Bits of Advice
------------------------
Regardless of what strategy you pick, there are a few things you should
consider.
One is make sure you have a robust test suite. You need to make sure everything
continues to work, just like when you support a new minor version of Python.
This means making sure your test suite is thorough and is ported properly
between Python 2 & 3. You will also most likely want to use something like tox_
to automate testing between both a Python 2 and Python 3 VM.
Two, once your project has Python 3 support, make sure to add the proper
classifier on the Cheeseshop_ (PyPI_). To have your project listed as Python 3
compatible it must have the
`Python 3 classifier <http://pypi.python.org/pypi?:action=browse&c=533>`_
(from
http://techspot.zzzeek.org/2011/01/24/zzzeek-s-guide-to-python-3-porting/)::
setup(
name='Your Library',
version='1.0',
classifiers=[
# make sure to use :: Python *and* :: Python :: 3 so
# that pypi can list the package on the python 3 page
'Programming Language :: Python',
'Programming Language :: Python :: 3'
],
packages=['yourlibrary'],
# make sure to add custom_fixers to the MANIFEST.in
include_package_data=True,
# ...
)
Doing so will cause your project to show up in the
`Python 3 packages list
<http://pypi.python.org/pypi?:action=browse&c=533&show=all>`_. You will know
you set the classifier properly as visiting your project page on the Cheeseshop
will show a Python 3 logo in the upper-left corner of the page.
Three, the six_ project provides a library which helps iron out differences
between Python 2 & 3. If you find there is a sticky point that is a continual
point of contention in your translation or maintenance of code, consider using
a source-compatible solution relying on six. If you have to create your own
Python 2/3 compatible solution, you can use ``sys.version_info[0] >= 3`` as a
guard.
Four, read all the approaches. Just because some bit of advice applies to one
approach more than another doesn't mean that some advice doesn't apply to other
strategies.
Five, drop support for older Python versions if possible. `Python 2.5`_
introduced a lot of useful syntax and libraries which have become idiomatic
in Python 3. `Python 2.6`_ introduced future statements which makes
compatibility much easier if you are going from Python 2 to 3.
`Python 2.7`_ continues the trend in the stdlib. So choose the newest version
of Python which you believe can be your minimum support version
and work from there.
.. _tox: http://codespeak.net/tox/
.. _Cheeseshop:
.. _PyPI: http://pypi.python.org/
.. _six: http://packages.python.org/six
.. _Python 2.7: http://www.python.org/2.7.x
.. _Python 2.6: http://www.python.org/2.6.x
.. _Python 2.5: http://www.python.org/2.5.x
.. _Python 2.4: http://www.python.org/2.4.x
.. _Python 2.3: http://www.python.org/2.3.x
.. _Python 2.2: http://www.python.org/2.2.x
.. _use_3to2:
Python 3 and 3to2
=================
If you are starting a new project or your codebase is small enough, you may
want to consider writing your code for Python 3 and backporting to Python 2
using 3to2_. Thanks to Python 3 being more strict about things than Python 2
(e.g., bytes vs. strings), the source translation can be easier and more
straightforward than from Python 2 to 3. Plus it gives you more direct
experience developing in Python 3 which, since it is the future of Python, is a
good thing long-term.
A drawback of this approach is that 3to2 is a third-party project. This means
that the Python core developers (and thus this guide) can make no promises
about how well 3to2 works at any time. There is nothing to suggest, though,
that 3to2 is not a high-quality project.
.. _3to2: https://bitbucket.org/amentajo/lib3to2/overview
.. _use_2to3:
Python 2 and 2to3
=================
Included with Python since 2.6, the 2to3_ tool (and :mod:`lib2to3` module)
helps with porting Python 2 to Python 3 by performing various source
translations. This is a perfect solution for projects which wish to branch
their Python 3 code from their Python 2 codebase and maintain them as
independent codebases. You can even begin preparing to use this approach
today by writing future-compatible Python code which works cleanly in
Python 2 in conjunction with 2to3; all steps outlined below will work
with Python 2 code up to the point when the actual use of 2to3 occurs.
Use of 2to3 as an on-demand translation step at install time is also possible,
preventing the need to maintain a separate Python 3 codebase, but this approach
does come with some drawbacks. While users will only have to pay the
translation cost once at installation, you as a developer will need to pay the
cost regularly during development. If your codebase is sufficiently large
enough then the translation step ends up acting like a compilation step,
robbing you of the rapid development process you are used to with Python.
Obviously the time required to translate a project will vary, so do an
experimental translation just to see how long it takes to evaluate whether you
prefer this approach compared to using :ref:`use_same_source` or simply keeping
a separate Python 3 codebase.
Below are the typical steps taken by a project which uses a 2to3-based approach
to supporting Python 2 & 3.
Support Python 2.7
------------------
As a first step, make sure that your project is compatible with `Python 2.7`_.
This is just good to do as Python 2.7 is the last release of Python 2 and thus
will be used for a rather long time. It also allows for use of the ``-3`` flag
to Python to help discover places in your code which 2to3 cannot handle but are
known to cause issues.
Try to Support `Python 2.6`_ and Newer Only
-------------------------------------------
While not possible for all projects, if you can support `Python 2.6`_ and newer
**only**, your life will be much easier. Various future statements, stdlib
additions, etc. exist only in Python 2.6 and later which greatly assist in
porting to Python 3. But if you project must keep support for `Python 2.5`_ (or
even `Python 2.4`_) then it is still possible to port to Python 3.
Below are the benefits you gain if you only have to support Python 2.6 and
newer. Some of these options are personal choice while others are
**strongly** recommended (the ones that are more for personal choice are
labeled as such). If you continue to support older versions of Python then you
at least need to watch out for situations that these solutions fix.
``from __future__ import print_function``
'''''''''''''''''''''''''''''''''''''''''
This is a personal choice. 2to3 handles the translation from the print
statement to the print function rather well so this is an optional step. This
future statement does help, though, with getting used to typing
``print('Hello, World')`` instead of ``print 'Hello, World'``.
``from __future__ import unicode_literals``
'''''''''''''''''''''''''''''''''''''''''''
Another personal choice. You can always mark what you want to be a (unicode)
string with a ``u`` prefix to get the same effect. But regardless of whether
you use this future statement or not, you **must** make sure you know exactly
which Python 2 strings you want to be bytes, and which are to be strings. This
means you should, **at minimum** mark all strings that are meant to be text
strings with a ``u`` prefix if you do not use this future statement.
Bytes literals
''''''''''''''
This is a **very** important one. The ability to prefix Python 2 strings that
are meant to contain bytes with a ``b`` prefix help to very clearly delineate
what is and is not a Python 3 string. When you run 2to3 on code, all Python 2
strings become Python 3 strings **unless** they are prefixed with ``b``.
There are some differences between byte literals in Python 2 and those in
Python 3 thanks to the bytes type just being an alias to ``str`` in Python 2.
Probably the biggest "gotcha" is that indexing results in different values. In
Python 2, the value of ``b'py'[1]`` is ``'y'``, while in Python 3 it's ``121``.
You can avoid this disparity by always slicing at the size of a single element:
``b'py'[1:2]`` is ``'y'`` in Python 2 and ``b'y'`` in Python 3 (i.e., close
enough).
You cannot concatenate bytes and strings in Python 3. But since in Python
2 has bytes aliased to ``str``, it will succeed: ``b'a' + u'b'`` works in
Python 2, but ``b'a' + 'b'`` in Python 3 is a :exc:`TypeError`. A similar issue
also comes about when doing comparisons between bytes and strings.
Supporting `Python 2.5`_ and Newer Only
---------------------------------------
If you are supporting `Python 2.5`_ and newer there are still some features of
Python that you can utilize.
``from __future__ import absolute_import``
''''''''''''''''''''''''''''''''''''''''''
Implicit relative imports (e.g., importing ``spam.bacon`` from within
``spam.eggs`` with the statement ``import bacon``) does not work in Python 3.
This future statement moves away from that and allows the use of explicit
relative imports (e.g., ``from . import bacon``).
In `Python 2.5`_ you must use
the __future__ statement to get to use explicit relative imports and prevent
implicit ones. In `Python 2.6`_ explicit relative imports are available without
the statement, but you still want the __future__ statement to prevent implicit
relative imports. In `Python 2.7`_ the __future__ statement is not needed. In
other words, unless you are only supporting Python 2.7 or a version earlier
than Python 2.5, use the __future__ statement.
Handle Common "Gotchas"
-----------------------
There are a few things that just consistently come up as sticking points for
people which 2to3 cannot handle automatically or can easily be done in Python 2
to help modernize your code.
``from __future__ import division``
'''''''''''''''''''''''''''''''''''
While the exact same outcome can be had by using the ``-Qnew`` argument to
Python, using this future statement lifts the requirement that your users use
the flag to get the expected behavior of division in Python 3
(e.g., ``1/2 == 0.5; 1//2 == 0``).
Specify when opening a file as binary
'''''''''''''''''''''''''''''''''''''
Unless you have been working on Windows, there is a chance you have not always
bothered to add the ``b`` mode when opening a binary file (e.g., ``rb`` for
binary reading). Under Python 3, binary files and text files are clearly
distinct and mutually incompatible; see the :mod:`io` module for details.
Therefore, you **must** make a decision of whether a file will be used for
binary access (allowing to read and/or write bytes data) or text access
(allowing to read and/or write unicode data).
Text files
''''''''''
Text files created using ``open()`` under Python 2 return byte strings,
while under Python 3 they return unicode strings. Depending on your porting
strategy, this can be an issue.
If you want text files to return unicode strings in Python 2, you have two
possibilities:
* Under Python 2.6 and higher, use :func:`io.open`. Since :func:`io.open`
is essentially the same function in both Python 2 and Python 3, it will
help iron out any issues that might arise.
* If pre-2.6 compatibility is needed, then you should use :func:`codecs.open`
instead. This will make sure that you get back unicode strings in Python 2.
Subclass ``object``
'''''''''''''''''''
New-style classes have been around since `Python 2.2`_. You need to make sure
you are subclassing from ``object`` to avoid odd edge cases involving method
resolution order, etc. This continues to be totally valid in Python 3 (although
unneeded as all classes implicitly inherit from ``object``).
Deal With the Bytes/String Dichotomy
''''''''''''''''''''''''''''''''''''
One of the biggest issues people have when porting code to Python 3 is handling
the bytes/string dichotomy. Because Python 2 allowed the ``str`` type to hold
textual data, people have over the years been rather loose in their delineation
of what ``str`` instances held text compared to bytes. In Python 3 you cannot
be so care-free anymore and need to properly handle the difference. The key
handling this issue to to make sure that **every** string literal in your
Python 2 code is either syntactically of functionally marked as either bytes or
text data. After this is done you then need to make sure your APIs are designed
to either handle a specific type or made to be properly polymorphic.
Mark Up Python 2 String Literals
********************************
First thing you must do is designate every single string literal in Python 2
as either textual or bytes data. If you are only supporting Python 2.6 or
newer, this can be accomplished by marking bytes literals with a ``b`` prefix
and then designating textual data with a ``u`` prefix or using the
``unicode_literals`` future statement.
If your project supports versions of Python pre-dating 2.6, then you should use
the six_ project and its ``b()`` function to denote bytes literals. For text
literals you can either use six's ``u()`` function or use a ``u`` prefix.
Decide what APIs Will Accept
****************************
In Python 2 it was very easy to accidentally create an API that accepted both
bytes and textual data. But in Python 3, thanks to the more strict handling of
disparate types, this loose usage of bytes and text together tends to fail.
Take the dict ``{b'a': 'bytes', u'a': 'text'}`` in Python 2.6. It creates the
dict ``{u'a': 'text'}`` since ``b'a' == u'a'``. But in Python 3 the equivalent
dict creates ``{b'a': 'bytes', 'a': 'text'}``, i.e., no lost data. Similar
issues can crop up when transitioning Python 2 code to Python 3.
This means you need to choose what an API is going to accept and create and
consistently stick to that API in both Python 2 and 3.
Bytes / Unicode Comparison
**************************
In Python 3, mixing bytes and unicode is forbidden in most situations; it
will raise a :class:`TypeError` where Python 2 would have attempted an implicit
coercion between types. However, there is one case where it doesn't and
it can be very misleading::
>>> b"" == ""
False
This is because an equality comparison is required by the language to always
succeed (and return ``False`` for incompatible types). However, this also
means that code incorrectly ported to Python 3 can display buggy behaviour
if such comparisons are silently executed. To detect such situations,
Python 3 has a ``-b`` flag that will display a warning::
$ python3 -b
>>> b"" == ""
__main__:1: BytesWarning: Comparison between bytes and string
False
To turn the warning into an exception, use the ``-bb`` flag instead::
$ python3 -bb
>>> b"" == ""
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
BytesWarning: Comparison between bytes and string
Indexing bytes objects
''''''''''''''''''''''
Another potentially surprising change is the indexing behaviour of bytes
objects in Python 3::
>>> b"xyz"[0]
120
Indeed, Python 3 bytes objects (as well as :class:`bytearray` objects)
are sequences of integers. But code converted from Python 2 will often
assume that indexing a bytestring produces another bytestring, not an
integer. To reconcile both behaviours, use slicing::
>>> b"xyz"[0:1]
b'x'
>>> n = 1
>>> b"xyz"[n:n+1]
b'y'
The only remaining gotcha is that an out-of-bounds slice returns an empty
bytes object instead of raising ``IndexError``:
>>> b"xyz"[3]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: index out of range
>>> b"xyz"[3:4]
b''
``__str__()``/``__unicode__()``
'''''''''''''''''''''''''''''''
In Python 2, objects can specify both a string and unicode representation of
themselves. In Python 3, though, there is only a string representation. This
becomes an issue as people can inadvertently do things in their ``__str__()``
methods which have unpredictable results (e.g., infinite recursion if you
happen to use the ``unicode(self).encode('utf8')`` idiom as the body of your
``__str__()`` method).
There are two ways to solve this issue. One is to use a custom 2to3 fixer. The
blog post at http://lucumr.pocoo.org/2011/1/22/forwards-compatible-python/
specifies how to do this. That will allow 2to3 to change all instances of ``def
__unicode(self): ...`` to ``def __str__(self): ...``. This does require you
define your ``__str__()`` method in Python 2 before your ``__unicode__()``
method.
The other option is to use a mixin class. This allows you to only define a
``__unicode__()`` method for your class and let the mixin derive
``__str__()`` for you (code from
http://lucumr.pocoo.org/2011/1/22/forwards-compatible-python/)::
import sys
class UnicodeMixin(object):
"""Mixin class to handle defining the proper __str__/__unicode__
methods in Python 2 or 3."""
if sys.version_info[0] >= 3: # Python 3
def __str__(self):
return self.__unicode__()
else: # Python 2
def __str__(self):
return self.__unicode__().encode('utf8')
class Spam(UnicodeMixin):
def __unicode__(self):
return u'spam-spam-bacon-spam' # 2to3 will remove the 'u' prefix
Don't Index on Exceptions
'''''''''''''''''''''''''
In Python 2, the following worked::
>>> exc = Exception(1, 2, 3)
>>> exc.args[1]
2
>>> exc[1] # Python 2 only!
2
But in Python 3, indexing directly on an exception is an error. You need to
make sure to only index on the :attr:`BaseException.args` attribute which is a
sequence containing all arguments passed to the :meth:`__init__` method.
Even better is to use the documented attributes the exception provides.
Don't use ``__getslice__`` & Friends
''''''''''''''''''''''''''''''''''''
Been deprecated for a while, but Python 3 finally drops support for
``__getslice__()``, etc. Move completely over to :meth:`__getitem__` and
friends.
Updating doctests
'''''''''''''''''
2to3_ will attempt to generate fixes for doctests that it comes across. It's
not perfect, though. If you wrote a monolithic set of doctests (e.g., a single
docstring containing all of your doctests), you should at least consider
breaking the doctests up into smaller pieces to make it more manageable to fix.
Otherwise it might very well be worth your time and effort to port your tests
to :mod:`unittest`.
Eliminate ``-3`` Warnings
-------------------------
When you run your application's test suite, run it using the ``-3`` flag passed
to Python. This will cause various warnings to be raised during execution about
things that 2to3 cannot handle automatically (e.g., modules that have been
removed). Try to eliminate those warnings to make your code even more portable
to Python 3.
Run 2to3
--------
Once you have made your Python 2 code future-compatible with Python 3, it's
time to use 2to3_ to actually port your code.
Manually
''''''''
To manually convert source code using 2to3_, you use the ``2to3`` script that
is installed with Python 2.6 and later.::
2to3 <directory or file to convert>
This will cause 2to3 to write out a diff with all of the fixers applied for the
converted source code. If you would like 2to3 to go ahead and apply the changes
you can pass it the ``-w`` flag::
2to3 -w <stuff to convert>
There are other flags available to control exactly which fixers are applied,
etc.
During Installation
'''''''''''''''''''
When a user installs your project for Python 3, you can have either
:mod:`distutils` or Distribute_ run 2to3_ on your behalf.
For distutils, use the following idiom::
try: # Python 3
from distutils.command.build_py import build_py_2to3 as build_py
except ImportError: # Python 2
from distutils.command.build_py import build_py
setup(cmdclass = {'build_py': build_py},
# ...
)
For Distribute::
setup(use_2to3=True,
# ...
)
This will allow you to not have to distribute a separate Python 3 version of
your project. It does require, though, that when you perform development that
you at least build your project and use the built Python 3 source for testing.
Verify & Test
-------------
At this point you should (hopefully) have your project converted in such a way
that it works in Python 3. Verify it by running your unit tests and making sure
nothing has gone awry. If you miss something then figure out how to fix it in
Python 3, backport to your Python 2 code, and run your code through 2to3 again
to verify the fix transforms properly.
.. _2to3: http://docs.python.org/py3k/library/2to3.html
.. _Distribute: http://packages.python.org/distribute/
.. _use_same_source:
Python 2/3 Compatible Source
============================
While it may seem counter-intuitive, you can write Python code which is
source-compatible between Python 2 & 3. It does lead to code that is not
entirely idiomatic Python (e.g., having to extract the currently raised
exception from ``sys.exc_info()[1]``), but it can be run under Python 2
**and** Python 3 without using 2to3_ as a translation step (although the tool
should be used to help find potential portability problems). This allows you to
continue to have a rapid development process regardless of whether you are
developing under Python 2 or Python 3. Whether this approach or using
:ref:`use_2to3` works best for you will be a per-project decision.
To get a complete idea of what issues you will need to deal with, see the
`What's New in Python 3.0`_. Others have reorganized the data in other formats
such as http://docs.pythonsprints.com/python3_porting/py-porting.html .
The following are some steps to take to try to support both Python 2 & 3 from
the same source code.
.. _What's New in Python 3.0: http://docs.python.org/release/3.0/whatsnew/3.0.html
Follow The Steps for Using 2to3_
--------------------------------
All of the steps outlined in how to
:ref:`port Python 2 code with 2to3 <use_2to3>` apply
to creating a Python 2/3 codebase. This includes trying only support Python 2.6
or newer (the :mod:`__future__` statements work in Python 3 without issue),
eliminating warnings that are triggered by ``-3``, etc.
You should even consider running 2to3_ over your code (without committing the
changes). This will let you know where potential pain points are within your
code so that you can fix them properly before they become an issue.
Use six_
--------
The six_ project contains many things to help you write portable Python code.
You should make sure to read its documentation from beginning to end and use
any and all features it provides. That way you will minimize any mistakes you
might make in writing cross-version code.
Capturing the Currently Raised Exception
----------------------------------------
One change between Python 2 and 3 that will require changing how you code (if
you support `Python 2.5`_ and earlier) is
accessing the currently raised exception. In Python 2.5 and earlier the syntax
to access the current exception is::
try:
raise Exception()
except Exception, exc:
# Current exception is 'exc'
pass
This syntax changed in Python 3 (and backported to `Python 2.6`_ and later)
to::
try:
raise Exception()
except Exception as exc:
# Current exception is 'exc'
# In Python 3, 'exc' is restricted to the block; Python 2.6 will "leak"
pass
Because of this syntax change you must change to capturing the current
exception to::
try:
raise Exception()
except Exception:
import sys
exc = sys.exc_info()[1]
# Current exception is 'exc'
pass
You can get more information about the raised exception from
:func:`sys.exc_info` than simply the current exception instance, but you most
likely don't need it.
.. note::
In Python 3, the traceback is attached to the exception instance
through the ``__traceback__`` attribute. If the instance is saved in
a local variable that persists outside of the ``except`` block, the
traceback will create a reference cycle with the current frame and its
dictionary of local variables. This will delay reclaiming dead
resources until the next cyclic :term:`garbage collection` pass.
In Python 2, this problem only occurs if you save the traceback itself
(e.g. the third element of the tuple returned by :func:`sys.exc_info`)
in a variable.
Other Resources
===============
The authors of the following blog posts, wiki pages, and books deserve special
thanks for making public their tips for porting Python 2 code to Python 3 (and
thus helping provide information for this document):
* http://python3porting.com/
* http://docs.pythonsprints.com/python3_porting/py-porting.html
* http://techspot.zzzeek.org/2011/01/24/zzzeek-s-guide-to-python-3-porting/
* http://dabeaz.blogspot.com/2011/01/porting-py65-and-my-superboard-to.html
* http://lucumr.pocoo.org/2011/1/22/forwards-compatible-python/
* http://lucumr.pocoo.org/2010/2/11/porting-to-python-3-a-guide/
* http://wiki.python.org/moin/PortingPythonToPy3k
If you feel there is something missing from this document that should be added,
please email the python-porting_ mailing list.
.. _python-porting: http://mail.python.org/mailman/listinfo/python-porting

View File

@ -4,6 +4,9 @@
.. module:: __future__
:synopsis: Future statement definitions
**Source code:** :source:`Lib/__future__.py`
--------------
:mod:`__future__` is a real module, and serves three purposes:

View File

@ -9,6 +9,10 @@
.. versionadded:: 2.6
**Source code:** :source:`Lib/abc.py`
--------------
This module provides the infrastructure for defining :term:`abstract base
classes <abstract base class>` (ABCs) in Python, as outlined in :pep:`3119`; see the PEP for why this
was added to Python. (See also :pep:`3141` and the :mod:`numbers` module

View File

@ -10,6 +10,10 @@
single: AIFF
single: AIFF-C
**Source code:** :source:`Lib/aifc.py`
--------------
This module provides support for reading and writing AIFF and AIFF-C files.
AIFF is Audio Interchange File Format, a format for storing digital audio
samples in a file. AIFF-C is a newer version of the format that includes the

View File

@ -2,11 +2,15 @@
===============================================================================
.. module:: argparse
:synopsis: Command-line option and argument-parsing library.
:synopsis: Command-line option and argument parsing library.
.. moduleauthor:: Steven Bethard <steven.bethard@gmail.com>
.. versionadded:: 2.7
.. sectionauthor:: Steven Bethard <steven.bethard@gmail.com>
.. versionadded:: 2.7
**Source code:** :source:`Lib/argparse.py`
--------------
The :mod:`argparse` module makes it easy to write user-friendly command-line
interfaces. The program defines what arguments it requires, and :mod:`argparse`
@ -103,9 +107,9 @@ or the :func:`max` function if it was not.
Parsing arguments
^^^^^^^^^^^^^^^^^
:class:`ArgumentParser` parses args through the
:class:`ArgumentParser` parses arguments through the
:meth:`~ArgumentParser.parse_args` method. This will inspect the command line,
convert each arg to the appropriate type and then invoke the appropriate action.
convert each argument to the appropriate type and then invoke the appropriate action.
In most cases, this means a simple :class:`Namespace` object will be built up from
attributes parsed out of the command line::
@ -114,7 +118,7 @@ attributes parsed out of the command line::
In a script, :meth:`~ArgumentParser.parse_args` will typically be called with no
arguments, and the :class:`ArgumentParser` will automatically determine the
command-line args from :data:`sys.argv`.
command-line arguments from :data:`sys.argv`.
ArgumentParser objects
@ -238,7 +242,7 @@ This can be achieved by passing ``False`` as the ``add_help=`` argument to
--foo FOO foo help
The help option is typically ``-h/--help``. The exception to this is
if the ``prefix_chars=`` is specified and does not include ``'-'``, in
if the ``prefix_chars=`` is specified and does not include ``-``, in
which case ``-h`` and ``--help`` are not valid options. In
this case, the first character in ``prefix_chars`` is used to prefix
the help options::
@ -254,7 +258,7 @@ the help options::
prefix_chars
^^^^^^^^^^^^
Most command-line options will use ``'-'`` as the prefix, e.g. ``-f/--foo``.
Most command-line options will use ``-`` as the prefix, e.g. ``-f/--foo``.
Parsers that need to support different or additional prefix
characters, e.g. for options
like ``+f`` or ``/foo``, may specify them using the ``prefix_chars=`` argument
@ -267,7 +271,7 @@ to the ArgumentParser constructor::
Namespace(bar='Y', f='X')
The ``prefix_chars=`` argument defaults to ``'-'``. Supplying a set of
characters that does not include ``'-'`` will cause ``-f/--foo`` options to be
characters that does not include ``-`` will cause ``-f/--foo`` options to be
disallowed.
@ -389,7 +393,7 @@ epilog_ texts in command-line help messages::
likewise for this epilog whose whitespace will be cleaned up and whose words
will be wrapped across a couple lines
Passing :class:`~argparse.RawDescriptionHelpFormatter` as ``formatter_class=``
Passing :class:`RawDescriptionHelpFormatter` as ``formatter_class=``
indicates that description_ and epilog_ are already correctly formatted and
should not be line-wrapped::
@ -415,7 +419,7 @@ should not be line-wrapped::
optional arguments:
-h, --help show this help message and exit
:class:`RawTextHelpFormatter` maintains whitespace for all sorts of help text
:class:`RawTextHelpFormatter` maintains whitespace for all sorts of help text,
including argument descriptions.
The other formatter class available, :class:`ArgumentDefaultsHelpFormatter`,
@ -642,11 +646,11 @@ be positional::
action
^^^^^^
:class:`ArgumentParser` objects associate command-line args with actions. These
actions can do just about anything with the command-line args associated with
:class:`ArgumentParser` objects associate command-line arguments with actions. These
actions can do just about anything with the command-line arguments associated with
them, though most actions simply add an attribute to the object returned by
:meth:`~ArgumentParser.parse_args`. The ``action`` keyword argument specifies
how the command-line args should be handled. The supported actions are:
how the command-line arguments should be handled. The supported actions are:
* ``'store'`` - This just stores the argument's value. This is the default
action. For example::
@ -718,8 +722,8 @@ the Action API. The easiest way to do this is to extend
:meth:`~ArgumentParser.parse_args`. Most actions add an attribute to this
object.
* ``values`` - The associated command-line args, with any type-conversions
applied. (Type-conversions are specified with the type_ keyword argument to
* ``values`` - The associated command-line arguments, with any type conversions
applied. (Type conversions are specified with the type_ keyword argument to
:meth:`~ArgumentParser.add_argument`.
* ``option_string`` - The option string that was used to invoke this action.
@ -751,7 +755,7 @@ single action to be taken. The ``nargs`` keyword argument associates a
different number of command-line arguments with a single action. The supported
values are:
* N (an integer). N args from the command line will be gathered together into a
* ``N`` (an integer). ``N`` arguments from the command line will be gathered together into a
list. For example::
>>> parser = argparse.ArgumentParser()
@ -763,11 +767,11 @@ values are:
Note that ``nargs=1`` produces a list of one item. This is different from
the default, in which the item is produced by itself.
* ``'?'``. One arg will be consumed from the command line if possible, and
produced as a single item. If no command-line arg is present, the value from
* ``'?'``. One argument will be consumed from the command line if possible, and
produced as a single item. If no command-line argument is present, the value from
default_ will be produced. Note that for optional arguments, there is an
additional case - the option string is present but not followed by a
command-line arg. In this case the value from const_ will be produced. Some
command-line argument. In this case the value from const_ will be produced. Some
examples to illustrate this::
>>> parser = argparse.ArgumentParser()
@ -795,7 +799,7 @@ values are:
Namespace(infile=<open file '<stdin>', mode 'r' at 0x...>,
outfile=<open file '<stdout>', mode 'w' at 0x...>)
* ``'*'``. All command-line args present are gathered into a list. Note that
* ``'*'``. All command-line arguments present are gathered into a list. Note that
it generally doesn't make much sense to have more than one positional argument
with ``nargs='*'``, but multiple optional arguments with ``nargs='*'`` is
possible. For example::
@ -809,7 +813,7 @@ values are:
* ``'+'``. Just like ``'*'``, all command-line args present are gathered into a
list. Additionally, an error message will be generated if there wasn't at
least one command-line arg present. For example::
least one command-line argument present. For example::
>>> parser = argparse.ArgumentParser(prog='PROG')
>>> parser.add_argument('foo', nargs='+')
@ -819,8 +823,8 @@ values are:
usage: PROG [-h] foo [foo ...]
PROG: error: too few arguments
If the ``nargs`` keyword argument is not provided, the number of args consumed
is determined by the action_. Generally this means a single command-line arg
If the ``nargs`` keyword argument is not provided, the number of arguments consumed
is determined by the action_. Generally this means a single command-line argument
will be consumed and a single item (not a list) will be produced.
@ -837,9 +841,9 @@ the various :class:`ArgumentParser` actions. The two most common uses of it are
* When :meth:`~ArgumentParser.add_argument` is called with option strings
(like ``-f`` or ``--foo``) and ``nargs='?'``. This creates an optional
argument that can be followed by zero or one command-line args.
argument that can be followed by zero or one command-line arguments.
When parsing the command line, if the option string is encountered with no
command-line arg following it, the value of ``const`` will be assumed instead.
command-line argument following it, the value of ``const`` will be assumed instead.
See the nargs_ description for examples.
The ``const`` keyword argument defaults to ``None``.
@ -851,7 +855,7 @@ default
All optional arguments and some positional arguments may be omitted at the
command line. The ``default`` keyword argument of
:meth:`~ArgumentParser.add_argument`, whose value defaults to ``None``,
specifies what value should be used if the command-line arg is not present.
specifies what value should be used if the command-line argument is not present.
For optional arguments, the ``default`` value is used when the option string
was not present at the command line::
@ -862,8 +866,8 @@ was not present at the command line::
>>> parser.parse_args(''.split())
Namespace(foo=42)
For positional arguments with nargs_ ``='?'`` or ``'*'``, the ``default`` value
is used when no command-line arg was present::
For positional arguments with nargs_ equal to ``?`` or ``*``, the ``default`` value
is used when no command-line argument was present::
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('foo', nargs='?', default=42)
@ -887,12 +891,12 @@ command-line argument was not present.::
type
^^^^
By default, ArgumentParser objects read command-line args in as simple strings.
However, quite often the command-line string should instead be interpreted as
another type, like a :class:`float`, :class:`int` or :class:`file`. The
By default, :class:`ArgumentParser` objects read command-line arguments in as simple
strings. However, quite often the command-line string should instead be
interpreted as another type, like a :class:`float` or :class:`int`. The
``type`` keyword argument of :meth:`~ArgumentParser.add_argument` allows any
necessary type-checking and type-conversions to be performed. Many common
built-in types can be used directly as the value of the ``type`` argument::
necessary type-checking and type conversions to be performed. Common built-in
types and functions can be used directly as the value of the ``type`` argument::
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('foo', type=int)
@ -911,7 +915,7 @@ writable file::
Namespace(bar=<open file 'out.txt', mode 'w' at 0x...>)
``type=`` can take any callable that takes a single string argument and returns
the type-converted value::
the converted value::
>>> def perfect_square(string):
... value = int(string)
@ -946,11 +950,11 @@ See the choices_ section for more details.
choices
^^^^^^^
Some command-line args should be selected from a restricted set of values.
Some command-line arguments should be selected from a restricted set of values.
These can be handled by passing a container object as the ``choices`` keyword
argument to :meth:`~ArgumentParser.add_argument`. When the command line is
parsed, arg values will be checked, and an error message will be displayed if
the arg was not one of the acceptable values::
parsed, argument values will be checked, and an error message will be displayed if
the argument was not one of the acceptable values::
>>> parser = argparse.ArgumentParser(prog='PROG')
>>> parser.add_argument('foo', choices='abc')
@ -1053,7 +1057,7 @@ value as the "name" of each object. By default, for positional argument
actions, the dest_ value is used directly, and for optional argument actions,
the dest_ value is uppercased. So, a single positional argument with
``dest='bar'`` will that argument will be referred to as ``bar``. A single
optional argument ``--foo`` that should be followed by a single command-line arg
optional argument ``--foo`` that should be followed by a single command-line argument
will be referred to as ``FOO``. An example::
>>> parser = argparse.ArgumentParser()
@ -1125,10 +1129,10 @@ attribute is determined by the ``dest`` keyword argument of
For optional argument actions, the value of ``dest`` is normally inferred from
the option strings. :class:`ArgumentParser` generates the value of ``dest`` by
taking the first long option string and stripping away the initial ``'--'``
taking the first long option string and stripping away the initial ``--``
string. If no long option strings were supplied, ``dest`` will be derived from
the first short option string by stripping the initial ``'-'`` character. Any
internal ``'-'`` characters will be converted to ``'_'`` characters to make sure
the first short option string by stripping the initial ``-`` character. Any
internal ``-`` characters will be converted to ``_`` characters to make sure
the string is a valid attribute name. The examples below illustrate this
behavior::
@ -1160,7 +1164,7 @@ The parse_args() method
created and how they are assigned. See the documentation for
:meth:`add_argument` for details.
By default, the arg strings are taken from :data:`sys.argv`, and a new empty
By default, the argument strings are taken from :data:`sys.argv`, and a new empty
:class:`Namespace` object is created for the attributes.
@ -1231,15 +1235,15 @@ it exits and prints the error along with a usage message::
PROG: error: extra arguments found: badger
Arguments containing ``"-"``
^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Arguments containing ``-``
^^^^^^^^^^^^^^^^^^^^^^^^^^
The :meth:`~ArgumentParser.parse_args` method attempts to give errors whenever
the user has clearly made a mistake, but some situations are inherently
ambiguous. For example, the command-line arg ``'-1'`` could either be an
ambiguous. For example, the command-line argument ``-1`` could either be an
attempt to specify an option or an attempt to provide a positional argument.
The :meth:`~ArgumentParser.parse_args` method is cautious here: positional
arguments may only begin with ``'-'`` if they look like negative numbers and
arguments may only begin with ``-`` if they look like negative numbers and
there are no options in the parser that look like negative numbers::
>>> parser = argparse.ArgumentParser(prog='PROG')
@ -1272,7 +1276,7 @@ there are no options in the parser that look like negative numbers::
usage: PROG [-h] [-1 ONE] [foo]
PROG: error: argument -1: expected one argument
If you have positional arguments that must begin with ``'-'`` and don't look
If you have positional arguments that must begin with ``-`` and don't look
like negative numbers, you can insert the pseudo-argument ``'--'`` which tells
:meth:`~ArgumentParser.parse_args` that everything after that is a positional
argument::
@ -1304,7 +1308,7 @@ An error is produced for arguments that could produce more than one options.
Beyond ``sys.argv``
^^^^^^^^^^^^^^^^^^^
Sometimes it may be useful to have an ArgumentParser parse args other than those
Sometimes it may be useful to have an ArgumentParser parse arguments other than those
of :data:`sys.argv`. This can be accomplished by passing a list of strings to
:meth:`~ArgumentParser.parse_args`. This is useful for testing at the
interactive prompt::
@ -1390,7 +1394,7 @@ Sub-commands
>>> parser_b = subparsers.add_parser('b', help='b help')
>>> parser_b.add_argument('--baz', choices='XYZ', help='baz help')
>>>
>>> # parse some arg lists
>>> # parse some argument lists
>>> parser.parse_args(['a', '12'])
Namespace(bar=12, foo=False)
>>> parser.parse_args(['--foo', 'b', '--baz', 'Z'])
@ -1399,8 +1403,8 @@ Sub-commands
Note that the object returned by :meth:`parse_args` will only contain
attributes for the main parser and the subparser that was selected by the
command line (and not any other subparsers). So in the example above, when
the ``"a"`` command is specified, only the ``foo`` and ``bar`` attributes are
present, and when the ``"b"`` command is specified, only the ``foo`` and
the ``a`` command is specified, only the ``foo`` and ``bar`` attributes are
present, and when the ``b`` command is specified, only the ``foo`` and
``baz`` attributes are present.
Similarly, when a help message is requested from a subparser, only the help
@ -1522,7 +1526,7 @@ FileType objects
The :class:`FileType` factory creates objects that can be passed to the type
argument of :meth:`ArgumentParser.add_argument`. Arguments that have
:class:`FileType` objects as their type will open command-line args as files
:class:`FileType` objects as their type will open command-line arguments as files
with the requested modes and buffer sizes:
>>> parser = argparse.ArgumentParser()
@ -1636,7 +1640,7 @@ Parser defaults
.. method:: ArgumentParser.set_defaults(**kwargs)
Most of the time, the attributes of the object returned by :meth:`parse_args`
will be fully determined by inspecting the command-line args and the argument
will be fully determined by inspecting the command-line arguments and the argument
actions. :meth:`set_defaults` allows some additional
attributes that are determined without any inspection of the command line to
be added::

View File

@ -1,7 +1,5 @@
.. _ast:
Abstract Syntax Trees
=====================
:mod:`ast` --- Abstract Syntax Trees
====================================
.. module:: ast
:synopsis: Abstract Syntax Tree classes and manipulation.
@ -15,6 +13,9 @@ Abstract Syntax Trees
.. versionadded:: 2.6
The high-level ``ast`` module containing all helpers.
**Source code:** :source:`Lib/ast.py`
--------------
The :mod:`ast` module helps Python applications to process trees of the Python
abstract syntax grammar. The abstract syntax itself might change with each
@ -28,11 +29,6 @@ classes all inherit from :class:`ast.AST`. An abstract syntax tree can be
compiled into a Python code object using the built-in :func:`compile` function.
.. seealso::
Latest version of the `ast module Python source code
<http://svn.python.org/view/python/branches/release27-maint/Lib/ast.py?view=markup>`_
Node classes
------------

View File

@ -1,4 +1,3 @@
:mod:`asynchat` --- Asynchronous socket command/response handler
================================================================
@ -7,6 +6,9 @@
.. moduleauthor:: Sam Rushing <rushing@nightmare.com>
.. sectionauthor:: Steve Holden <sholden@holdenweb.com>
**Source code:** :source:`Lib/asynchat.py`
--------------
This module builds on the :mod:`asyncore` infrastructure, simplifying
asynchronous clients and servers and making it easier to handle protocols

View File

@ -1,4 +1,3 @@
:mod:`asyncore` --- Asynchronous socket handler
===============================================
@ -10,6 +9,9 @@
.. sectionauthor:: Steve Holden <sholden@holdenweb.com>
.. heavily adapted from original documentation by Sam Rushing
**Source code:** :source:`Lib/asyncore.py`
--------------
This module provides the basic infrastructure for writing asynchronous socket
service clients and servers.

View File

@ -1,4 +1,3 @@
:mod:`atexit` --- Exit handlers
===============================
@ -10,17 +9,16 @@
.. versionadded:: 2.0
**Source code:** :source:`Lib/atexit.py`
--------------
The :mod:`atexit` module defines a single function to register cleanup
functions. Functions thus registered are automatically executed upon normal
interpreter termination. The order in which the functions are called is not
defined; if you have cleanup operations that depend on each other, you should
wrap them in a function and register that one. This keeps :mod:`atexit` simple.
.. seealso::
Latest version of the `atexit Python source code
<http://svn.python.org/view/python/branches/release27-maint/Lib/atexit.py?view=markup>`_
Note: the functions registered via this module are not called when the program
is killed by a signal not handled by Python, when a Python fatal internal error
is detected, or when :func:`os._exit` is called.

View File

@ -18,6 +18,10 @@
module: SimpleHTTPServer
module: CGIHTTPServer
**Source code:** :source:`Lib/BaseHTTPServer.py`
--------------
This module defines two classes for implementing HTTP servers (Web servers).
Usually, this module isn't used directly, but is used as a basis for building
functioning Web servers. See the :mod:`SimpleHTTPServer` and

View File

@ -4,6 +4,10 @@
.. module:: bdb
:synopsis: Debugger framework.
**Source code:** :source:`Lib/bdb.py`
--------------
The :mod:`bdb` module handles basic debugger functions, like setting breakpoints
or managing execution via the debugger.

View File

@ -7,6 +7,12 @@
.. sectionauthor:: Raymond Hettinger <python at rcn.com>
.. example based on the PyModules FAQ entry by Aaron Watters <arw@pythonpros.com>
.. versionadded:: 2.1
**Source code:** :source:`Lib/bisect.py`
--------------
This module provides support for maintaining a list in sorted order without
having to sort the list after each insertion. For long lists of items with
expensive comparison operations, this can be an improvement over the more common
@ -14,13 +20,6 @@ approach. The module is called :mod:`bisect` because it uses a basic bisection
algorithm to do its work. The source code may be most useful as a working
example of the algorithm (the boundary conditions are already right!).
.. versionadded:: 2.1
.. seealso::
Latest version of the `bisect module Python source code
<http://svn.python.org/view/python/branches/release27-maint/Lib/bisect.py?view=markup>`_
The following functions are provided:

View File

@ -1,4 +1,3 @@
:mod:`calendar` --- General calendar-related functions
======================================================
@ -7,6 +6,9 @@
program.
.. sectionauthor:: Drew Csillag <drew_csillag@geocities.com>
**Source code:** :source:`Lib/calendar.py`
--------------
This module allows you to output calendars like the Unix :program:`cal` program,
and provides additional useful functions related to the calendar. By default,
@ -22,10 +24,6 @@ in both directions. This matches the definition of the "proleptic Gregorian"
calendar in Dershowitz and Reingold's book "Calendrical Calculations", where
it's the base calendar for all computations.
.. seealso::
Latest version of the `calendar module Python source code
<http://svn.python.org/view/python/branches/release27-maint/Lib/calendar.py?view=markup>`_
.. class:: Calendar([firstweekday])

View File

@ -13,6 +13,10 @@
single: URL
single: Common Gateway Interface
**Source code:** :source:`Lib/cgi.py`
--------------
Support module for Common Gateway Interface (CGI) scripts.
This module defines a number of utilities for use by CGI scripts written in

View File

@ -1,4 +1,3 @@
:mod:`cmd` --- Support for line-oriented command interpreters
=============================================================
@ -6,17 +5,15 @@
:synopsis: Build line-oriented command interpreters.
.. sectionauthor:: Eric S. Raymond <esr@snark.thyrsus.com>
**Source code:** :source:`Lib/cmd.py`
--------------
The :class:`Cmd` class provides a simple framework for writing line-oriented
command interpreters. These are often useful for test harnesses, administrative
tools, and prototypes that will later be wrapped in a more sophisticated
interface.
.. seealso::
Latest version of the `cmd module Python source code
<http://svn.python.org/view/python/branches/release27-maint/Lib/cmd.py?view=markup>`_
.. class:: Cmd([completekey[, stdin[, stdout]]])
A :class:`Cmd` instance or subclass instance is a line-oriented interpreter

View File

@ -1,4 +1,3 @@
:mod:`collections` --- High-performance container datatypes
===========================================================
@ -15,6 +14,10 @@
import itertools
__name__ = '<doctest>'
**Source code:** :source:`Lib/collections.py` and :source:`Lib/_abcoll.py`
--------------
This module implements specialized container datatypes providing alternatives to
Python's general purpose built-in containers, :class:`dict`, :class:`list`,
:class:`set`, and :class:`tuple`.
@ -28,13 +31,10 @@ Python's general purpose built-in containers, :class:`dict`, :class:`list`,
===================== ==================================================================== ===========================
In addition to the concrete container classes, the collections module provides
:ref:`collections-abstract-base-classes` that can be used to test whether a class provides a
particular interface, for example, whether it is hashable or a mapping.
:ref:`abstract base classes <collections-abstract-base-classes>` that can be
used to test whether a class provides a particular interface, for example,
whether it is hashable or a mapping.
.. seealso::
Latest version of the `collections module Python source code
<http://svn.python.org/view/python/branches/release27-maint/Lib/collections.py?view=markup>`_
:class:`Counter` objects
------------------------
@ -1023,9 +1023,6 @@ Notes on using :class:`Set` and :class:`MutableSet` as a mixin:
.. seealso::
* Latest version of the `Python source code for the collections abstract base classes
<http://svn.python.org/view/python/branches/release27-maint/Lib/_abcoll.py?view=markup>`_
* `OrderedSet recipe <http://code.activestate.com/recipes/576694/>`_ for an
example built on :class:`MutableSet`.

View File

@ -5,6 +5,9 @@
:synopsis: Conversion functions between RGB and other color systems.
.. sectionauthor:: David Ascher <da@python.net>
**Source code:** :source:`Lib/colorsys.py`
--------------
The :mod:`colorsys` module defines bidirectional conversions of color values
between colors expressed in the RGB (Red Green Blue) color space used in

View File

@ -7,15 +7,14 @@
.. versionadded:: 2.5
**Source code:** :source:`Lib/contextlib.py`
--------------
This module provides utilities for common tasks involving the :keyword:`with`
statement. For more information see also :ref:`typecontextmanager` and
:ref:`context-managers`.
.. seealso::
Latest version of the `contextlib Python source code
<http://svn.python.org/view/python/branches/release27-maint/Lib/contextlib.py?view=markup>`_
Functions provided:

View File

@ -11,6 +11,9 @@
3.0. The :term:`2to3` tool will automatically adapt imports when converting
your sources to 3.0.
**Source code:** :source:`Lib/Cookie.py`
--------------
The :mod:`Cookie` module defines classes for abstracting the concept of
cookies, an HTTP state management mechanism. It supports both simple string-only

View File

@ -11,10 +11,11 @@
Python 3.0. The :term:`2to3` tool will automatically adapt imports when
converting your sources to 3.0.
.. versionadded:: 2.4
**Source code:** :source:`Lib/cookielib.py`
--------------
The :mod:`cookielib` module defines classes for automatic handling of HTTP
cookies. It is useful for accessing web sites that require small pieces of data

View File

@ -1,21 +1,18 @@
:mod:`dis` --- Disassembler for Python bytecode
===============================================
.. module:: dis
:synopsis: Disassembler for Python bytecode.
**Source code:** :source:`Lib/dis.py`
--------------
The :mod:`dis` module supports the analysis of CPython :term:`bytecode` by
disassembling it. The CPython bytecode which this module takes as an
input is defined in the file :file:`Include/opcode.h` and used by the compiler
and the interpreter.
.. seealso::
Latest version of the `dis module Python source code
<http://svn.python.org/view/python/branches/release27-maint/Lib/dis.py?view=markup>`_
.. impl-detail::
Bytecode is an implementation detail of the CPython interpreter! No

View File

@ -10,6 +10,9 @@
converting your sources to 3.0; however, you should consider using the
high-lever :mod:`dummy_threading` module instead.
**Source code:** :source:`Lib/dummy_thread.py`
--------------
This module provides a duplicate interface to the :mod:`thread` module. It is
meant to be imported when the :mod:`thread` module is not provided on a

View File

@ -1,10 +1,12 @@
:mod:`dummy_threading` --- Drop-in replacement for the :mod:`threading` module
==============================================================================
.. module:: dummy_threading
:synopsis: Drop-in replacement for the threading module.
**Source code:** :source:`Lib/dummy_threading.py`
--------------
This module provides a duplicate interface to the :mod:`threading` module. It
is meant to be imported when the :mod:`thread` module is not provided on a

View File

@ -1,4 +1,3 @@
:mod:`filecmp` --- File and Directory Comparisons
=================================================
@ -6,16 +5,14 @@
:synopsis: Compare files efficiently.
.. sectionauthor:: Moshe Zadka <moshez@zadka.site.co.il>
**Source code:** :source:`Lib/filecmp.py`
--------------
The :mod:`filecmp` module defines functions to compare files and directories,
with various optional time/correctness trade-offs. For comparing files,
see also the :mod:`difflib` module.
.. seealso::
Latest version of the `filecmp Python source code
<http://svn.python.org/view/python/branches/release27-maint/Lib/filecmp.py?view=markup>`_
The :mod:`filecmp` module defines the following functions:

View File

@ -6,6 +6,9 @@
.. moduleauthor:: Guido van Rossum <guido@python.org>
.. sectionauthor:: Fred L. Drake, Jr. <fdrake@acm.org>
**Source code:** :source:`Lib/fileinput.py`
--------------
This module implements a helper class and functions to quickly write a
loop over standard input or a list of files. If you just want to read or
@ -44,11 +47,6 @@ hook must be a function that takes two arguments, *filename* and *mode*, and
returns an accordingly opened file-like object. Two useful hooks are already
provided by this module.
.. seealso::
Latest version of the `fileinput Python source code
<http://svn.python.org/view/python/branches/release27-maint/Lib/fileinput.py?view=markup>`_
The following function is the primary interface of this module:

View File

@ -1,4 +1,3 @@
:mod:`fnmatch` --- Unix filename pattern matching
=================================================
@ -10,6 +9,10 @@
.. index:: module: re
**Source code:** :source:`Lib/fnmatch.py`
--------------
This module provides support for Unix shell-style wildcards, which are *not* the
same as regular expressions (which are documented in the :mod:`re` module). The
special characters used in shell-style wildcards are:
@ -34,10 +37,6 @@ module. See module :mod:`glob` for pathname expansion (:mod:`glob` uses
a period are not special for this module, and are matched by the ``*`` and ``?``
patterns.
.. seealso::
Latest version of the `fnmatch Python source code
<http://svn.python.org/view/python/branches/release27-maint/Lib/fnmatch.py?view=markup>`_
.. function:: fnmatch(filename, pattern)
@ -95,4 +94,3 @@ patterns.
Module :mod:`glob`
Unix shell-style path expansion.

View File

@ -1,4 +1,3 @@
:mod:`fractions` --- Rational numbers
=====================================
@ -8,6 +7,9 @@
.. sectionauthor:: Jeffrey Yasskin <jyasskin at gmail.com>
.. versionadded:: 2.6
**Source code:** :source:`Lib/fractions.py`
--------------
The :mod:`fractions` module provides support for rational number arithmetic.

View File

@ -9,6 +9,10 @@
pair: FTP; protocol
single: FTP; ftplib (standard module)
**Source code:** :source:`Lib/ftplib.py`
--------------
This module defines the class :class:`FTP` and a few related items. The
:class:`FTP` class implements the client side of the FTP protocol. You can use
this to write Python programs that perform a variety of automated FTP jobs, such

View File

@ -8,18 +8,16 @@
.. moduleauthor:: Nick Coghlan <ncoghlan@gmail.com>
.. sectionauthor:: Peter Harris <scav@blueyonder.co.uk>
.. versionadded:: 2.5
**Source code:** :source:`Lib/functools.py`
--------------
The :mod:`functools` module is for higher-order functions: functions that act on
or return other functions. In general, any callable object can be treated as a
function for the purposes of this module.
.. seealso::
Latest version of the `functools Python source code
<http://svn.python.org/view/python/branches/release27-maint/Lib/functools.py?view=markup>`_
The :mod:`functools` module defines the following functions:
.. function:: cmp_to_key(func)

View File

@ -1,4 +1,3 @@
:mod:`getopt` --- C-style parser for command line options
=========================================================
@ -6,6 +5,10 @@
:synopsis: Portable parser for command line options; support both short and long option
names.
**Source code:** :source:`Lib/getopt.py`
--------------
.. note::
The :mod:`getopt` module is a parser for command line options whose API is
designed to be familiar to users of the C :cfunc:`getopt` function. Users who

View File

@ -1,4 +1,3 @@
:mod:`gettext` --- Multilingual internationalization services
=============================================================
@ -7,6 +6,9 @@
.. moduleauthor:: Barry A. Warsaw <barry@zope.com>
.. sectionauthor:: Barry A. Warsaw <barry@zope.com>
**Source code:** :source:`Lib/gettext.py`
--------------
The :mod:`gettext` module provides internationalization (I18N) and localization
(L10N) services for your Python modules and applications. It supports both the

View File

@ -1,4 +1,3 @@
:mod:`glob` --- Unix style pathname pattern expansion
=====================================================
@ -8,6 +7,10 @@
.. index:: single: filenames; pathname expansion
**Source code:** :source:`Lib/glob.py`
--------------
The :mod:`glob` module finds all the pathnames matching a specified pattern
according to the rules used by the Unix shell. No tilde expansion is done, but
``*``, ``?``, and character ranges expressed with ``[]`` will be correctly
@ -16,10 +19,6 @@ matched. This is done by using the :func:`os.listdir` and
subshell. (For tilde and shell variable expansion, use
:func:`os.path.expanduser` and :func:`os.path.expandvars`.)
.. seealso::
Latest version of the `glob module Python source code
<http://svn.python.org/view/python/branches/release27-maint/Lib/glob.py?view=markup>`_
.. function:: glob(pathname)

View File

@ -4,6 +4,10 @@
.. module:: gzip
:synopsis: Interfaces for gzip compression and decompression using file objects.
**Source code:** :source:`Lib/gzip.py`
--------------
This module provides a simple interface to compress and decompress files just
like the GNU programs :program:`gzip` and :program:`gunzip` would.

View File

@ -1,4 +1,3 @@
:mod:`hashlib` --- Secure hashes and message digests
====================================================
@ -14,6 +13,10 @@
single: message digest, MD5
single: secure hash algorithm, SHA1, SHA224, SHA256, SHA384, SHA512
**Source code:** :source:`Lib/hashlib.py`
--------------
This module implements a common interface to many different secure hash and
message digest algorithms. Included are the FIPS secure hash algorithms SHA1,
SHA224, SHA256, SHA384, and SHA512 (defined in FIPS 180-2) as well as RSA's MD5

View File

@ -10,14 +10,13 @@
.. versionadded:: 2.3
**Source code:** :source:`Lib/heapq.py`
--------------
This module provides an implementation of the heap queue algorithm, also known
as the priority queue algorithm.
.. seealso::
Latest version of the `heapq Python source code
<http://svn.python.org/view/*checkout*/python/branches/release27-maint/Lib/heapq.py?content-type=text%2Fplain>`_
Heaps are binary trees for which every parent node has a value less than or
equal to any of its children. This implementation uses arrays for which
``heap[k] <= heap[2*k+1]`` and ``heap[k] <= heap[2*k+2]`` for all *k*, counting

View File

@ -1,4 +1,3 @@
:mod:`hmac` --- Keyed-Hashing for Message Authentication
========================================================
@ -10,6 +9,10 @@
.. versionadded:: 2.2
**Source code:** :source:`Lib/hmac.py`
--------------
This module implements the HMAC algorithm as described by :rfc:`2104`.

View File

@ -165,6 +165,9 @@ additional methods and instance variables for use within tag methods.
Python 3.0. The :term:`2to3` tool will automatically adapt imports when
converting your sources to 3.0.
**Source code:** :source:`Lib/htmlentitydefs.py`
--------------
This module defines three dictionaries, ``name2codepoint``, ``codepoint2name``,
and ``entitydefs``. ``entitydefs`` is used by the :mod:`htmllib` module to

View File

@ -18,6 +18,10 @@
single: HTML
single: XHTML
**Source code:** :source:`Lib/HTMLParser.py`
--------------
This module defines a class :class:`HTMLParser` which serves as the basis for
parsing text files formatted in HTML (HyperText Mark-up Language) and XHTML.
Unlike the parser in :mod:`htmllib`, this parser is not based on the SGML parser

View File

@ -16,6 +16,10 @@
.. index:: module: urllib
**Source code:** :source:`Lib/httplib.py`
--------------
This module defines classes which implement the client side of the HTTP and
HTTPS protocols. It is normally not used directly --- the module :mod:`urllib`
uses it to handle URLs that use HTTP and HTTPS.

View File

@ -16,6 +16,10 @@
pair: IMAP4_SSL; protocol
pair: IMAP4_stream; protocol
**Source code:** :source:`Lib/imaplib.py`
--------------
This module defines three classes, :class:`IMAP4`, :class:`IMAP4_SSL` and
:class:`IMAP4_stream`, which encapsulate a connection to an IMAP4 server and
implement a large subset of the IMAP4rev1 client protocol as defined in

View File

@ -1,10 +1,12 @@
:mod:`imghdr` --- Determine the type of an image
================================================
.. module:: imghdr
:synopsis: Determine the type of image contained in a file or byte stream.
**Source code:** :source:`Lib/imghdr.py`
--------------
The :mod:`imghdr` module determines the type of image contained in a file or
byte stream.

View File

@ -1,4 +1,3 @@
:mod:`inspect` --- Inspect live objects
=======================================
@ -10,6 +9,10 @@
.. versionadded:: 2.1
**Source code:** :source:`Lib/inspect.py`
--------------
The :mod:`inspect` module provides several useful functions to help get
information about live objects such as modules, classes, methods, functions,
tracebacks, frame objects, and code objects. For example, it can help you

View File

@ -1,10 +1,12 @@
:mod:`keyword` --- Testing for Python keywords
==============================================
.. module:: keyword
:synopsis: Test whether a string is a keyword in Python.
**Source code:** :source:`Lib/keyword.py`
--------------
This module allows a Python program to determine if a string is a keyword.
@ -19,9 +21,3 @@ This module allows a Python program to determine if a string is a keyword.
Sequence containing all the keywords defined for the interpreter. If any
keywords are defined to only be active when particular :mod:`__future__`
statements are in effect, these will be included as well.
.. seealso::
Latest version of the `keyword module Python source code
<http://svn.python.org/view/python/branches/release27-maint/Lib/keyword.py?view=markup>`_

View File

@ -6,17 +6,15 @@
:synopsis: This module provides random access to individual lines from text files.
.. sectionauthor:: Moshe Zadka <moshez@zadka.site.co.il>
**Source code:** :source:`Lib/linecache.py`
--------------
The :mod:`linecache` module allows one to get any line from any file, while
attempting to optimize internally, using a cache, the common case where many
lines are read from a single file. This is used by the :mod:`traceback` module
to retrieve source lines for inclusion in the formatted traceback.
.. seealso::
Latest version of the `linecache module Python source code
<http://svn.python.org/view/python/branches/release27-maint/Lib/linecache.py?view=markup>`_
The :mod:`linecache` module defines the following functions:

View File

@ -4,7 +4,9 @@
.. module:: mailcap
:synopsis: Mailcap file handling.
**Source code:** :source:`Lib/mailcap.py`
--------------
Mailcap files are used to configure how MIME-aware applications such as mail
readers and Web browsers react to files with different MIME types. (The name

View File

@ -9,6 +9,10 @@
.. index:: pair: MIME; content type
**Source code:** :source:`Lib/mimetypes.py`
--------------
The :mod:`mimetypes` module converts between a filename or URL and the MIME type
associated with the filename extension. Conversions are provided from filename
to MIME type and from MIME type to filename extension; encodings are not

View File

@ -1,16 +1,17 @@
:mod:`modulefinder` --- Find modules used by a script
=====================================================
.. module:: modulefinder
:synopsis: Find modules used by a script.
.. sectionauthor:: A.M. Kuchling <amk@amk.ca>
.. module:: modulefinder
:synopsis: Find modules used by a script.
.. versionadded:: 2.3
**Source code:** :source:`Lib/modulefinder.py`
--------------
This module provides a :class:`ModuleFinder` class that can be used to determine
the set of modules imported by a script. ``modulefinder.py`` can also be run as
a script, giving the filename of a Python script as its argument, after which a

View File

@ -10,6 +10,10 @@
.. versionadded:: 1.5.2
**Source code:** :source:`Lib/netrc.py`
--------------
The :class:`netrc` class parses and encapsulates the netrc file format used by
the Unix :program:`ftp` program and other FTP clients.

View File

@ -10,6 +10,10 @@
pair: NNTP; protocol
single: Network News Transfer Protocol
**Source code:** :source:`Lib/nntplib.py`
--------------
This module defines the class :class:`NNTP` which implements the client side of
the NNTP protocol. It can be used to implement a news reader or poster, or
automated news processors. For more information on NNTP (Network News Transfer

View File

@ -4,17 +4,18 @@
.. module:: optparse
:synopsis: Command-line option parsing library.
:deprecated:
.. moduleauthor:: Greg Ward <gward@python.net>
.. sectionauthor:: Greg Ward <gward@python.net>
.. versionadded:: 2.3
.. deprecated:: 2.7
The :mod:`optparse` module is deprecated and will not be developed further;
development will continue with the :mod:`argparse` module.
.. moduleauthor:: Greg Ward <gward@python.net>
.. versionadded:: 2.3
.. sectionauthor:: Greg Ward <gward@python.net>
**Source code:** :source:`Lib/optparse.py`
--------------
:mod:`optparse` is a more convenient, flexible, and powerful library for parsing
command-line options than the old :mod:`getopt` module. :mod:`optparse` uses a

View File

@ -8,6 +8,10 @@
.. versionadded:: 2.3
**Source code:** :source:`Lib/pickletools.py`
--------------
This module contains various constants relating to the intimate details of the
:mod:`pickle` module, some lengthy comments about the implementation, and a few
useful functions for analyzing pickled data. The contents of this module are

View File

@ -1,4 +1,3 @@
:mod:`pipes` --- Interface to shell pipelines
=============================================
@ -7,6 +6,9 @@
:synopsis: A Python interface to Unix shell pipelines.
.. sectionauthor:: Moshe Zadka <moshez@zadka.site.co.il>
**Source code:** :source:`Lib/pipes.py`
--------------
The :mod:`pipes` module defines a class to abstract the concept of a *pipeline*
--- a sequence of converters from one file to another.

View File

@ -1,15 +1,18 @@
:mod:`pkgutil` --- Package extension utility
============================================
.. module:: pkgutil
:synopsis: Utilities for the import system.
.. versionadded:: 2.3
**Source code:** :source:`Lib/pkgutil.py`
--------------
This module provides utilities for the import system, in particular package
support.
.. versionadded:: 2.3
.. function:: extend_path(path, name)

View File

@ -9,6 +9,10 @@
.. versionadded:: 2.3
**Source code:** :source:`Lib/platform.py`
--------------
.. note::
Specific platforms listed alphabetically, with Linux included in the Unix

View File

@ -15,6 +15,10 @@
pair: plist; file
single: property list
**Source code:** :source:`Lib/plistlib.py`
--------------
This module provides an interface for reading and writing the "property list"
XML files used mainly by Mac OS X.

View File

@ -1,4 +1,3 @@
:mod:`poplib` --- POP3 protocol client
======================================
@ -9,6 +8,10 @@
.. index:: pair: POP3; protocol
**Source code:** :source:`Lib/poplib.py`
--------------
This module defines a class, :class:`POP3`, which encapsulates a connection to a
POP3 server and implements the protocol as defined in :rfc:`1725`. The
:class:`POP3` class supports both the minimal and optional command sets.

View File

@ -1,4 +1,3 @@
:mod:`pprint` --- Data pretty printer
=====================================
@ -7,6 +6,9 @@
.. moduleauthor:: Fred L. Drake, Jr. <fdrake@acm.org>
.. sectionauthor:: Fred L. Drake, Jr. <fdrake@acm.org>
**Source code:** :source:`Lib/pprint.py`
--------------
The :mod:`pprint` module provides a capability to "pretty-print" arbitrary
Python data structures in a form which can be used as input to the interpreter.
@ -28,10 +30,6 @@ width constraint.
.. versionchanged:: 2.6
Added support for :class:`set` and :class:`frozenset`.
.. seealso::
Latest version of the `pprint module Python source code
<http://svn.python.org/view/python/branches/release27-maint/Lib/pprint.py?view=markup>`_
The :mod:`pprint` module defines one class:

View File

@ -1,4 +1,3 @@
.. _profile:
********************
@ -10,6 +9,9 @@ The Python Profilers
.. module:: profile
:synopsis: Python source profiler.
**Source code:** :source:`Lib/profile.py` and :source:`Lib/pstats.py`
--------------
.. _profiler-introduction:

View File

@ -8,6 +8,10 @@
.. index:: pair: file; byte-code
**Source code:** :source:`Lib/py_compile.py`
--------------
The :mod:`py_compile` module provides a function to generate a byte-code file
from a source file, and another function used when the module source file is
invoked as a script.

View File

@ -1,4 +1,3 @@
:mod:`pyclbr` --- Python class browser support
==============================================
@ -6,6 +5,9 @@
:synopsis: Supports information extraction for a Python class browser.
.. sectionauthor:: Fred L. Drake, Jr. <fdrake@acm.org>
**Source code:** :source:`Lib/pyclbr.py`
--------------
The :mod:`pyclbr` module can be used to determine some limited information
about the classes, methods and top-level functions defined in a module. The

View File

@ -1,4 +1,3 @@
:mod:`pydoc` --- Documentation generator and online help system
===============================================================
@ -15,6 +14,10 @@
single: documentation; online
single: help; online
**Source code:** :source:`Lib/pydoc.py`
--------------
The :mod:`pydoc` module automatically generates documentation from Python
modules. The documentation can be presented as pages of text on the console,
served to a Web browser, or saved to HTML files.

View File

@ -9,6 +9,9 @@
:term:`2to3` tool will automatically adapt imports when converting your
sources to 3.0.
**Source code:** :source:`Lib/Queue.py`
--------------
The :mod:`Queue` module implements multi-producer, multi-consumer queues.
It is especially useful in threaded programming when information must be
@ -24,11 +27,6 @@ the first retrieved (operating like a stack). With a priority queue,
the entries are kept sorted (using the :mod:`heapq` module) and the
lowest valued entry is retrieved first.
.. seealso::
Latest version of the `Queue module Python source code
<http://svn.python.org/view/python/branches/release27-maint/Lib/Queue.py?view=markup>`_.
The :mod:`Queue` module defines the following classes and exceptions:
.. class:: Queue(maxsize=0)

View File

@ -1,4 +1,3 @@
:mod:`quopri` --- Encode and decode MIME quoted-printable data
==============================================================
@ -10,6 +9,10 @@
pair: quoted-printable; encoding
single: MIME; quoted-printable encoding
**Source code:** :source:`Lib/quopri.py`
--------------
This module performs quoted-printable transport encoding and decoding, as
defined in :rfc:`1521`: "MIME (Multipurpose Internet Mail Extensions) Part One:
Mechanisms for Specifying and Describing the Format of Internet Message Bodies".
@ -18,11 +21,6 @@ few nonprintable characters; the base64 encoding scheme available via the
:mod:`base64` module is more compact if there are many such characters, as when
sending a graphics file.
.. seealso::
Latest version of the `quopri module Python source code
<http://svn.python.org/view/python/branches/release27-maint/Lib/quopri.py?view=markup>`_
.. function:: decode(input, output[,header])
Decode the contents of the *input* file and write the resulting decoded binary

View File

@ -1,19 +1,16 @@
:mod:`random` --- Generate pseudo-random numbers
================================================
.. module:: random
:synopsis: Generate pseudo-random numbers with various common distributions.
**Source code:** :source:`Lib/random.py`
--------------
This module implements pseudo-random number generators for various
distributions.
.. seealso::
Latest version of the `random module Python source code
<http://svn.python.org/view/python/branches/release27-maint/Lib/random.py?view=markup>`_
For integers, uniform selection from a range. For sequences, uniform selection
of a random element, a function to generate a random permutation of a list
in-place, and a function for random sampling without replacement.

View File

@ -1,4 +1,3 @@
:mod:`repr` --- Alternate :func:`repr` implementation
=====================================================
@ -11,15 +10,14 @@
:term:`2to3` tool will automatically adapt imports when converting your
sources to 3.0.
**Source code:** :source:`Lib/repr.py`
--------------
The :mod:`repr` module provides a means for producing object representations
with limits on the size of the resulting strings. This is used in the Python
debugger and may be useful in other contexts as well.
.. seealso::
Latest version of the `repr module Python source code
<http://svn.python.org/view/python/branches/release27-maint/Lib/repr.py?view=markup>`_
This module provides a class, an instance, and a function:

View File

@ -1,4 +1,3 @@
:mod:`rlcompleter` --- Completion function for GNU readline
===========================================================
@ -6,6 +5,9 @@
:synopsis: Python identifier completion, suitable for the GNU readline library.
.. sectionauthor:: Moshe Zadka <moshez@zadka.site.co.il>
**Source code:** :source:`Lib/rlcompleter.py`
--------------
The :mod:`rlcompleter` module defines a completion function suitable for the
:mod:`readline` module by completing valid Python identifiers and keywords.

View File

@ -8,6 +8,10 @@
.. versionadded:: 2.5
**Source code:** :source:`Lib/runpy.py`
--------------
The :mod:`runpy` module is used to locate and run Python modules without
importing them first. Its main use is to implement the :option:`-m` command
line switch that allows scripts to be located using the Python module

View File

@ -7,14 +7,13 @@
.. index:: single: event scheduling
**Source code:** :source:`Lib/sched.py`
--------------
The :mod:`sched` module defines a class which implements a general purpose event
scheduler:
.. seealso::
Latest version of the `sched module Python source code
<http://svn.python.org/view/python/branches/release27-maint/Lib/sched.py?view=markup>`_
.. class:: scheduler(timefunc, delayfunc)
The :class:`scheduler` class defines a generic interface to scheduling events.

View File

@ -7,16 +7,16 @@
.. index:: module: pickle
**Source code:** :source:`Lib/shelve.py`
--------------
A "shelf" is a persistent, dictionary-like object. The difference with "dbm"
databases is that the values (not the keys!) in a shelf can be essentially
arbitrary Python objects --- anything that the :mod:`pickle` module can handle.
This includes most class instances, recursive data types, and objects containing
lots of shared sub-objects. The keys are ordinary strings.
.. seealso::
Latest version of the `shelve module Python source code
<http://svn.python.org/view/python/branches/release27-maint/Lib/shelve.py?view=markup>`_
.. function:: open(filename[, flag='c'[, protocol=None[, writeback=False]]])

View File

@ -1,4 +1,3 @@
:mod:`shlex` --- Simple lexical analysis
========================================
@ -12,6 +11,11 @@
.. versionadded:: 1.5.2
**Source code:** :source:`Lib/shlex.py`
--------------
The :class:`shlex` class makes it easy to write lexical analyzers for simple
syntaxes resembling that of the Unix shell. This will often be useful for
writing minilanguages, (for example, in run control files for Python

View File

@ -1,4 +1,3 @@
:mod:`shutil` --- High-level file operations
============================================
@ -11,16 +10,15 @@
single: file; copying
single: copying files
**Source code:** :source:`Lib/shutil.py`
--------------
The :mod:`shutil` module offers a number of high-level operations on files and
collections of files. In particular, functions are provided which support file
copying and removal. For operations on individual files, see also the
:mod:`os` module.
.. seealso::
Latest version of the `shutil module Python source code
<http://svn.python.org/view/python/branches/release27-maint/Lib/shutil.py?view=markup>`_
.. warning::
Even the higher-level file copying functions (:func:`copy`, :func:`copy2`)

View File

@ -14,6 +14,10 @@
.. versionadded:: 2.2
**Source code:** :source:`Lib/SimpleXMLRPCServer.py`
--------------
The :mod:`SimpleXMLRPCServer` module provides a basic server framework for
XML-RPC servers written in Python. Servers can either be free standing, using
:class:`SimpleXMLRPCServer`, or embedded in a CGI environment, using

View File

@ -1,10 +1,12 @@
:mod:`site` --- Site-specific configuration hook
================================================
.. module:: site
:synopsis: A standard way to reference site-specific modules.
**Source code:** :source:`Lib/site.py`
--------------
**This module is automatically imported during initialization.** The automatic
import can be suppressed using the interpreter's :option:`-S` option.

View File

@ -7,8 +7,9 @@
.. moduleauthor:: Barry Warsaw <barry@zope.com>
.. sectionauthor:: Moshe Zadka <moshez@moshez.org>
**Source code:** :source:`Lib/smtpd.py`
--------------
This module offers several classes to implement SMTP servers. One is a generic
do-nothing implementation, which can be overridden, while the other two offer

View File

@ -1,4 +1,3 @@
:mod:`smtplib` --- SMTP protocol client
=======================================
@ -11,6 +10,10 @@
pair: SMTP; protocol
single: Simple Mail Transfer Protocol
**Source code:** :source:`Lib/smtplib.py`
--------------
The :mod:`smtplib` module defines an SMTP client session object that can be used
to send mail to any Internet machine with an SMTP or ESMTP listener daemon. For
details of SMTP and ESMTP operation, consult :rfc:`821` (Simple Mail Transfer

View File

@ -1,4 +1,3 @@
:mod:`sndhdr` --- Determine type of sound file
==============================================
@ -11,6 +10,10 @@
single: A-LAW
single: u-LAW
**Source code:** :source:`Lib/sndhdr.py`
--------------
The :mod:`sndhdr` provides utility functions which attempt to determine the type
of sound data which is in a file. When these functions are able to determine
what type of sound data is stored in a file, they return a tuple ``(type,

View File

@ -1,4 +1,3 @@
:mod:`SocketServer` --- A framework for network servers
=======================================================
@ -11,6 +10,9 @@
Python 3.0. The :term:`2to3` tool will automatically adapt imports when
converting your sources to 3.0.
**Source code:** :source:`Lib/SocketServer.py`
--------------
The :mod:`SocketServer` module simplifies the task of writing network servers.

View File

@ -5,9 +5,6 @@
:synopsis: TLS/SSL wrapper for socket objects
.. moduleauthor:: Bill Janssen <bill.janssen@gmail.com>
.. versionadded:: 2.6
.. sectionauthor:: Bill Janssen <bill.janssen@gmail.com>
@ -15,6 +12,12 @@
.. index:: TLS, SSL, Transport Layer Security, Secure Sockets Layer
.. versionadded:: 2.6
**Source code:** :source:`Lib/ssl.py`
--------------
This module provides access to Transport Layer Security (often known as "Secure
Sockets Layer") encryption and peer authentication facilities for network
sockets, both client-side and server-side. This module uses the OpenSSL

View File

@ -1,4 +1,3 @@
:mod:`stat` --- Interpreting :func:`stat` results
=================================================
@ -6,6 +5,9 @@
:synopsis: Utilities for interpreting the results of os.stat(), os.lstat() and os.fstat().
.. sectionauthor:: Skip Montanaro <skip@automatrix.com>
**Source code:** :source:`Lib/stat.py`
--------------
The :mod:`stat` module defines constants and functions for interpreting the
results of :func:`os.stat`, :func:`os.fstat` and :func:`os.lstat` (if they

View File

@ -7,6 +7,10 @@
.. index:: module: re
**Source code:** :source:`Lib/string.py`
--------------
The :mod:`string` module contains a number of useful constants and
classes, as well as some deprecated legacy functions that are also
available as methods on strings. In addition, Python's built-in string
@ -17,12 +21,6 @@ template strings or the ``%`` operator described in the
:ref:`string-formatting` section. Also, see the :mod:`re` module for
string functions based on regular expressions.
.. seealso::
Latest version of the `string module Python source code
<http://svn.python.org/view/python/branches/release27-maint/Lib/string.py?view=markup>`_
String constants
----------------

View File

@ -1,4 +1,3 @@
:mod:`sunau` --- Read and write Sun AU files
============================================
@ -6,6 +5,9 @@
:synopsis: Provide an interface to the Sun AU sound format.
.. sectionauthor:: Moshe Zadka <moshez@zadka.site.co.il>
**Source code:** :source:`Lib/sunau.py`
--------------
The :mod:`sunau` module provides a convenient interface to the Sun AU sound
format. Note that this module is interface-compatible with the modules

View File

@ -1,4 +1,3 @@
:mod:`symbol` --- Constants used with Python parse trees
========================================================
@ -6,6 +5,9 @@
:synopsis: Constants representing internal nodes of the parse tree.
.. sectionauthor:: Fred L. Drake, Jr. <fdrake@acm.org>
**Source code:** :source:`Lib/symbol.py`
--------------
This module provides constants which represent the numeric values of internal
nodes of the parse tree. Unlike most Python constants, these use lower-case

View File

@ -5,10 +5,15 @@
:synopsis: Python's configuration information
.. moduleauthor:: Tarek Ziade <tarek@ziade.org>
.. sectionauthor:: Tarek Ziade <tarek@ziade.org>
.. versionadded:: 2.7
.. index::
single: configuration information
.. versionadded:: 2.7
**Source code:** :source:`Lib/sysconfig.py`
--------------
The :mod:`sysconfig` module provides access to Python's configuration
information like the list of installation paths and the configuration variables
relevant for the current platform.

View File

@ -9,6 +9,10 @@
.. rudimentary documentation based on module comments
**Source code:** :source:`Lib/tabnanny.py`
--------------
For the time being this module is intended to be called as a script. However it
is possible to import it into an IDE and use the function :func:`check`
described below.

View File

@ -1,5 +1,3 @@
.. _tarfile-mod:
:mod:`tarfile` --- Read and write tar archive files
===================================================
@ -12,6 +10,9 @@
.. moduleauthor:: Lars Gustäbel <lars@gustaebel.de>
.. sectionauthor:: Lars Gustäbel <lars@gustaebel.de>
**Source code:** :source:`Lib/tarfile.py`
--------------
The :mod:`tarfile` module makes it possible to read and write tar
archives, including those using gzip or bz2 compression.

View File

@ -1,4 +1,3 @@
:mod:`telnetlib` --- Telnet client
==================================
@ -9,6 +8,10 @@
.. index:: single: protocol; Telnet
**Source code:** :source:`Lib/telnetlib.py`
--------------
The :mod:`telnetlib` module provides a :class:`Telnet` class that implements the
Telnet protocol. See :rfc:`854` for details about the protocol. In addition, it
provides symbolic constants for the protocol characters (see below), and for the

View File

@ -1,4 +1,3 @@
:mod:`tempfile` --- Generate temporary files and directories
============================================================
@ -13,6 +12,10 @@
pair: temporary; file name
pair: temporary; file
**Source code:** :source:`Lib/tempfile.py`
--------------
This module generates temporary files and directories. It works on all
supported platforms.

View File

@ -1,4 +1,3 @@
:mod:`textwrap` --- Text wrapping and filling
=============================================
@ -7,20 +6,18 @@
.. moduleauthor:: Greg Ward <gward@python.net>
.. sectionauthor:: Greg Ward <gward@python.net>
.. versionadded:: 2.3
**Source code:** :source:`Lib/textwrap.py`
--------------
The :mod:`textwrap` module provides two convenience functions, :func:`wrap` and
:func:`fill`, as well as :class:`TextWrapper`, the class that does all the work,
and a utility function :func:`dedent`. If you're just wrapping or filling one
or two text strings, the convenience functions should be good enough;
otherwise, you should use an instance of :class:`TextWrapper` for efficiency.
.. seealso::
Latest version of the `textwrap module Python source code
<http://svn.python.org/view/python/branches/release27-maint/Lib/textwrap.py?view=markup>`_
.. function:: wrap(text[, width[, ...]])
Wraps the single paragraph in *text* (a string) so every line is at most *width*

View File

@ -4,6 +4,9 @@
.. module:: threading
:synopsis: Higher-level threading interface.
**Source code:** :source:`Lib/threading.py`
--------------
This module constructs higher-level threading interfaces on top of the lower
level :mod:`thread` module.
@ -36,11 +39,6 @@ The :mod:`dummy_threading` module is provided for situations where
:mod:`multiprocessing`. However, threading is still an appropriate model
if you want to run multiple I/O-bound tasks simultaneously.
.. seealso::
Latest version of the `threading module Python source code
<http://svn.python.org/view/python/branches/release27-maint/Lib/threading.py?view=markup>`_
This module defines the following functions and objects:

View File

@ -1,4 +1,3 @@
:mod:`timeit` --- Measure execution time of small code snippets
===============================================================
@ -12,6 +11,10 @@
single: Benchmarking
single: Performance
**Source code:** :source:`Lib/timeit.py`
--------------
This module provides a simple way to time small bits of Python code. It has both
command line as well as callable interfaces. It avoids a number of common traps
for measuring execution times. See also Tim Peters' introduction to the

View File

@ -1,4 +1,3 @@
:mod:`token` --- Constants used with Python parse trees
=======================================================
@ -6,6 +5,9 @@
:synopsis: Constants representing terminal nodes of the parse tree.
.. sectionauthor:: Fred L. Drake, Jr. <fdrake@acm.org>
**Source code:** :source:`Lib/token.py`
--------------
This module provides constants which represent the numeric values of leaf nodes
of the parse tree (terminal tokens). Refer to the file :file:`Grammar/Grammar`

View File

@ -1,4 +1,3 @@
:mod:`tokenize` --- Tokenizer for Python source
===============================================
@ -7,17 +6,15 @@
.. moduleauthor:: Ka Ping Yee
.. sectionauthor:: Fred L. Drake, Jr. <fdrake@acm.org>
**Source code:** :source:`Lib/tokenize.py`
--------------
The :mod:`tokenize` module provides a lexical scanner for Python source code,
implemented in Python. The scanner in this module returns comments as tokens as
well, making it useful for implementing "pretty-printers," including colorizers
for on-screen displays.
.. seealso::
Latest version of the `tokenize module Python source code
<http://svn.python.org/view/python/branches/release27-maint/Lib/tokenize.py?view=markup>`_
The primary entry point is a :term:`generator`:
.. function:: generate_tokens(readline)

View File

@ -1,21 +1,18 @@
:mod:`trace` --- Trace or track Python statement execution
==========================================================
.. module:: trace
:synopsis: Trace or track Python statement execution.
**Source code:** :source:`Lib/trace.py`
--------------
The :mod:`trace` module allows you to trace program execution, generate
annotated statement coverage listings, print caller/callee relationships and
list functions executed during a program run. It can be used in another program
or from the command line.
.. seealso::
Latest version of the `trace module Python source code
<http://svn.python.org/view/python/branches/release27-maint/Lib/trace.py?view=markup>`_
.. _trace-cli:
Command-Line Usage

View File

@ -4,6 +4,9 @@
.. module:: types
:synopsis: Names for built-in types.
**Source code:** :source:`Lib/types.py`
--------------
This module defines names for some object types that are used by the standard
Python interpreter, but not for the types defined by various extension modules.

View File

@ -17,6 +17,9 @@
The :term:`2to3` tool will automatically adapt imports when converting
your sources to 3.0.
**Source code:** :source:`Lib/urlparse.py`
--------------
This module defines a standard interface to break Uniform Resource Locator (URL)
strings up in components (addressing scheme, network location, path etc.), to
@ -33,11 +36,6 @@ following URL schemes: ``file``, ``ftp``, ``gopher``, ``hdl``, ``http``,
.. versionadded:: 2.5
Support for the ``sftp`` and ``sips`` schemes.
.. seealso::
Latest version of the `urlparse module Python source code
<http://svn.python.org/view/python/branches/release27-maint/Lib/urlparse.py?view=markup>`_
The :mod:`urlparse` module defines the following functions:

View File

@ -1,4 +1,3 @@
:mod:`UserDict` --- Class wrapper for dictionary objects
========================================================
@ -6,6 +5,10 @@
:synopsis: Class wrapper for dictionary objects.
**Source code:** :source:`Lib/UserDict.py`
--------------
The module defines a mixin, :class:`DictMixin`, defining all dictionary methods
for classes that already have a minimum mapping interface. This greatly
simplifies writing classes that need to be substitutable for dictionaries (such
@ -19,11 +22,6 @@ available starting with Python version 2.2). Prior to the introduction of
sub-classes that obtained new behaviors by overriding existing methods or adding
new ones.
.. seealso::
Latest version of the `UserDict Python source code
<http://svn.python.org/view/python/branches/release27-maint/Lib/UserDict.py?view=markup>`_
The :mod:`UserDict` module defines the :class:`UserDict` class and
:class:`DictMixin`:

View File

@ -1,4 +1,3 @@
:mod:`uu` --- Encode and decode uuencode files
==============================================
@ -6,6 +5,9 @@
:synopsis: Encode and decode files in uuencode format.
.. moduleauthor:: Lance Ellinghouse
**Source code:** :source:`Lib/uu.py`
--------------
This module encodes and decodes files in uuencode format, allowing arbitrary
binary data to be transferred over ASCII-only connections. Wherever a file
@ -22,11 +24,6 @@ that, when required, the mode is ``'rb'`` or ``'wb'`` on Windows.
This code was contributed by Lance Ellinghouse, and modified by Jack Jansen.
.. seealso::
Latest version of the `uu module Python source code
<http://svn.python.org/view/python/branches/release27-maint/Lib/uu.py?view=markup>`_
The :mod:`uu` module defines the following functions:
@ -62,4 +59,3 @@ The :mod:`uu` module defines the following functions:
Module :mod:`binascii`
Support module containing ASCII-to-binary and binary-to-ASCII conversions.

Some files were not shown because too many files have changed in this diff Show More