remaining compatible with existing code by not removing older features
or syntax. When it's not possible to do that, Python 2.6 tries to do
what it can, adding compatibility functions in a
-:mod:`future_builtins` module and a :option:`!-3` switch to warn about
+:mod:`!future_builtins` module and a :option:`!-3` switch to warn about
usages that will become unsupported in 3.0.
Some significant new packages have been added to the standard library,
Python 3.0 adds several new built-in functions and changes the
semantics of some existing builtins. Functions that are new in 3.0
such as :func:`bin` have simply been added to Python 2.6, but existing
-builtins haven't been changed; instead, the :mod:`future_builtins`
+builtins haven't been changed; instead, the :mod:`!future_builtins`
module has versions with the new 3.0 semantics. Code written to be
compatible with 3.0 can do ``from future_builtins import hex, map`` as
necessary.
about features that will be removed in Python 3.0. You can run code
with this switch to see how much work will be necessary to port
code to 3.0. The value of this switch is available
-to Python code as the boolean variable :data:`sys.py3kwarning`,
+to Python code as the boolean variable :data:`!sys.py3kwarning`,
and to C extension code as :c:data:`!Py_Py3kWarningFlag`.
.. seealso::
The lock is acquired before the block is executed and always released once the
block is complete.
-The :func:`localcontext` function in the :mod:`decimal` module makes it easy
-to save and restore the current decimal context, which encapsulates the desired
-precision and rounding characteristics for computations::
+The :func:`~decimal.localcontext` function in the :mod:`decimal` module makes
+it easy to save and restore the current decimal context, which encapsulates
+the desired precision and rounding characteristics for computations::
from decimal import Decimal, Context, localcontext
A high-level explanation of the context management protocol is:
* The expression is evaluated and should result in an object called a "context
- manager". The context manager must have :meth:`~object.__enter__` and :meth:`~object.__exit__`
- methods.
+ manager". The context manager must have :meth:`~object.__enter__` and
+ :meth:`~object.__exit__` methods.
-* The context manager's :meth:`~object.__enter__` method is called. The value returned
- is assigned to *VAR*. If no ``as VAR`` clause is present, the value is simply
- discarded.
+* The context manager's :meth:`~object.__enter__` method is called. The value
+ returned is assigned to *VAR*. If no ``as VAR`` clause is present, the
+ value is simply discarded.
* The code in *BLOCK* is executed.
The transaction should be committed if the code in the block runs flawlessly or
rolled back if there's an exception. Here's the basic interface for
-:class:`DatabaseConnection` that I'll assume::
+:class:`!DatabaseConnection` that I'll assume::
class DatabaseConnection:
# Database interface
The :mod:`contextlib` module provides some functions and a decorator that
are useful when writing objects for use with the ':keyword:`with`' statement.
-The decorator is called :func:`contextmanager`, and lets you write a single
-generator function instead of defining a new class. The generator should yield
-exactly one value. The code up to the :keyword:`yield` will be executed as the
-:meth:`~object.__enter__` method, and the value yielded will be the method's return
-value that will get bound to the variable in the ':keyword:`with`' statement's
-:keyword:`!as` clause, if any. The code after the :keyword:`!yield` will be
-executed in the :meth:`~object.__exit__` method. Any exception raised in the block will
-be raised by the :keyword:`!yield` statement.
+The decorator is called :func:`~contextlib.contextmanager`, and lets you write
+a single generator function instead of defining a new class. The generator
+should yield exactly one value. The code up to the :keyword:`yield` will be
+executed as the :meth:`~object.__enter__` method, and the value yielded will
+be the method's return value that will get bound to the variable in the
+':keyword:`with`' statement's :keyword:`!as` clause, if any. The code after
+the :keyword:`!yield` will be executed in the :meth:`~object.__exit__` method.
+Any exception raised in the block will be raised by the :keyword:`!yield`
+statement.
Using this decorator, our database example from the previous section
could be written as::
with nested (db_transaction(db), lock) as (cursor, locked):
...
-Finally, the :func:`closing` function returns its argument so that it can be
+Finally, the :func:`~contextlib.closing` function returns its argument so that it can be
bound to a variable, and calls the argument's ``.close()`` method at the end
of the block. ::
environment variable. :envvar:`PYTHONUSERBASE` sets the root
directory used for all Python versions supporting this feature. On
Windows, the directory for application-specific data can be changed by
-setting the :envvar:`APPDATA` environment variable. You can also
+setting the :envvar:`!APPDATA` environment variable. You can also
modify the :file:`site.py` file for your Python installation.
The feature can be disabled entirely by running Python with the
the :mod:`threading` module using processes instead of threads. That
goal was discarded along the path to Python 2.6, but the general
approach of the module is still similar. The fundamental class
-is the :class:`Process`, which is passed a callable object and
-a collection of arguments. The :meth:`start` method
+is the :class:`~multiprocessing.Process`, which is passed a callable object and
+a collection of arguments. The :meth:`~multiprocessing.Process.start` method
sets the callable running in a subprocess, after which you can call
-the :meth:`is_alive` method to check whether the subprocess is still running
-and the :meth:`join` method to wait for the process to exit.
+the :meth:`~multiprocessing.Process.is_alive` method to check whether the
+subprocess is still running and the :meth:`~multiprocessing.Process.join`
+method to wait for the process to exit.
Here's a simple example where the subprocess will calculate a
factorial. The function doing the calculation is written strangely so
the global variable, the child's value would be unaffected, and vice
versa.)
-Two other classes, :class:`Pool` and :class:`Manager`, provide
-higher-level interfaces. :class:`Pool` will create a fixed number of
-worker processes, and requests can then be distributed to the workers
-by calling :meth:`apply` or :meth:`apply_async` to add a single request,
-and :meth:`map` or :meth:`map_async` to add a number of
-requests. The following code uses a :class:`Pool` to spread requests
-across 5 worker processes and retrieve a list of results::
+Two other classes, :class:`~multiprocessing.pool.Pool` and
+:class:`~multiprocessing.Manager`, provide higher-level interfaces.
+:class:`~multiprocessing.pool.Pool` will create a fixed number of worker
+processes, and requests can then be distributed to the workers by calling
+:meth:`~multiprocessing.pool.Pool.apply` or
+:meth:`~multiprocessing.pool.Pool.apply_async` to add a single request, and
+:meth:`~multiprocessing.pool.Pool.map` or
+:meth:`~multiprocessing.pool.Pool.map_async` to add a number of
+requests. The following code uses a :class:`~multiprocessing.pool.Pool` to
+spread requests across 5 worker processes and retrieve a list of results::
from multiprocessing import Pool
33452526613163807108170062053440751665152000000000
...
-The other high-level interface, the :class:`Manager` class, creates a
-separate server process that can hold master copies of Python data
+The other high-level interface, the :class:`~multiprocessing.Manager` class,
+creates a separate server process that can hold master copies of Python data
structures. Other processes can then access and modify these data
structures using proxy objects. The following example creates a
shared dictionary by calling the :meth:`dict` method; the worker
processes then insert values into the dictionary. (Locking is not
done for you automatically, which doesn't matter in this example.
-:class:`Manager`'s methods also include :meth:`Lock`, :meth:`RLock`,
-and :meth:`Semaphore` to create shared locks.)
+:class:`~multiprocessing.Manager`'s methods also include
+:meth:`~multiprocessing.managers.SyncManager.Lock`,
+:meth:`~multiprocessing.managers.SyncManager.RLock`,
+and :meth:`~multiprocessing.managers.SyncManager.Semaphore` to create
+shared locks.)
::
format, followed by a percent sign.
===== ========================================================================
-Classes and types can define a :meth:`__format__` method to control how they're
+Classes and types can define a :meth:`~object.__format__` method to control how they're
formatted. It receives a single argument, the format specifier::
def __format__(self, format_spec):
return str(self)
There's also a :func:`format` builtin that will format a single
-value. It calls the type's :meth:`__format__` method with the
+value. It calls the type's :meth:`~object.__format__` method with the
provided specifier::
>>> format(75.6564, '.2f')
Python's built-in file objects support a number of methods, but
file-like objects don't necessarily support all of them. Objects that
-imitate files usually support :meth:`read` and :meth:`write`, but they
-may not support :meth:`readline`, for example. Python 3.0 introduces
-a layered I/O library in the :mod:`io` module that separates buffering
-and text-handling features from the fundamental read and write
-operations.
+imitate files usually support :meth:`!read` and
+:meth:`!write`, but they may not support :meth:`!readline`,
+for example. Python 3.0 introduces a layered I/O library in the :mod:`io`
+module that separates buffering and text-handling features from the
+fundamental read and write operations.
There are three levels of abstract base classes provided by
the :mod:`io` module:
-* :class:`RawIOBase` defines raw I/O operations: :meth:`read`,
- :meth:`readinto`,
- :meth:`write`, :meth:`seek`, :meth:`tell`, :meth:`truncate`,
- and :meth:`close`.
+* :class:`~io.RawIOBase` defines raw I/O operations: :meth:`~io.RawIOBase.read`,
+ :meth:`~io.RawIOBase.readinto`, :meth:`~io.RawIOBase.write`,
+ :meth:`~io.IOBase.seek`, :meth:`~io.IOBase.tell`, :meth:`~io.IOBase.truncate`,
+ and :meth:`~io.IOBase.close`.
Most of the methods of this class will often map to a single system call.
- There are also :meth:`readable`, :meth:`writable`, and :meth:`seekable`
- methods for determining what operations a given object will allow.
+ There are also :meth:`~io.IOBase.readable`, :meth:`~io.IOBase.writable`,
+ and :meth:`~io.IOBase.seekable` methods for determining what operations a
+ given object will allow.
Python 3.0 has concrete implementations of this class for files and
sockets, but Python 2.6 hasn't restructured its file and socket objects
in this way.
-* :class:`BufferedIOBase` is an abstract base class that
+* :class:`~io.BufferedIOBase` is an abstract base class that
buffers data in memory to reduce the number of
system calls used, making I/O processing more efficient.
- It supports all of the methods of :class:`RawIOBase`,
- and adds a :attr:`raw` attribute holding the underlying raw object.
+ It supports all of the methods of :class:`~io.RawIOBase`,
+ and adds a :attr:`~io.BufferedIOBase.raw` attribute holding the underlying
+ raw object.
There are five concrete classes implementing this ABC.
- :class:`BufferedWriter` and :class:`BufferedReader` are for objects
- that support write-only or read-only usage that have a :meth:`seek`
- method for random access. :class:`BufferedRandom` objects support
+ :class:`~io.BufferedWriter` and :class:`~io.BufferedReader` are for objects
+ that support write-only or read-only usage that have a :meth:`~io.IOBase.seek`
+ method for random access. :class:`~io.BufferedRandom` objects support
read and write access upon the same underlying stream, and
- :class:`BufferedRWPair` is for objects such as TTYs that have both
+ :class:`~io.BufferedRWPair` is for objects such as TTYs that have both
read and write operations acting upon unconnected streams of data.
- The :class:`BytesIO` class supports reading, writing, and seeking
+ The :class:`~io.BytesIO` class supports reading, writing, and seeking
over an in-memory buffer.
.. index::
single: universal newlines; What's new
-* :class:`TextIOBase`: Provides functions for reading and writing
+* :class:`~io.TextIOBase`: Provides functions for reading and writing
strings (remember, strings will be Unicode in Python 3.0),
- and supporting :term:`universal newlines`. :class:`TextIOBase` defines
+ and supporting :term:`universal newlines`. :class:`~io.TextIOBase` defines
the :meth:`readline` method and supports iteration upon
objects.
- There are two concrete implementations. :class:`TextIOWrapper`
+ There are two concrete implementations. :class:`~io.TextIOWrapper`
wraps a buffered I/O object, supporting all of the methods for
- text I/O and adding a :attr:`buffer` attribute for access
- to the underlying object. :class:`StringIO` simply buffers
+ text I/O and adding a :attr:`~io.TextIOBase.buffer` attribute for access
+ to the underlying object. :class:`~io.StringIO` simply buffers
everything in memory without ever writing anything to disk.
(In Python 2.6, :class:`io.StringIO` is implemented in
declaring that a class has a given set of methods or supports a given
access protocol. Abstract Base Classes (or ABCs) are an equivalent
feature for Python. The ABC support consists of an :mod:`abc` module
-containing a metaclass called :class:`ABCMeta`, special handling of
+containing a metaclass called :class:`~abc.ABCMeta`, special handling of
this metaclass by the :func:`isinstance` and :func:`issubclass`
builtins, and a collection of basic ABCs that the Python developers
think will be widely useful. Future versions of Python will probably
dictionary-style access. The phrase "dictionary-style" is vague, however.
It probably means that accessing items with ``obj[1]`` works.
Does it imply that setting items with ``obj[2] = value`` works?
-Or that the object will have :meth:`keys`, :meth:`values`, and :meth:`items`
-methods? What about the iterative variants such as :meth:`iterkeys`? :meth:`copy`
-and :meth:`update`? Iterating over the object with :func:`iter`?
+Or that the object will have :meth:`!keys`, :meth:`!values`, and :meth:`!items`
+methods? What about the iterative variants such as :meth:`!iterkeys`?
+:meth:`!copy`and :meth:`!update`? Iterating over the object with :func:`!iter`?
The Python 2.6 :mod:`collections` module includes a number of
different ABCs that represent these distinctions. :class:`Iterable`
-indicates that a class defines :meth:`__iter__`, and
-:class:`Container` means the class defines a :meth:`__contains__`
+indicates that a class defines :meth:`~object.__iter__`, and
+:class:`Container` means the class defines a :meth:`~object.__contains__`
method and therefore supports ``x in y`` expressions. The basic
dictionary interface of getting items, setting items, and
-:meth:`keys`, :meth:`values`, and :meth:`items`, is defined by the
+:meth:`!keys`, :meth:`!values`, and :meth:`!items`, is defined by the
:class:`MutableMapping` ABC.
You can derive your own classes from a particular ABC
Alternatively, you could write the class without deriving from
the desired ABC and instead register the class by
-calling the ABC's :meth:`register` method::
+calling the ABC's :meth:`~abc.ABCMeta.register` method::
import collections
collections.MutableMapping.register(Storage)
For classes that you write, deriving from the ABC is probably clearer.
-The :meth:`register` method is useful when you've written a new
+The :meth:`~abc.ABCMeta.register` method is useful when you've written a new
ABC that can describe an existing type or class, or if you want
to declare that some third-party class implements an ABC.
-For example, if you defined a :class:`PrintableType` ABC,
+For example, if you defined a :class:`!PrintableType` ABC,
it's legal to do::
# Register Python's types
...
-In the :class:`Drawable` ABC above, the :meth:`draw_doubled` method
+In the :class:`!Drawable` ABC above, the :meth:`!draw_doubled` method
renders the object at twice its size and can be implemented in terms
-of other methods described in :class:`Drawable`. Classes implementing
+of other methods described in :class:`!Drawable`. Classes implementing
this ABC therefore don't need to provide their own implementation
-of :meth:`draw_doubled`, though they can do so. An implementation
-of :meth:`draw` is necessary, though; the ABC can't provide
+of :meth:`!draw_doubled`, though they can do so. An implementation
+of :meth:`!draw` is necessary, though; the ABC can't provide
a useful generic implementation.
-You can apply the ``@abstractmethod`` decorator to methods such as
-:meth:`draw` that must be implemented; Python will then raise an
+You can apply the :deco:`~abc.abstractmethod` decorator to methods such as
+:meth:`!draw` that must be implemented; Python will then raise an
exception for classes that don't define the method.
Note that the exception is only raised when you actually
try to create an instance of a subclass lacking the method::
def readonly(self):
return self._x
-Subclasses must then define a :meth:`readonly` property.
+Subclasses must then define a ``readonly`` property.
.. seealso::
.. ======================================================================
-The :mod:`future_builtins` module
+The :mod:`!future_builtins` module
--------------------------------------
Python 3.0 makes many changes to the repertoire of built-in
functions, and most of the changes can't be introduced in the Python
2.x series because they would break compatibility.
-The :mod:`future_builtins` module provides versions
+The :mod:`!future_builtins` module provides versions
of these built-in functions that can be imported when writing
3.0-compatible code.