summaryrefslogtreecommitdiffstats
path: root/Doc/whatsnew/2.6.rst
diff options
context:
space:
mode:
Diffstat (limited to 'Doc/whatsnew/2.6.rst')
-rw-r--r--Doc/whatsnew/2.6.rst969
1 files changed, 582 insertions, 387 deletions
diff --git a/Doc/whatsnew/2.6.rst b/Doc/whatsnew/2.6.rst
index f3b03e7..21ccf9b 100644
--- a/Doc/whatsnew/2.6.rst
+++ b/Doc/whatsnew/2.6.rst
@@ -1,5 +1,5 @@
****************************
- What's New in Python 2.6
+ What's New in Python 2.6
****************************
.. XXX add trademark info for Apple, Microsoft, SourceForge.
@@ -10,42 +10,42 @@
.. $Id: whatsnew26.tex 55746 2007-06-02 18:33:53Z neal.norwitz $
Rules for maintenance:
-
+
* Anyone can add text to this document. Do not spend very much time
on the wording of your changes, because your text will probably
get rewritten to some degree.
-
+
* The maintainer will go through Misc/NEWS periodically and add
changes; it's therefore more important to add your changes to
Misc/NEWS than to this file.
-
+
* This is not a complete list of every single change; completeness
is the purpose of Misc/NEWS. Some changes I consider too small
or esoteric to include. If such a change is added to the text,
I'll just remove it. (This is another reason you shouldn't spend
too much time on writing your addition.)
-
+
* If you want to draw your new text to the attention of the
maintainer, add 'XXX' to the beginning of the paragraph or
section.
-
+
* It's OK to just add a fragmentary note about a change. For
example: "XXX Describe the transmogrify() function added to the
socket module." The maintainer will research the change and
write the necessary text.
-
+
* You can comment out your additions if you like, but it's not
necessary (especially when a final release is some months away).
-
+
* Credit the author of a patch or bugfix. Just the name is
sufficient; the e-mail address isn't necessary.
-
+
* It's helpful to add the bug/patch number in a parenthetical comment.
-
+
XXX Describe the transmogrify() function added to the socket
module.
(Contributed by P.Y. Developer; :issue:`12345`.)
-
+
This saves the maintainer some effort going through the SVN logs
when researching a change.
@@ -74,7 +74,7 @@ Python 3.0
================
The development cycle for Python 2.6 also saw the release of the first
-alphas of Python 3.0, and the development of 3.0 has influenced
+alphas of Python 3.0, and the development of 3.0 has influenced
a number of features in 2.6.
Python 3.0 is a far-ranging redesign of Python that breaks
@@ -83,7 +83,7 @@ code will need a certain amount of conversion in order to run on
Python 3.0. However, not all the changes in 3.0 necessarily break
compatibility. In cases where new features won't cause existing code
to break, they've been backported to 2.6 and are described in this
-document in the appropriate place. Some of the 3.0-derived features
+document in the appropriate place. Some of the 3.0-derived features
are:
* A :meth:`__complex__` method for converting objects to a complex number.
@@ -94,8 +94,8 @@ are:
A new command-line switch, :option:`-3`, enables warnings
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 ``sys.py3kwarning``,
+code to 3.0. The value of this switch is available
+to Python code as the boolean variable :data:`sys.py3kwarning`,
and to C extension code as :cdata:`Py_Py3kWarningFlag`.
Python 3.0 adds several new built-in functions and change the
@@ -116,9 +116,9 @@ as necessary.
Development Changes
==================================================
-While 2.6 was being developed, the Python development process
-underwent two significant changes: the developer group
-switched from SourceForge's issue tracker to a customized
+While 2.6 was being developed, the Python development process
+underwent two significant changes: the developer group
+switched from SourceForge's issue tracker to a customized
Roundup installation, and the documentation was converted from
LaTeX to reStructuredText.
@@ -135,34 +135,34 @@ The infrastructure committee of the Python Software Foundation
therefore posted a call for issue trackers, asking volunteers to set
up different products and import some of the bugs and patches from
SourceForge. Four different trackers were examined: Atlassian's `Jira
-<http://www.atlassian.com/software/jira/>`__,
-`Launchpad <http://www.launchpad.net>`__,
-`Roundup <http://roundup.sourceforge.net/>`__, and
-`Trac <http://trac.edgewall.org/>`__.
+<http://www.atlassian.com/software/jira/>`__,
+`Launchpad <http://www.launchpad.net>`__,
+`Roundup <http://roundup.sourceforge.net/>`__, and
+`Trac <http://trac.edgewall.org/>`__.
The committee eventually settled on Jira
and Roundup as the two candidates. Jira is a commercial product that
-offers a no-cost hosted instance to free-software projects; Roundup
+offers a no-cost hosted instance to free-software projects; Roundup
is an open-source project that requires volunteers
to administer it and a server to host it.
After posting a call for volunteers, a new Roundup installation was
set up at http://bugs.python.org. One installation of Roundup can
host multiple trackers, and this server now also hosts issue trackers
-for Jython and for the Python web site. It will surely find
+for Jython and for the Python web site. It will surely find
other uses in the future. Where possible,
this edition of "What's New in Python" links to the bug/patch
item for each change.
-Hosting is kindly provided by
-`Upfront Systems <http://www.upfrontsystems.co.za/>`__
+Hosting is kindly provided by
+`Upfront Systems <http://www.upfrontsystems.co.za/>`__
of Stellenbosch, South Africa. Martin von Loewis put a
lot of effort into importing existing bugs and patches from
-SourceForge; his scripts for this import operation are at
+SourceForge; his scripts for this import operation are at
http://svn.python.org/view/tracker/importer/.
.. seealso::
- http://bugs.python.org
+ http://bugs.python.org
The Python bug tracker.
http://bugs.jython.org:
@@ -189,8 +189,8 @@ it online and HTML has become the most important format to support.
Unfortunately, converting LaTeX to HTML is fairly complicated, and
Fred L. Drake Jr., the Python documentation editor for many years,
spent a lot of time wrestling the conversion process into shape.
-Occasionally people would suggest converting the documentation into
-SGML or, later, XML, but performing a good conversion is a major task
+Occasionally people would suggest converting the documentation into
+SGML or, later, XML, but performing a good conversion is a major task
and no one pursued the task to completion.
During the 2.6 development cycle, Georg Brandl put a substantial
@@ -222,7 +222,7 @@ The previous version, Python 2.5, added the ':keyword:`with`'
statement an optional feature, to be enabled by a ``from __future__
import with_statement`` directive. In 2.6 the statement no longer needs to
be specially enabled; this means that :keyword:`with` is now always a
-keyword. The rest of this section is a copy of the corresponding
+keyword. The rest of this section is a copy of the corresponding
section from "What's New in Python 2.5" document; if you read
it back when Python 2.5 came out, you can skip the rest of this
section.
@@ -518,7 +518,7 @@ environment variable.
:pep:`370` - Per-user ``site-packages`` Directory
PEP written and implemented by Christian Heimes.
-
+
.. ======================================================================
.. _pep-0371:
@@ -526,13 +526,27 @@ environment variable.
PEP 371: The ``multiprocessing`` Package
=====================================================
-XXX write this.
+.. XXX I think this still needs help
+
+:mod:`multiprocessing` makes it easy to distribute work over multiple processes.
+Its API is similiar to that of :mod:`threading`. For example::
+
+ from multiprocessing import Process
+
+ def long_hard_task(n):
+ print n * 43
+
+ for i in range(10):
+ Process(target=long_hard_task, args=(i)).start()
+
+will multiply the numbers between 0 and 10 times 43 and print out the result
+concurrently.
.. seealso::
- :pep:`371` - Per-user ``site-packages`` Directory
+ :pep:`371` - Addition of the multiprocessing package
PEP written by Jesse Noller and Richard Oudkerk;
- implemented by Jesse Noller.
+ implemented by Richard Oudkerk and Jesse Noller.
.. ======================================================================
@@ -554,7 +568,7 @@ The formatting template uses curly brackets (`{`, `}`) as special characters::
# Use the named keyword arguments
uid = 'root'
-
+
'User ID: {uid} Last seen: {last_login}'.format(uid='root',
last_login = '5 Mar 2008 07:20') ->
'User ID: root Last seen: 5 Mar 2008 07:20'
@@ -563,8 +577,8 @@ Curly brackets can be escaped by doubling them::
format("Empty dict: {{}}") -> "Empty dict: {}"
-Field names can be integers indicating positional arguments, such as
-``{0}``, ``{1}``, etc. or names of keyword arguments. You can also
+Field names can be integers indicating positional arguments, such as
+``{0}``, ``{1}``, etc. or names of keyword arguments. You can also
supply compound field names that read attributes or access dictionary keys::
import sys
@@ -617,7 +631,7 @@ Character Effect
= (For numeric types only) Pad after the sign.
================ ============================================
-Format specifiers can also include a presentation type, which
+Format specifiers can also include a presentation type, which
controls how the value is formatted. For example, floating-point numbers
can be formatted as a general number or in exponential notation:
@@ -627,8 +641,7 @@ can be formatted as a general number or in exponential notation:
'3.750000e+00'
A variety of presentation types are available. Consult the 2.6
-documentation for a complete list (XXX add link, once it's in the 2.6
-docs), but here's a sample::
+documentation for a :ref:`complete list <formatstrings>`; here's a sample::
'b' - Binary. Outputs the number in base 2.
'c' - Character. Converts the integer to the corresponding
@@ -680,10 +693,10 @@ PEP 3105: ``print`` As a Function
=====================================================
The ``print`` statement becomes the :func:`print` function in Python 3.0.
-Making :func:`print` a function makes it easier to change
-by doing 'def print(...)' or importing a new function from somewhere else.
+Making :func:`print` a function makes it easier to change
+by doing 'def print(...)' or importing a new function from somewhere else.
-Python 2.6 has a ``__future__`` import that removes ``print`` as language
+Python 2.6 has a ``__future__`` import that removes ``print`` as language
syntax, letting you use the functional form instead. For example::
from __future__ import print_function
@@ -697,7 +710,7 @@ The parameters are:
* **args**: positional arguments whose values will be printed out.
* **sep**: the separator, which will be printed between arguments.
- * **end**: the ending text, which will be printed after all of the
+ * **end**: the ending text, which will be printed after all of the
arguments have been output.
* **file**: the file object to which the output will be sent.
@@ -713,7 +726,7 @@ The parameters are:
PEP 3110: Exception-Handling Changes
=====================================================
-One error that Python programmers occasionally make
+One error that Python programmers occasionally make
is the following::
try:
@@ -721,11 +734,11 @@ is the following::
except TypeError, ValueError:
...
-The author is probably trying to catch both
+The author is probably trying to catch both
:exc:`TypeError` and :exc:`ValueError` exceptions, but this code
-actually does something different: it will catch
+actually does something different: it will catch
:exc:`TypeError` and bind the resulting exception object
-to the local name ``"ValueError"``. The correct code
+to the local name ``"ValueError"``. The correct code
would have specified a tuple::
try:
@@ -738,7 +751,7 @@ does it indicate two different nodes in the parse tree, or a single
node that's a tuple.
Python 3.0 changes the syntax to make this unambiguous by replacing
-the comma with the word "as". To catch an exception and store the
+the comma with the word "as". To catch an exception and store the
exception object in the variable ``exc``, you must write::
try:
@@ -763,14 +776,14 @@ work.
PEP 3112: Byte Literals
=====================================================
-Python 3.0 adopts Unicode as the language's fundamental string type, and
-denotes 8-bit literals differently, either as ``b'string'``
-or using a :class:`bytes` constructor. For future compatibility,
+Python 3.0 adopts Unicode as the language's fundamental string type and
+denotes 8-bit literals differently, either as ``b'string'``
+or using a :class:`bytes` constructor. For future compatibility,
Python 2.6 adds :class:`bytes` as a synonym for the :class:`str` type,
and it also supports the ``b''`` notation.
There's also a ``__future__`` import that causes all string literals
-to become Unicode strings. This means that ``\u`` escape sequences
+to become Unicode strings. This means that ``\u`` escape sequences
can be used to include Unicode characters::
@@ -781,7 +794,38 @@ can be used to include Unicode characters::
print len(s) # 12 Unicode characters
-
+At the C level, Python 3.0 will rename the existing 8-bit
+string type, called :ctype:`PyStringObject` in Python 2.x,
+to :ctype:`PyBytesObject`. Python 2.6 uses ``#define``
+to support using the names :cfunc:`PyBytesObject`,
+:cfunc:`PyBytes_Check`, :cfunc:`PyBytes_FromStringAndSize`,
+and all the other functions and macros used with strings.
+
+Instances of the :class:`bytes` type are immutable just
+as strings are. A new :class:`bytearray` type stores a mutable
+sequence of bytes::
+
+ >>> bytearray([65, 66, 67])
+ bytearray(b'ABC')
+ >>> b = bytearray(u'\u21ef\u3244', 'utf-8')
+ >>> b
+ bytearray(b'\xe2\x87\xaf \xe3\x89\x84')
+ >>> b[0] = '\xe3'
+ >>> b
+ bytearray(b'\xe3\x87\xaf \xe3\x89\x84')
+ >>> unicode(str(b), 'utf-8')
+ u'\u31ef \u3244'
+
+Byte arrays support most of the methods of string types, such as
+:meth:`startswith`/:meth:`endswith`, :meth:`find`/:meth:`rfind`,
+and some of the methods of lists, such as :meth:`append`,
+:meth:`pop`, and :meth:`reverse`.
+
+ >>> b = bytearray('ABC')
+ >>> b.append('d')
+ >>> b.append(ord('e'))
+ >>> b
+ bytearray(b'ABCde')
.. seealso::
@@ -806,7 +850,7 @@ 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:`readinto`,
:meth:`write`, :meth:`seek`, :meth:`tell`, :meth:`truncate`,
and :meth:`close`.
Most of the methods of this class will often map to a single system call.
@@ -819,36 +863,36 @@ the :mod:`io` module:
.. XXX should 2.6 register them in io.py?
-* :class:`BufferedIOBase`: is an abstract base class that
- buffers data in memory to reduce the number of
+* :class:`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`,
+ It supports all of the methods of :class:`RawIOBase`,
and adds a :attr:`raw` attribute holding the underlying raw object.
There are four concrete classes implementing this ABC:
- :class:`BufferedWriter` and
+ :class:`BufferedWriter` and
:class:`BufferedReader` for objects that only support
writing or reading and don't support random access,
:class:`BufferedRandom` for objects that support the :meth:`seek` method
for random access,
- and :class:`BufferedRWPair` for objects such as TTYs that have
+ and :class:`BufferedRWPair` for objects such as TTYs that have
both read and write operations that act upon unconnected streams of data.
* :class:`TextIOBase`: Provides functions for reading and writing
strings (remember, strings will be Unicode in Python 3.0),
- and supporting universal newlines. :class:`TextIOBase` defines
- the :meth:`readline` method and supports iteration upon
- objects.
+ and supporting universal newlines. :class:`TextIOBase` defines
+ the :meth:`readline` method and supports iteration upon
+ objects.
There are two concrete implementations. :class:`TextIOWrapper`
wraps a buffered I/O object, supporting all of the methods for
- text I/O and adding a :attr:`buffer` attribute for access
+ text I/O and adding a :attr:`buffer` attribute for access
to the underlying object. :class:`StringIO` simply buffers
everything in memory without ever writing anything to disk.
(In current 2.6 alpha releases, :class:`io.StringIO` is implemented in
- pure Python, so it's pretty slow. You should therefore stick with the
- existing :mod:`StringIO` module or :mod:`cStringIO` for now. At some
+ pure Python, so it's pretty slow. You should therefore stick with the
+ existing :mod:`StringIO` module or :mod:`cStringIO` for now. At some
point Python 3.0's :mod:`io` module will be rewritten into C for speed,
and perhaps the C implementation will be backported to the 2.x releases.)
@@ -856,7 +900,7 @@ the :mod:`io` module:
In Python 2.6, the underlying implementations haven't been
restructured to build on top of the :mod:`io` module's classes. The
-module is being provided to make it easier to write code that's
+module is being provided to make it easier to write code that's
forward-compatible with 3.0, and to save developers the effort of writing
their own implementations of buffering and text I/O.
@@ -875,7 +919,7 @@ PEP 3118: Revised Buffer Protocol
=====================================================
The buffer protocol is a C-level API that lets Python types
-exchange pointers into their internal representations. A
+exchange pointers into their internal representations. A
memory-mapped file can be viewed as a buffer of characters, for
example, and this lets another module such as :mod:`re`
treat memory-mapped files as a string of characters to be searched.
@@ -883,19 +927,19 @@ treat memory-mapped files as a string of characters to be searched.
The primary users of the buffer protocol are numeric-processing
packages such as NumPy, which can expose the internal representation
of arrays so that callers can write data directly into an array instead
-of going through a slower API. This PEP updates the buffer protocol in light of experience
+of going through a slower API. This PEP updates the buffer protocol in light of experience
from NumPy development, adding a number of new features
-such as indicating the shape of an array,
+such as indicating the shape of an array,
locking memory .
-The most important new C API function is
+The most important new C API function is
``PyObject_GetBuffer(PyObject *obj, Py_buffer *view, int flags)``, which
takes an object and a set of flags, and fills in the
-``Py_buffer`` structure with information
+``Py_buffer`` structure with information
about the object's memory representation. Objects
-can use this operation to lock memory in place
+can use this operation to lock memory in place
while an external caller could be modifying the contents,
-so there's a corresponding
+so there's a corresponding
``PyObject_ReleaseBuffer(PyObject *obj, Py_buffer *view)`` to
indicate that the external caller is done.
@@ -903,7 +947,7 @@ The **flags** argument to :cfunc:`PyObject_GetBuffer` specifies
constraints upon the memory returned. Some examples are:
* :const:`PyBUF_WRITABLE` indicates that the memory must be writable.
-
+
* :const:`PyBUF_LOCK` requests a read-only or exclusive lock on the memory.
* :const:`PyBUF_C_CONTIGUOUS` and :const:`PyBUF_F_CONTIGUOUS`
@@ -917,7 +961,7 @@ constraints upon the memory returned. Some examples are:
:pep:`3118` - Revising the buffer protocol
PEP written by Travis Oliphant and Carl Banks; implemented by
Travis Oliphant.
-
+
.. ======================================================================
@@ -929,16 +973,16 @@ PEP 3119: Abstract Base Classes
Some object-oriented languages such as Java support interfaces: declarations
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
+support consists of an :mod:`abc` module containing a metaclass called
:class:`ABCMeta`, special handling
of this metaclass by the :func:`isinstance` and :func:`issubclass` built-ins,
and a collection of basic ABCs that the Python developers think will be widely
useful.
-Let's say you have a particular class and wish to know whether it supports
+Let's say you have a particular class and wish to know whether it supports
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?
+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`?
@@ -947,7 +991,7 @@ Python 2.6 includes a number of different ABCs in the :mod:`collections`
module. :class:`Iterable` indicates that a class defines :meth:`__iter__`,
and :class:`Container` means the class supports ``x in y`` expressions
by defining a :meth:`__contains__` method. The basic dictionary interface of
-getting items, setting items, and
+getting items, setting items, and
:meth:`keys`, :meth:`values`, and :meth:`items`, is defined by the
:class:`MutableMapping` ABC.
@@ -955,22 +999,22 @@ You can derive your own classes from a particular ABC
to indicate they support that ABC's interface::
import collections
-
+
class Storage(collections.MutableMapping):
...
-Alternatively, you could write the class without deriving from
+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::
import collections
-
+
class Storage:
...
-
+
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
ABC that can describe an existing type or class, or if you want
@@ -983,8 +1027,8 @@ it's legal to do:
PrintableType.register(float)
PrintableType.register(str)
-Classes should obey the semantics specified by an ABC, but
-Python can't check this; it's up to the class author to
+Classes should obey the semantics specified by an ABC, but
+Python can't check this; it's up to the class author to
understand the ABC's requirements and to implement the code accordingly.
To check whether an object supports a particular interface, you can
@@ -992,11 +1036,11 @@ now write::
def func(d):
if not isinstance(d, collections.MutableMapping):
- raise ValueError("Mapping object expected, not %r" % d)
+ raise ValueError("Mapping object expected, not %r" % d)
-(Don't feel that you must now begin writing lots of checks as in the
-above example. Python has a strong tradition of duck-typing, where
-explicit type-checking isn't done and code simply calls methods on
+(Don't feel that you must now begin writing lots of checks as in the
+above example. Python has a strong tradition of duck-typing, where
+explicit type-checking isn't done and code simply calls methods on
an object, trusting that those methods will be there and raising an
exception if they aren't. Be judicious in checking for ABCs
and only do it where it helps.)
@@ -1008,46 +1052,46 @@ metaclass in a class definition::
class Drawable():
__metaclass__ = ABCMeta
-
+
def draw(self, x, y, scale=1.0):
pass
def draw_doubled(self, x, y):
self.draw(x, y, scale=2.0)
-
+
class Square(Drawable):
def draw(self, x, y, scale):
...
-
+
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
-this ABC therefore don't need to provide their own implementation
+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
-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 exception for classes that
+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 exception for classes that
don't define the method::
class Drawable():
__metaclass__ = ABCMeta
-
+
@abstractmethod
def draw(self, x, y, scale):
pass
-Note that the exception is only raised when you actually
+Note that the exception is only raised when you actually
try to create an instance of a subclass without the method::
>>> s=Square()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: Can't instantiate abstract class Square with abstract methods draw
- >>>
+ >>>
Abstract data attributes can be declared using the ``@abstractproperty`` decorator::
@@ -1055,7 +1099,7 @@ Abstract data attributes can be declared using the ``@abstractproperty`` decorat
def readonly(self):
return self._x
-Subclasses must then define a :meth:`readonly` property
+Subclasses must then define a :meth:`readonly` property
.. seealso::
@@ -1076,7 +1120,7 @@ which are now prefixed by "0o" or "0O" instead of a leading zero, and
adds support for binary (base-2) integer literals, signalled by a "0b"
or "0B" prefix.
-Python 2.6 doesn't drop support for a leading 0 signalling
+Python 2.6 doesn't drop support for a leading 0 signalling
an octal number, but it does add support for "0o" and "0b"::
>>> 0o21, 2*8 + 1
@@ -1084,8 +1128,8 @@ an octal number, but it does add support for "0o" and "0b"::
>>> 0b101111
47
-The :func:`oct` built-in still returns numbers
-prefixed with a leading zero, and a new :func:`bin`
+The :func:`oct` built-in still returns numbers
+prefixed with a leading zero, and a new :func:`bin`
built-in returns the binary representation for a number::
>>> oct(42)
@@ -1161,36 +1205,36 @@ Exact numbers can represent values precisely and operations never
round off the results or introduce tiny errors that may break the
commutativity and associativity properties; inexact numbers may
perform such rounding or introduce small errors. Integers, long
-integers, and rational numbers are exact, while floating-point
+integers, and rational numbers are exact, while floating-point
and complex numbers are inexact.
:class:`Complex` is a subclass of :class:`Number`. Complex numbers
can undergo the basic operations of addition, subtraction,
multiplication, division, and exponentiation, and you can retrieve the
-real and imaginary parts and obtain a number's conjugate. Python's built-in
+real and imaginary parts and obtain a number's conjugate. Python's built-in
complex type is an implementation of :class:`Complex`.
-:class:`Real` further derives from :class:`Complex`, and adds
-operations that only work on real numbers: :func:`floor`, :func:`trunc`,
-rounding, taking the remainder mod N, floor division,
-and comparisons.
+:class:`Real` further derives from :class:`Complex`, and adds
+operations that only work on real numbers: :func:`floor`, :func:`trunc`,
+rounding, taking the remainder mod N, floor division,
+and comparisons.
:class:`Rational` numbers derive from :class:`Real`, have
:attr:`numerator` and :attr:`denominator` properties, and can be
converted to floats. Python 2.6 adds a simple rational-number class,
-:class:`Fraction`, in the :mod:`fractions` module. (It's called
-:class:`Fraction` instead of :class:`Rational` to avoid
+:class:`Fraction`, in the :mod:`fractions` module. (It's called
+:class:`Fraction` instead of :class:`Rational` to avoid
a name clash with :class:`numbers.Rational`.)
:class:`Integral` numbers derive from :class:`Rational`, and
-can be shifted left and right with ``<<`` and ``>>``,
-combined using bitwise operations such as ``&`` and ``|``,
+can be shifted left and right with ``<<`` and ``>>``,
+combined using bitwise operations such as ``&`` and ``|``,
and can be used as array indexes and slice boundaries.
In Python 3.0, the PEP slightly redefines the existing built-ins
:func:`round`, :func:`math.floor`, :func:`math.ceil`, and adds a new
-one, :func:`math.trunc`, that's been backported to Python 2.6.
-:func:`math.trunc` rounds toward zero, returning the closest
+one, :func:`math.trunc`, that's been backported to Python 2.6.
+:func:`math.trunc` rounds toward zero, returning the closest
:class:`Integral` that's between the function's argument and zero.
.. seealso::
@@ -1201,16 +1245,16 @@ one, :func:`math.trunc`, that's been backported to Python 2.6.
`Scheme's numerical tower <http://www.gnu.org/software/guile/manual/html_node/Numerical-Tower.html#Numerical-Tower>`__, from the Guile manual.
`Scheme's number datatypes <http://schemers.org/Documents/Standards/R5RS/HTML/r5rs-Z-H-9.html#%_sec_6.2>`__ from the R5RS Scheme specification.
-
+
The :mod:`fractions` Module
--------------------------------------------------
-To fill out the hierarchy of numeric types, a rational-number class
-has been added as the :mod:`fractions` module. Rational numbers are
-represented as a fraction, and can exactly represent
-numbers such as two-thirds that floating-point numbers can only
-approximate.
+To fill out the hierarchy of numeric types, a rational-number class is
+provided by the :mod:`fractions` module. Rational numbers store their
+values as a numerator and denominator forming a fraction, and can
+exactly represent numbers such as ``2/3`` that floating-point numbers
+can only approximate.
The :class:`Fraction` constructor takes two :class:`Integral` values
that will be the numerator and denominator of the resulting fraction. ::
@@ -1225,8 +1269,8 @@ that will be the numerator and denominator of the resulting fraction. ::
>>> a/b
Fraction(5, 3)
-To help in converting floating-point numbers to rationals,
-the float type now has a :meth:`as_integer_ratio()` method that returns
+To help in converting floating-point numbers to rationals,
+the float type now has a :meth:`as_integer_ratio()` method that returns
the numerator and denominator for a fraction that evaluates to the same
floating-point value::
@@ -1253,13 +1297,21 @@ Other Language Changes
Here are all of the changes that Python 2.6 makes to the core Python language.
+* The :func:`hasattr` function was catching and ignoring all errors,
+ under the assumption that they meant a :meth:`__getattr__` method
+ was failing somewhere and the return value of :func:`hasattr` would
+ therefore be ``False``. This logic shouldn't be applied to
+ :exc:`KeyboardInterrupt` and :exc:`SystemExit`, however; Python 2.6
+ will no longer discard such exceptions when :func:`hasattr`
+ encounters them. (Fixed by Benjamin Peterson; :issue:`2196`.)
+
* When calling a function using the ``**`` syntax to provide keyword
arguments, you are no longer required to use a Python dictionary;
any mapping will now work::
>>> def f(**kw):
... print sorted(kw)
- ...
+ ...
>>> ud=UserDict.UserDict()
>>> ud['a'] = 1
>>> ud['b'] = 'string'
@@ -1289,21 +1341,21 @@ Here are all of the changes that Python 2.6 makes to the core Python language.
* Properties now have three attributes, :attr:`getter`,
:attr:`setter` and :attr:`deleter`, that are useful shortcuts for
- adding or modifying a getter, setter or deleter function to an
+ adding or modifying a getter, setter or deleter function to an
existing property. You would use them like this::
class C(object):
- @property
- def x(self):
- return self._x
+ @property
+ def x(self):
+ return self._x
- @x.setter
- def x(self, value):
- self._x = value
+ @x.setter
+ def x(self, value):
+ self._x = value
- @x.deleter
- def x(self):
- del self._x
+ @x.deleter
+ def x(self):
+ del self._x
class D(C):
@C.x.getter
@@ -1314,51 +1366,65 @@ Here are all of the changes that Python 2.6 makes to the core Python language.
def x(self, value):
self._x = value / 2
+* Several methods of the built-in set types now accept multiple iterables:
+ :meth:`intersection`,
+ :meth:`intersection_update`,
+ :meth:`union`, :meth:`update`,
+ :meth:`difference` and :meth:`difference_update`.
-* C functions and methods that use
- :cfunc:`PyComplex_AsCComplex` will now accept arguments that
- have a :meth:`__complex__` method. In particular, the functions in the
- :mod:`cmath` module will now accept objects with this method.
- This is a backport of a Python 3.0 change.
- (Contributed by Mark Dickinson; :issue:`1675423`.)
+ ::
+
+ >>> s=set('1234567890')
+ >>> s.intersection('abc123', 'cdf246') # Intersection between all inputs
+ set(['2'])
+ >>> s.difference('246', '789')
+ set(['1', '0', '3', '5'])
+
+ (Contributed by Raymond Hettinger.)
- A numerical nicety: when creating a complex number from two floats
- on systems that support signed zeros (-0 and +0), the
- :func:`complex` constructor will now preserve the sign
- of the zero. (:issue:`1507`)
+* A numerical nicety: when creating a complex number from two floats
+ on systems that support signed zeros (-0 and +0), the
+ :func:`complex` constructor will now preserve the sign
+ of the zero. (Fixed by Mark T. Dickinson; :issue:`1507`)
* More floating-point features were also added. The :func:`float` function
- will now turn the strings ``+nan`` and ``-nan`` into the corresponding
- IEEE 754 Not A Number values, and ``+inf`` and ``-inf`` into
- positive or negative infinity. This works on any platform with
+ will now turn the string ``nan`` into an
+ IEEE 754 Not A Number value, and ``+inf`` and ``-inf`` into
+ positive or negative infinity. This works on any platform with
IEEE 754 semantics. (Contributed by Christian Heimes; :issue:`1635`.)
Other functions in the :mod:`math` module, :func:`isinf` and
:func:`isnan`, return true if their floating-point argument is
infinite or Not A Number. (:issue:`1640`)
-* The :mod:`math` module has seven new functions, and the existing
+* The :mod:`math` module has a number of new functions, and the existing
functions have been improved to give more consistent behaviour
across platforms, especially with respect to handling of
floating-point exceptions and IEEE 754 special values.
- The new functions are:
+ The new functions are:
- * :func:`isinf` and :func:`isnan` determine whether a given float is
- a (positive or negative) infinity or a NaN (Not a Number),
- respectively.
+ * :func:`~math.isinf` and :func:`~math.isnan` determine whether a given float
+ is a (positive or negative) infinity or a NaN (Not a Number), respectively.
- * ``copysign(x, y)`` copies the sign bit of an IEEE 754 number,
+ * :func:`~math.copysign` copies the sign bit of an IEEE 754 number,
returning the absolute value of *x* combined with the sign bit of
*y*. For example, ``math.copysign(1, -0.0)`` returns -1.0.
(Contributed by Christian Heimes.)
- * The inverse hyperbolic functions :func:`acosh`, :func:`asinh` and
- :func:`atanh`.
+ * :func:`~math.factorial` computes the factorial of a number.
+ (Contributed by Raymond Hettinger; :issue:`2138`.)
- * The function :func:`log1p`, returning the natural logarithm of
- *1+x* (base *e*).
+ * :func:`~math.sum` adds up the stream of numbers from an iterable,
+ and is careful to avoid loss of precision by calculating partial sums.
+ (Contributed by Jean Brouwers; :issue:`2819`.)
- There's also a new :func:`trunc` function as a result of the
+ * The inverse hyperbolic functions :func:`~math.acosh`, :func:`~math.asinh`
+ and :func:`~math.atanh`.
+
+ * The function :func:`~math.log1p`, returning the natural logarithm of *1+x*
+ (base *e*).
+
+ There's also a new :func:`trunc` built-in function as a result of the
backport of `PEP 3141's type hierarchy for numbers <#pep-3141>`__.
The existing math functions have been modified to follow the
@@ -1375,31 +1441,31 @@ Here are all of the changes that Python 2.6 makes to the core Python language.
(Contributed by Christian Heimes and Mark Dickinson.)
* Changes to the :class:`Exception` interface
- as dictated by :pep:`352` continue to be made. For 2.6,
+ as dictated by :pep:`352` continue to be made. For 2.6,
the :attr:`message` attribute is being deprecated in favor of the
:attr:`args` attribute.
-* The :exc:`GeneratorExit` exception now subclasses
- :exc:`BaseException` instead of :exc:`Exception`. This means
+* The :exc:`GeneratorExit` exception now subclasses
+ :exc:`BaseException` instead of :exc:`Exception`. This means
that an exception handler that does ``except Exception:``
- will not inadvertently catch :exc:`GeneratorExit`.
+ will not inadvertently catch :exc:`GeneratorExit`.
(Contributed by Chad Austin; :issue:`1537`.)
-* Generator objects now have a :attr:`gi_code` attribute that refers to
- the original code object backing the generator.
+* Generator objects now have a :attr:`gi_code` attribute that refers to
+ the original code object backing the generator.
(Contributed by Collin Winter; :issue:`1473257`.)
* The :func:`compile` built-in function now accepts keyword arguments
as well as positional parameters. (Contributed by Thomas Wouters;
:issue:`1444529`.)
-* The :func:`complex` constructor now accepts strings containing
+* The :func:`complex` constructor now accepts strings containing
parenthesized complex numbers, letting ``complex(repr(cmplx))``
will now round-trip values. For example, ``complex('(3+4j)')``
now returns the value (3+4j). (:issue:`1491866`)
-* The string :meth:`translate` method now accepts ``None`` as the
- translation table parameter, which is treated as the identity
+* The string :meth:`translate` method now accepts ``None`` as the
+ translation table parameter, which is treated as the identity
transformation. This makes it easier to carry out operations
that only delete characters. (Contributed by Bengt Richter;
:issue:`1193128`.)
@@ -1408,7 +1474,7 @@ Here are all of the changes that Python 2.6 makes to the core Python language.
method on the objects it receives. This method must return a list
of strings containing the names of valid attributes for the object,
and lets the object control the value that :func:`dir` produces.
- Objects that have :meth:`__getattr__` or :meth:`__getattribute__`
+ Objects that have :meth:`__getattr__` or :meth:`__getattribute__`
methods can use this to advertise pseudo-attributes they will honor.
(:issue:`1591665`)
@@ -1436,12 +1502,12 @@ Optimizations
* Type objects now have a cache of methods that can reduce
the amount of work required to find the correct method implementation
for a particular class; once cached, the interpreter doesn't need to
- traverse base classes to figure out the right method to call.
- The cache is cleared if a base class or the class itself is modified,
- so the cache should remain correct even in the face of Python's dynamic
+ traverse base classes to figure out the right method to call.
+ The cache is cleared if a base class or the class itself is modified,
+ so the cache should remain correct even in the face of Python's dynamic
nature.
- (Original optimization implemented by Armin Rigo, updated for
- Python 2.6 by Kevin Jacobs; :issue:`1700288`.)
+ (Original optimization implemented by Armin Rigo, updated for
+ Python 2.6 by Kevin Jacobs; :issue:`1700288`.)
* All of the functions in the :mod:`struct` module have been rewritten in
C, thanks to work at the Need For Speed sprint.
@@ -1452,7 +1518,7 @@ Optimizations
these types. (Contributed by Neal Norwitz.)
* Unicode strings now use faster code for detecting
- whitespace and line breaks; this speeds up the :meth:`split` method
+ whitespace and line breaks; this speeds up the :meth:`split` method
by about 25% and :meth:`splitlines` by 35%.
(Contributed by Antoine Pitrou.) Memory usage is reduced
by using pymalloc for the Unicode string's data.
@@ -1469,9 +1535,9 @@ benchmark around XX% faster than Python 2.5.
.. ======================================================================
-.. _new-26-interactive:
+.. _new-26-interpreter:
-Interactive Interpreter Changes
+Interpreter Changes
-------------------------------
Two command-line options have been reserved for use by other Python
@@ -1482,6 +1548,25 @@ specific to a particular implementation of Python such as CPython,
Jython, or IronPython. If either option is used with Python 2.6, the
interpreter will report that the option isn't currently used.
+It's now possible to prevent Python from writing :file:`.pyc` or
+:file:`.pyo` files on importing a module by supplying the :option:`-B`
+switch to the Python interpreter, or by setting the
+:envvar:`PYTHONDONTWRITEBYTECODE` environment variable before running
+the interpreter. This setting is available to Python programs as the
+``sys.dont_write_bytecode`` variable, and can be changed by Python
+code to modify the interpreter's behaviour. (Contributed by Neal
+Norwitz and Georg Brandl.)
+
+The encoding used for standard input, output, and standard error can
+be specified by setting the :envvar:`PYTHONIOENCODING` environment
+variable before running the interpreter. The value should be a string
+in the form ``**encoding**`` or ``**encoding**:**errorhandler**``.
+The **encoding** part specifies the encoding's name, e.g. ``utf-8`` or
+``latin-1``; the optional **errorhandler** part specifies
+what to do with characters that can't be handled by the encoding,
+and should be one of "error", "ignore", or "replace". (Contributed
+by Martin von Loewis.)
+
.. ======================================================================
New, Improved, and Deprecated Modules
@@ -1493,23 +1578,11 @@ by module name. Consult the :file:`Misc/NEWS` file in the source tree for a more
complete list of changes, or look through the Subversion logs for all the
details.
-* (3.0-warning mode) Python 3.0 will feature a reorganized standard
- library; many outdated modules are being dropped,
- and some modules are being renamed or moved into packages.
- Python 2.6 running in 3.0-warning mode will warn about these modules
+* (3.0-warning mode) Python 3.0 will feature a reorganized standard
+ library; many outdated modules are being dropped.
+ Python 2.6 running in 3.0-warning mode will warn about these modules
when they are imported.
- The modules that have been renamed are:
-
- * :mod:`ConfigParser` has become :mod:`configparser`.
- * :mod:`copy_reg` has become :mod:`copyreg`.
- * :mod:`htmlentitydefs` has become :mod:`html.entities`.
- * :mod:`HTMLParser` has become :mod:`html.parser`.
- * :mod:`repr` (the module) has become :mod:`reprlib`.
- * :mod:`SocketServer` has become :mod:`socketserver`.
- * :mod:`Tkinter` has become the :mod:`tkinter` package.
- * :mod:`Queue` has become :mod:`queue`.
-
The list of deprecated modules is:
:mod:`audiodev`,
:mod:`bgenlocations`,
@@ -1526,6 +1599,7 @@ details.
:mod:`imgfile`,
:mod:`linuxaudiodev`,
:mod:`mhlib`,
+ :mod:`mimetools`,
:mod:`multifile`,
:mod:`new`,
:mod:`popen2`,
@@ -1598,6 +1672,11 @@ details.
:mod:`videoreader`,
:mod:`WAIT`.
+* The :mod:`asyncore` and :mod:`asynchat` modules are
+ being actively maintained again, and a number of patches and bugfixes
+ were applied. (Maintained by Josiah Carlson; see :issue:`1736190` for
+ one patch.)
+
* The :mod:`bsddb.dbshelve` module now uses the highest pickling protocol
available, instead of restricting itself to protocol 1.
(Contributed by W. Barnes; :issue:`1551443`.)
@@ -1606,18 +1685,18 @@ details.
thanks to Mark Dickinson and Christian Heimes, that added some new
features and greatly improved the accuracy of the computations.
- Five new functions were added:
+ Five new functions were added:
* :func:`polar` converts a complex number to polar form, returning
- the modulus and argument of that complex number.
+ the modulus and argument of that complex number.
* :func:`rect` does the opposite, turning a (modulus, argument) pair
back into the corresponding complex number.
- * :func:`phase` returns the phase or argument of a complex number.
+ * :func:`phase` returns the phase or argument of a complex number.
* :func:`isnan` returns True if either
- the real or imaginary part of its argument is a NaN.
+ the real or imaginary part of its argument is a NaN.
* :func:`isinf` returns True if either the real or imaginary part of
its argument is infinite.
@@ -1640,7 +1719,7 @@ details.
fieldnames)` is a factory function that creates subclasses of the standard tuple
whose fields are accessible by name as well as index. For example::
- >>> var_type = collections.namedtuple('variable',
+ >>> var_type = collections.namedtuple('variable',
... 'id name type size')
# Names are separated by spaces or commas.
# 'id, name, type, size' would also work.
@@ -1659,15 +1738,15 @@ details.
variable(id=1, name='amplitude', type='int', size=4)
Where the new :class:`namedtuple` type proved suitable, the standard
- library has been modified to return them. For example,
- the :meth:`Decimal.as_tuple` method now returns a named tuple with
+ library has been modified to return them. For example,
+ the :meth:`Decimal.as_tuple` method now returns a named tuple with
:attr:`sign`, :attr:`digits`, and :attr:`exponent` fields.
(Contributed by Raymond Hettinger.)
-* Another change to the :mod:`collections` module is that the
+* Another change to the :mod:`collections` module is that the
:class:`deque` type now supports an optional *maxlen* parameter;
- if supplied, the deque's size will be restricted to no more
+ if supplied, the deque's size will be restricted to no more
than *maxlen* items. Adding more items to a full deque causes
old items to be discarded.
@@ -1706,9 +1785,9 @@ details.
(Contributed by Fabian Kreutz.)
::
- # Boldface text starting at y=0,x=21
+ # Boldface text starting at y=0,x=21
# and affecting the rest of the line.
- stdscr.chgat(0,21, curses.A_BOLD)
+ stdscr.chgat(0,21, curses.A_BOLD)
The :class:`Textbox` class in the :mod:`curses.textpad` module
now supports editing in insert mode as well as overwrite mode.
@@ -1720,7 +1799,7 @@ details.
object, zero-padded on
the left to six places. (Contributed by Skip Montanaro; :issue:`1158`.)
-* The :mod:`decimal` module was updated to version 1.66 of
+* The :mod:`decimal` module was updated to version 1.66 of
`the General Decimal Specification <http://www2.hursley.ibm.com/decimal/decarith.html>`__. New features
include some methods for some basic mathematical functions such as
:meth:`exp` and :meth:`log10`::
@@ -1732,14 +1811,14 @@ details.
>>> Decimal(1000).log10()
Decimal("3")
- The :meth:`as_tuple` method of :class:`Decimal` objects now returns a
+ The :meth:`as_tuple` method of :class:`Decimal` objects now returns a
named tuple with :attr:`sign`, :attr:`digits`, and :attr:`exponent` fields.
-
+
(Implemented by Facundo Batista and Mark Dickinson. Named tuple
support added by Raymond Hettinger.)
-* The :mod:`difflib` module's :class:`SequenceMatcher` class
- now returns named tuples representing matches.
+* The :mod:`difflib` module's :class:`SequenceMatcher` class
+ now returns named tuples representing matches.
In addition to behaving like tuples, the returned values
also have :attr:`a`, :attr:`b`, and :attr:`size` attributes.
(Contributed by Raymond Hettinger.)
@@ -1747,16 +1826,16 @@ details.
* An optional ``timeout`` parameter was added to the
:class:`ftplib.FTP` class constructor as well as the :meth:`connect`
method, specifying a timeout measured in seconds. (Added by Facundo
- Batista.) Also, the :class:`FTP` class's
+ Batista.) Also, the :class:`FTP` class's
:meth:`storbinary` and :meth:`storlines`
- now take an optional *callback* parameter that will be called with
+ now take an optional *callback* parameter that will be called with
each block of data after the data has been sent.
(Contributed by Phil Schwartz; :issue:`1221598`.)
-* The :func:`reduce` built-in function is also available in the
+* The :func:`reduce` built-in function is also available in the
:mod:`functools` module. In Python 3.0, the built-in is dropped and it's
only available from :mod:`functools`; currently there are no plans
- to drop the built-in in the 2.x series. (Patched by
+ to drop the built-in in the 2.x series. (Patched by
Christian Heimes; :issue:`1739906`.)
* When possible, the :mod:`getpass` module will now use
@@ -1772,7 +1851,7 @@ details.
* The :mod:`gopherlib` module has been removed.
-* A new function in the :mod:`heapq` module: ``merge(iter1, iter2, ...)``
+* A new function in the :mod:`heapq` module: ``merge(iter1, iter2, ...)``
takes any number of iterables that return data *in sorted
order*, and returns a new iterator that returns the contents of all
the iterators, also in sorted order. For example::
@@ -1781,7 +1860,7 @@ details.
[1, 2, 3, 5, 8, 9, 16]
Another new function, ``heappushpop(heap, item)``,
- pushes *item* onto *heap*, then pops off and returns the smallest item.
+ pushes *item* onto *heap*, then pops off and returns the smallest item.
This is more efficient than making a call to :func:`heappush` and then
:func:`heappop`.
@@ -1792,18 +1871,18 @@ details.
(Contributed by Raymond Hettinger.)
* An optional ``timeout`` parameter was added to the
- :class:`httplib.HTTPConnection` and :class:`HTTPSConnection`
+ :class:`httplib.HTTPConnection` and :class:`HTTPSConnection`
class constructors, specifying a timeout measured in seconds.
(Added by Facundo Batista.)
-* Most of the :mod:`inspect` module's functions, such as
- :func:`getmoduleinfo` and :func:`getargs`, now return named tuples.
+* Most of the :mod:`inspect` module's functions, such as
+ :func:`getmoduleinfo` and :func:`getargs`, now return named tuples.
In addition to behaving like tuples, the elements of the return value
can also be accessed as attributes.
(Contributed by Raymond Hettinger.)
- Some new functions in the module include
- :func:`isgenerator`, :func:`isgeneratorfunction`,
+ Some new functions in the module include
+ :func:`isgenerator`, :func:`isgeneratorfunction`,
and :func:`isabstract`.
* The :mod:`itertools` module gained several new functions.
@@ -1820,25 +1899,25 @@ details.
every possible combination of the elements returned from each iterable. ::
itertools.product([1,2,3], [4,5,6]) ->
- [(1, 4), (1, 5), (1, 6),
- (2, 4), (2, 5), (2, 6),
+ [(1, 4), (1, 5), (1, 6),
+ (2, 4), (2, 5), (2, 6),
(3, 4), (3, 5), (3, 6)]
The optional *repeat* keyword argument is used for taking the
- product of an iterable or a set of iterables with themselves,
+ product of an iterable or a set of iterables with themselves,
repeated *N* times. With a single iterable argument, *N*-tuples
are returned::
itertools.product([1,2], repeat=3)) ->
- [(1, 1, 1), (1, 1, 2), (1, 2, 1), (1, 2, 2),
+ [(1, 1, 1), (1, 1, 2), (1, 2, 1), (1, 2, 2),
(2, 1, 1), (2, 1, 2), (2, 2, 1), (2, 2, 2)]
With two iterables, *2N*-tuples are returned. ::
itertools(product([1,2], [3,4], repeat=2) ->
- [(1, 3, 1, 3), (1, 3, 1, 4), (1, 3, 2, 3), (1, 3, 2, 4),
- (1, 4, 1, 3), (1, 4, 1, 4), (1, 4, 2, 3), (1, 4, 2, 4),
- (2, 3, 1, 3), (2, 3, 1, 4), (2, 3, 2, 3), (2, 3, 2, 4),
+ [(1, 3, 1, 3), (1, 3, 1, 4), (1, 3, 2, 3), (1, 3, 2, 4),
+ (1, 4, 1, 3), (1, 4, 1, 4), (1, 4, 2, 3), (1, 4, 2, 4),
+ (2, 3, 1, 3), (2, 3, 1, 4), (2, 3, 2, 3), (2, 3, 2, 4),
(2, 4, 1, 3), (2, 4, 1, 4), (2, 4, 2, 3), (2, 4, 2, 4)]
``combinations(iterable, r)`` returns sub-sequences of length *r* from
@@ -1851,35 +1930,35 @@ details.
[('1', '2', '3')]
itertools.combinations('1234', 3) ->
- [('1', '2', '3'), ('1', '2', '4'), ('1', '3', '4'),
+ [('1', '2', '3'), ('1', '2', '4'), ('1', '3', '4'),
('2', '3', '4')]
``permutations(iter[, r])`` returns all the permutations of length *r* of
- the iterable's elements. If *r* is not specified, it will default to the
+ the iterable's elements. If *r* is not specified, it will default to the
number of elements produced by the iterable. ::
itertools.permutations([1,2,3,4], 2) ->
- [(1, 2), (1, 3), (1, 4),
- (2, 1), (2, 3), (2, 4),
- (3, 1), (3, 2), (3, 4),
+ [(1, 2), (1, 3), (1, 4),
+ (2, 1), (2, 3), (2, 4),
+ (3, 1), (3, 2), (3, 4),
(4, 1), (4, 2), (4, 3)]
``itertools.chain(*iterables)`` is an existing function in
:mod:`itertools` that gained a new constructor in Python 2.6.
- ``itertools.chain.from_iterable(iterable)`` takes a single
+ ``itertools.chain.from_iterable(iterable)`` takes a single
iterable that should return other iterables. :func:`chain` will
then return all the elements of the first iterable, then
all the elements of the second, and so on. ::
chain.from_iterable([[1,2,3], [4,5,6]]) ->
[1, 2, 3, 4, 5, 6]
-
+
(All contributed by Raymond Hettinger.)
-* The :mod:`logging` module's :class:`FileHandler` class
+* The :mod:`logging` module's :class:`FileHandler` class
and its subclasses :class:`WatchedFileHandler`, :class:`RotatingFileHandler`,
- and :class:`TimedRotatingFileHandler` now
- have an optional *delay* parameter to its constructor. If *delay*
+ and :class:`TimedRotatingFileHandler` now
+ have an optional *delay* parameter to its constructor. If *delay*
is true, opening of the log file is deferred until the first
:meth:`emit` call is made. (Contributed by Vinay Sajip.)
@@ -1899,16 +1978,16 @@ details.
the forward search.
(Contributed by John Lenton.)
-* The :mod:`operator` module gained a
- :func:`methodcaller` function that takes a name and an optional
- set of arguments, returning a callable that will call
+* The :mod:`operator` module gained a
+ :func:`methodcaller` function that takes a name and an optional
+ set of arguments, returning a callable that will call
the named function on any arguments passed to it. For example::
>>> # Equivalent to lambda s: s.replace('old', 'new')
>>> replacer = operator.methodcaller('replace', 'old', 'new')
>>> replacer('old wine in old bottles')
'new wine in new bottles'
-
+
(Contributed by Georg Brandl, after a suggestion by Gregory Petrosyan.)
The :func:`attrgetter` function now accepts dotted names and performs
@@ -1922,8 +2001,8 @@ details.
(Contributed by Georg Brandl, after a suggestion by Barry Warsaw.)
-* New functions in the :mod:`os` module include
- ``fchmod(fd, mode)``, ``fchown(fd, uid, gid)``,
+* New functions in the :mod:`os` module include
+ ``fchmod(fd, mode)``, ``fchown(fd, uid, gid)``,
and ``lchmod(path, mode)``, on operating systems that support these
functions. :func:`fchmod` and :func:`fchown` let you change the mode
and ownership of an opened file, and :func:`lchmod` changes the mode
@@ -1937,8 +2016,8 @@ details.
parameter's default value is false. Note that the function can fall
into an infinite recursion if there's a symlink that points to a
parent directory. (:issue:`1273829`)
-
-* The ``os.environ`` object's :meth:`clear` method will now unset the
+
+* The ``os.environ`` object's :meth:`clear` method will now unset the
environment variables using :func:`os.unsetenv` in addition to clearing
the object's keys. (Contributed by Martin Horcicka; :issue:`1181`.)
@@ -1954,23 +2033,23 @@ details.
working directory to the destination ``path``. (Contributed by
Richard Barran; :issue:`1339796`.)
- On Windows, :func:`os.path.expandvars` will now expand environment variables
- in the form "%var%", and "~user" will be expanded into the
+ On Windows, :func:`os.path.expandvars` will now expand environment variables
+ in the form "%var%", and "~user" will be expanded into the
user's home directory path. (Contributed by Josiah Carlson;
:issue:`957650`.)
-* The Python debugger provided by the :mod:`pdb` module
+* The Python debugger provided by the :mod:`pdb` module
gained a new command: "run" restarts the Python program being debugged,
and can optionally take new command-line arguments for the program.
(Contributed by Rocky Bernstein; :issue:`1393667`.)
- The :func:`post_mortem` function, used to enter debugging of a
+ The :func:`post_mortem` function, used to enter debugging of a
traceback, will now use the traceback returned by :func:`sys.exc_info`
if no traceback is supplied. (Contributed by Facundo Batista;
:issue:`1106316`.)
-* The :mod:`pickletools` module now has an :func:`optimize` function
- that takes a string containing a pickle and removes some unused
+* The :mod:`pickletools` module now has an :func:`optimize` function
+ that takes a string containing a pickle and removes some unused
opcodes, returning a shorter pickle that contains the same data structure.
(Contributed by Raymond Hettinger.)
@@ -1988,7 +2067,7 @@ details.
+-- StopIteration
+-- StandardError
...'
- >>>
+ >>>
(Contributed by Paul Moore; :issue:`2439`.)
@@ -2005,13 +2084,13 @@ details.
processes faster. (Contributed by Georg Brandl; :issue:`1663329`.)
* The :mod:`pyexpat` module's :class:`Parser` objects now allow setting
- their :attr:`buffer_size` attribute to change the size of the buffer
+ their :attr:`buffer_size` attribute to change the size of the buffer
used to hold character data.
(Contributed by Achim Gaedke; :issue:`1137`.)
* The :mod:`Queue` module now provides queue classes that retrieve entries
- in different orders. The :class:`PriorityQueue` class stores
- queued items in a heap and retrieves them in priority order,
+ in different orders. The :class:`PriorityQueue` class stores
+ queued items in a heap and retrieves them in priority order,
and :class:`LifoQueue` retrieves the most recently added entries first,
meaning that it behaves like a stack.
(Contributed by Raymond Hettinger.)
@@ -2025,20 +2104,24 @@ details.
The new ``triangular(low, high, mode)`` function returns random
numbers following a triangular distribution. The returned values
- are between *low* and *high*, not including *high* itself, and
- with *mode* as the mode, the most frequently occurring value
+ are between *low* and *high*, not including *high* itself, and
+ with *mode* as the mode, the most frequently occurring value
in the distribution. (Contributed by Wladmir van der Laan and
Raymond Hettinger; :issue:`1681432`.)
* Long regular expression searches carried out by the :mod:`re`
module will now check for signals being delivered, so especially
- long searches can now be interrupted.
+ time-consuming searches can now be interrupted.
(Contributed by Josh Hoyt and Ralf Schmitt; :issue:`846388`.)
* The :mod:`rgbimg` module has been removed.
-* The :mod:`sched` module's :class:`scheduler` instances now
- have a read-only :attr:`queue` attribute that returns the
+* The :mod:`rlcompleter` module's :meth:`Completer.complete()` method
+ will now ignore exceptions triggered while evaluating a name.
+ (Fixed by Lorenz Quack; :issue:`2250`.)
+
+* The :mod:`sched` module's :class:`scheduler` instances now
+ have a read-only :attr:`queue` attribute that returns the
contents of the scheduler's queue, represented as a list of
named tuples with the fields ``(time, priority, action, argument)``.
(Contributed by Raymond Hettinger; :issue:`1861`.)
@@ -2047,19 +2130,19 @@ details.
for the Linux :cfunc:`epoll` and BSD :cfunc:`kqueue` system calls.
Also, a :meth:`modify` method was added to the existing :class:`poll`
objects; ``pollobj.modify(fd, eventmask)`` takes a file descriptor
- or file object and an event mask,
-
+ or file object and an event mask,
+
(Contributed by Christian Heimes; :issue:`1657`.)
-* The :mod:`sets` module has been deprecated; it's better to
+* The :mod:`sets` module has been deprecated; it's better to
use the built-in :class:`set` and :class:`frozenset` types.
-* Integrating signal handling with GUI handling event loops
+* Integrating signal handling with GUI handling event loops
like those used by Tkinter or GTk+ has long been a problem; most
software ends up polling, waking up every fraction of a second.
The :mod:`signal` module can now make this more efficient.
Calling ``signal.set_wakeup_fd(fd)`` sets a file descriptor
- to be used; when a signal is received, a byte is written to that
+ to be used; when a signal is received, a byte is written to that
file descriptor. There's also a C-level function,
:cfunc:`PySignal_SetWakeupFd`, for setting the descriptor.
@@ -2068,7 +2151,7 @@ details.
will be passed to :func:`set_wakeup_fd`, and the readable descriptor
will be added to the list of descriptors monitored by the event loop via
:cfunc:`select` or :cfunc:`poll`.
- On receiving a signal, a byte will be written and the main event loop
+ On receiving a signal, a byte will be written and the main event loop
will be woken up, without the need to poll.
(Contributed by Adam Olsen; :issue:`1583`.)
@@ -2086,7 +2169,7 @@ details.
* The :mod:`smtplib` module now supports SMTP over SSL thanks to the
addition of the :class:`SMTP_SSL` class. This class supports an
- interface identical to the existing :class:`SMTP` class. Both
+ interface identical to the existing :class:`SMTP` class. Both
class constructors also have an optional ``timeout`` parameter
that specifies a timeout for the initial connection attempt, measured in
seconds.
@@ -2109,35 +2192,35 @@ details.
environments. TIPC addresses are 4- or 5-tuples.
(Contributed by Alberto Bertogli; :issue:`1646`.)
- A new function, :func:`create_connection`, takes an address
- and connects to it using an optional timeout value, returning
+ A new function, :func:`create_connection`, takes an address
+ and connects to it using an optional timeout value, returning
the connected socket object.
* The base classes in the :mod:`SocketServer` module now support
- calling a :meth:`handle_timeout` method after a span of inactivity
- specified by the server's :attr:`timeout` attribute. (Contributed
- by Michael Pomraning.) The :meth:`serve_forever` method
+ calling a :meth:`handle_timeout` method after a span of inactivity
+ specified by the server's :attr:`timeout` attribute. (Contributed
+ by Michael Pomraning.) The :meth:`serve_forever` method
now takes an optional poll interval measured in seconds,
controlling how often the server will check for a shutdown request.
- (Contributed by Pedro Werneck and Jeffrey Yasskin;
+ (Contributed by Pedro Werneck and Jeffrey Yasskin;
:issue:`742598`, :issue:`1193577`.)
* The :mod:`struct` module now supports the C99 :ctype:`_Bool` type,
- using the format character ``'?'``.
+ using the format character ``'?'``.
(Contributed by David Remahl.)
* The :class:`Popen` objects provided by the :mod:`subprocess` module
now have :meth:`terminate`, :meth:`kill`, and :meth:`send_signal` methods.
On Windows, :meth:`send_signal` only supports the :const:`SIGTERM`
signal, and all these methods are aliases for the Win32 API function
- :cfunc:`TerminateProcess`.
+ :cfunc:`TerminateProcess`.
(Contributed by Christian Heimes.)
-
+
* A new variable in the :mod:`sys` module,
:attr:`float_info`, is an object
containing information about the platform's floating-point support
derived from the :file:`float.h` file. Attributes of this object
- include
+ include
:attr:`mant_dig` (number of digits in the mantissa), :attr:`epsilon`
(smallest difference between 1.0 and the next largest value
representable), and several others. (Contributed by Christian Heimes;
@@ -2149,7 +2232,7 @@ details.
variable is initially set on start-up by supplying the :option:`-B`
switch to the Python interpreter, or by setting the
:envvar:`PYTHONDONTWRITEBYTECODE` environment variable before
- running the interpreter. Python code can subsequently
+ running the interpreter. Python code can subsequently
change the value of this variable to control whether bytecode files
are written or not.
(Contributed by Neal Norwitz and Georg Brandl.)
@@ -2170,12 +2253,12 @@ details.
(Contributed by Robert Schuppenies; :issue:`2898`.)
It's now possible to determine the current profiler and tracer functions
- by calling :func:`sys.getprofile` and :func:`sys.gettrace`.
+ by calling :func:`sys.getprofile` and :func:`sys.gettrace`.
(Contributed by Georg Brandl; :issue:`1648`.)
* The :mod:`tarfile` module now supports POSIX.1-2001 (pax) and
POSIX.1-1988 (ustar) format tarfiles, in addition to the GNU tar
- format that was already supported. The default format
+ format that was already supported. The default format
is GNU tar; specify the ``format`` parameter to open a file
using a different format::
@@ -2190,37 +2273,37 @@ details.
The :meth:`TarFile.add` method now accepts a ``exclude`` argument that's
a function that can be used to exclude certain filenames from
- an archive.
- The function must take a filename and return true if the file
+ an archive.
+ The function must take a filename and return true if the file
should be excluded or false if it should be archived.
The function is applied to both the name initially passed to :meth:`add`
and to the names of files in recursively-added directories.
-
+
(All changes contributed by Lars Gustäbel).
* An optional ``timeout`` parameter was added to the
:class:`telnetlib.Telnet` class constructor, specifying a timeout
measured in seconds. (Added by Facundo Batista.)
-* The :class:`tempfile.NamedTemporaryFile` class usually deletes
- the temporary file it created when the file is closed. This
- behaviour can now be changed by passing ``delete=False`` to the
+* The :class:`tempfile.NamedTemporaryFile` class usually deletes
+ the temporary file it created when the file is closed. This
+ behaviour can now be changed by passing ``delete=False`` to the
constructor. (Contributed by Damien Miller; :issue:`1537850`.)
- A new class, :class:`SpooledTemporaryFile`, behaves like
- a temporary file but stores its data in memory until a maximum size is
- exceeded. On reaching that limit, the contents will be written to
+ A new class, :class:`SpooledTemporaryFile`, behaves like
+ a temporary file but stores its data in memory until a maximum size is
+ exceeded. On reaching that limit, the contents will be written to
an on-disk temporary file. (Contributed by Dustin J. Mitchell.)
The :class:`NamedTemporaryFile` and :class:`SpooledTemporaryFile` classes
- both work as context managers, so you can write
+ both work as context managers, so you can write
``with tempfile.NamedTemporaryFile() as tmp: ...``.
(Contributed by Alexander Belopolsky; :issue:`2021`.)
* The :mod:`test.test_support` module now contains a
:func:`EnvironmentVarGuard`
context manager that supports temporarily changing environment variables and
- automatically restores them to their old values.
+ automatically restores them to their old values.
Another context manager, :class:`TransientResource`, can surround calls
to resources that may or may not be available; it will catch and
@@ -2229,12 +2312,12 @@ details.
external web site::
with test_support.TransientResource(IOError, errno=errno.ETIMEDOUT):
- f = urllib.urlopen('https://sf.net')
+ f = urllib.urlopen('https://sf.net')
...
(Contributed by Brett Cannon.)
-* The :mod:`textwrap` module can now preserve existing whitespace
+* The :mod:`textwrap` module can now preserve existing whitespace
at the beginnings and ends of the newly-created lines
by specifying ``drop_whitespace=False``
as an argument::
@@ -2250,23 +2333,29 @@ details.
has a bunch
of extra
whitespace.
- >>>
+ >>>
(Contributed by Dwayne Bailey; :issue:`1581073`.)
* The :mod:`threading` module's :class:`Thread` objects
gained a :meth:`getIdent` method that returns the thread's
- identifier, a nonzero integer. (Contributed by XXX; :issue:`2871`.)
+ identifier, a nonzero integer. (Contributed by Gregory P. Smith;
+ :issue:`2871`.)
* The :mod:`timeit` module now accepts callables as well as strings
for the statement being timed and for the setup code.
- Two convenience functions were added for creating
- :class:`Timer` instances:
- ``repeat(stmt, setup, time, repeat, number)`` and
+ Two convenience functions were added for creating
+ :class:`Timer` instances:
+ ``repeat(stmt, setup, time, repeat, number)`` and
``timeit(stmt, setup, time, number)`` create an instance and call
the corresponding method. (Contributed by Erik Demaine;
:issue:`1533909`.)
+* The :mod:`Tkinter` module now accepts lists and tuples for options,
+ separating the elements by spaces before passing the resulting value to
+ Tcl/Tk.
+ (Contributed by Guilherme Polo; :issue:`2906`.)
+
* The :mod:`turtle` module for turtle graphics was greatly enhanced by
Gregor Lingl. New features in the module include:
@@ -2287,7 +2376,7 @@ details.
* An optional ``timeout`` parameter was added to the
:func:`urllib.urlopen` function and the
- :class:`urllib.ftpwrapper` class constructor, as well as the
+ :class:`urllib.ftpwrapper` class constructor, as well as the
:func:`urllib2.urlopen` function. The parameter specifies a timeout
measured in seconds. For example::
@@ -2295,11 +2384,11 @@ details.
Traceback (most recent call last):
...
urllib2.URLError: <urlopen error timed out>
- >>>
+ >>>
- (Added by Facundo Batista.)
+ (Added by Facundo Batista.)
-* The :mod:`warnings` module's :func:`formatwarning` and :func:`showwarning`
+* The :mod:`warnings` module's :func:`formatwarning` and :func:`showwarning`
gained an optional *line* argument that can be used to supply the
line of source code. (Added as part of :issue:`1631171`, which re-implemented
part of the :mod:`warnings` module in C code.)
@@ -2308,32 +2397,32 @@ details.
classes can now be prevented from immediately opening and binding to
their socket by passing True as the ``bind_and_activate``
constructor parameter. This can be used to modify the instance's
- :attr:`allow_reuse_address` attribute before calling the
- :meth:`server_bind` and :meth:`server_activate` methods to
+ :attr:`allow_reuse_address` attribute before calling the
+ :meth:`server_bind` and :meth:`server_activate` methods to
open the socket and begin listening for connections.
(Contributed by Peter Parente; :issue:`1599845`.)
:class:`SimpleXMLRPCServer` also has a :attr:`_send_traceback_header`
- attribute; if true, the exception and formatted traceback are returned
- as HTTP headers "X-Exception" and "X-Traceback". This feature is
+ attribute; if true, the exception and formatted traceback are returned
+ as HTTP headers "X-Exception" and "X-Traceback". This feature is
for debugging purposes only and should not be used on production servers
because the tracebacks could possibly reveal passwords or other sensitive
- information. (Contributed by Alan McIntyre as part of his
+ information. (Contributed by Alan McIntyre as part of his
project for Google's Summer of Code 2007.)
* The :mod:`xmlrpclib` module no longer automatically converts
- :class:`datetime.date` and :class:`datetime.time` to the
+ :class:`datetime.date` and :class:`datetime.time` to the
:class:`xmlrpclib.DateTime` type; the conversion semantics were
not necessarily correct for all applications. Code using
- :mod:`xmlrpclib` should convert :class:`date` and :class:`time`
- instances. (:issue:`1330538`) The code can also handle
+ :mod:`xmlrpclib` should convert :class:`date` and :class:`time`
+ instances. (:issue:`1330538`) The code can also handle
dates before 1900 (contributed by Ralf Schmitt; :issue:`2014`)
and 64-bit integers represented by using ``<i8>`` in XML-RPC responses
- (contributed by XXX; :issue:`2985`).
+ (contributed by Riku Lindblad; :issue:`2985`).
-* The :mod:`zipfile` module's :class:`ZipFile` class now has
- :meth:`extract` and :meth:`extractall` methods that will unpack
- a single file or all the files in the archive to the current directory, or
+* The :mod:`zipfile` module's :class:`ZipFile` class now has
+ :meth:`extract` and :meth:`extractall` methods that will unpack
+ a single file or all the files in the archive to the current directory, or
to a specified directory::
z = zipfile.ZipFile('python-251.zip')
@@ -2357,6 +2446,93 @@ details.
.. ======================================================================
.. whole new modules get described in subsections here
+The :mod:`ast` module
+----------------------
+
+The :mod:`ast` module provides an Abstract Syntax Tree representation
+of Python code. For Python 2.6, Armin Ronacher contributed a set of
+helper functions that perform various common tasks. These will be useful
+for HTML templating packages, code analyzers, and similar tools that
+process Python code.
+
+The :func:`parse` function takes an expression and returns an AST.
+The :func:`dump` function outputs a representation of a tree, suitable
+for debugging::
+
+ import ast
+
+ t = ast.parse("""
+ d = {}
+ for i in 'abcdefghijklm':
+ d[i + i] = ord(i) - ord('a') + 1
+ print d
+ """)
+ print ast.dump(t)
+
+This outputs::
+
+ Module(body=[Assign(targets=[Name(id='d', ctx=Store())],
+ value=Dict(keys=[], values=[])), For(target=Name(id='i',
+ ctx=Store()), iter=Str(s='abcdefghijklm'),
+ body=[Assign(targets=[Subscript(value=Name(id='d', ctx=Load()),
+ slice=Index(value=BinOp(left=Name(id='i', ctx=Load()), op=Add(),
+ right=Name(id='i', ctx=Load()))), ctx=Store())],
+ value=BinOp(left=BinOp(left=Call(func=Name(id='ord', ctx=Load()),
+ args=[Name(id='i', ctx=Load())], keywords=[], starargs=None,
+ kwargs=None), op=Sub(), right=Call(func=Name(id='ord',
+ ctx=Load()), args=[Str(s='a')], keywords=[], starargs=None,
+ kwargs=None)), op=Add(), right=Num(n=1)))], orelse=[]),
+ Print(dest=None, values=[Name(id='d', ctx=Load())], nl=True)])
+
+The :func:`literal_eval` method takes a string or an AST
+representing a literal expression, one that contains a Python
+expression containing only strings, numbers, dictionaries, etc. but no
+statements or function calls, and returns the resulting value. If you
+need to unserialize an expression but need to worry about security
+and can't risk using an :func:`eval` call, :func:`literal_eval` will
+handle it safely::
+
+ >>> literal = '("a", "b", {2:4, 3:8, 1:2})'
+ >>> print ast.literal_eval(literal)
+ ('a', 'b', {1: 2, 2: 4, 3: 8})
+ >>> print ast.literal_eval('"a" + "b"')
+ Traceback (most recent call last):
+ ...
+ ValueError: malformed string
+
+The module also includes
+:class:`NodeVisitor` and :class:`NodeTransformer` classes
+for traversing and modifying an AST, and functions for common transformations such as changing line numbers.
+
+.. ======================================================================
+
+The :mod:`future_builtins` module
+--------------------------------------
+
+Python 3.0 makes various 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
+of these built-in functions that can be imported when writing
+3.0-compatible code.
+
+The functions in this module currently include:
+
+* ``ascii(**obj**)``: equivalent to :func:`repr`. In Python 3.0,
+ :func:`repr` will return a Unicode string, while :func:`ascii` will
+ return a pure ASCII bytestring.
+
+* ``filter(**predicate**, **iterable**)``,
+ ``map(**func**, **iterable1**, ...)``: the 3.0 versions
+ return iterators, differing from the 2.x built-ins that return lists.
+
+* ``hex(**value**)``, ``oct(**value**)``: instead of calling the
+ :meth:`__hex__` or :meth:`__oct__` methods, these versions will
+ call the :meth:`__index__` method and convert the result to hexadecimal
+ or octal.
+
+.. ======================================================================
+
The :mod:`json` module
----------------------
@@ -2382,39 +2558,17 @@ types. Pretty-printing of the JSON strings is also supported.
:mod:`json` (originally called simplejson) was written by Bob Ippolito.
-Improved SSL Support
---------------------------------------------------
-
-Bill Janssen made extensive improvements to Python 2.6's support for
-the Secure Sockets Layer by adding a new module, :mod:`ssl`, on top of
-the `OpenSSL <http://www.openssl.org/>`__ library. This new module
-provides more control over the protocol negotiated, the X.509
-certificates used, and has better support for writing SSL servers (as
-opposed to clients) in Python. The existing SSL support in the
-:mod:`socket` module hasn't been removed and continues to work,
-though it will be removed in Python 3.0.
-
-To use the new module, first you must create a TCP connection in the
-usual way and then pass it to the :func:`ssl.wrap_socket` function.
-It's possible to specify whether a certificate is required, and to
-obtain certificate info by calling the :meth:`getpeercert` method.
-
-.. seealso::
-
- The documentation for the :mod:`ssl` module.
-
-
.. ======================================================================
plistlib: A Property-List Parser
--------------------------------------------------
-A commonly-used format on MacOS X is the ``.plist`` format,
-which stores basic data types (numbers, strings, lists,
+A commonly-used format on MacOS X is the ``.plist`` format,
+which stores basic data types (numbers, strings, lists,
and dictionaries) and serializes them into an XML-based format.
(It's a lot like the XML-RPC serialization of data types.)
-Despite being primarily used on MacOS X, the format
+Despite being primarily used on MacOS X, the format
has nothing Mac-specific about it and the Python implementation works
on any platform that Python supports, so the :mod:`plistlib` module
has been promoted to the standard library.
@@ -2442,7 +2596,29 @@ Using the module is simple::
# read/writePlist accepts file-like objects as well as paths.
plistlib.writePlist(data_struct, sys.stdout)
-
+
+.. ======================================================================
+
+Improved SSL Support
+--------------------------------------------------
+
+Bill Janssen made extensive improvements to Python 2.6's support for
+the Secure Sockets Layer by adding a new module, :mod:`ssl`, on top of
+the `OpenSSL <http://www.openssl.org/>`__ library. This new module
+provides more control over the protocol negotiated, the X.509
+certificates used, and has better support for writing SSL servers (as
+opposed to clients) in Python. The existing SSL support in the
+:mod:`socket` module hasn't been removed and continues to work,
+though it will be removed in Python 3.0.
+
+To use the new module, first you must create a TCP connection in the
+usual way and then pass it to the :func:`ssl.wrap_socket` function.
+It's possible to specify whether a certificate is required, and to
+obtain certificate info by calling the :meth:`getpeercert` method.
+
+.. seealso::
+
+ The documentation for the :mod:`ssl` module.
.. ======================================================================
@@ -2456,30 +2632,37 @@ Changes to Python's build process and to the C API include:
See the :file:`PCbuild9` directory for the build files.
(Implemented by Christian Heimes.)
+* On MacOS X, Python 2.6 can be compiled as a 4-way universal build.
+ The :program:`configure` script
+ can take a :option:`--with-universal-archs=[32-bit|64-bit|all]`
+ switch, controlling whether the binaries are built for 32-bit
+ architectures (x86, PowerPC), 64-bit (x86-64 and PPC-64), or both.
+ (Contributed by Ronald Oussoren.)
+
* Python now can only be compiled with C89 compilers (after 19
years!). This means that the Python source tree can now drop its
own implementations of :cfunc:`memmove` and :cfunc:`strerror`, which
are in the C89 standard library.
-* The BerkeleyDB module now has a C API object, available as
+* The BerkeleyDB module now has a C API object, available as
``bsddb.db.api``. This object can be used by other C extensions
that wish to use the :mod:`bsddb` module for their own purposes.
(Contributed by Duncan Grisby; :issue:`1551895`.)
-* The new buffer interface, previously described in
+* The new buffer interface, previously described in
`the PEP 3118 section <#pep-3118-revised-buffer-protocol>`__,
adds :cfunc:`PyObject_GetBuffer` and :cfunc:`PyObject_ReleaseBuffer`,
as well as a few other functions.
* Python's use of the C stdio library is now thread-safe, or at least
as thread-safe as the underlying library is. A long-standing potential
- bug occurred if one thread closed a file object while another thread
- was reading from or writing to the object. In 2.6 file objects
- have a reference count, manipulated by the
+ bug occurred if one thread closed a file object while another thread
+ was reading from or writing to the object. In 2.6 file objects
+ have a reference count, manipulated by the
:cfunc:`PyFile_IncUseCount` and :cfunc:`PyFile_DecUseCount`
- functions. File objects can't be closed unless the reference count
- is zero. :cfunc:`PyFile_IncUseCount` should be called while the GIL
- is still held, before carrying out an I/O operation using the
+ functions. File objects can't be closed unless the reference count
+ is zero. :cfunc:`PyFile_IncUseCount` should be called while the GIL
+ is still held, before carrying out an I/O operation using the
``FILE *`` pointer, and :cfunc:`PyFile_DecUseCount` should be called
immediately after the GIL is re-acquired.
(Contributed by Antoine Pitrou and Gregory P. Smith.)
@@ -2492,39 +2675,46 @@ Changes to Python's build process and to the C API include:
thread, the :exc:`ImportError` is raised.
(Contributed by Christian Heimes.)
-* Several functions return information about the platform's
+* Several functions return information about the platform's
floating-point support. :cfunc:`PyFloat_GetMax` returns
the maximum representable floating point value,
- and :cfunc:`PyFloat_GetMin` returns the minimum
- positive value. :cfunc:`PyFloat_GetInfo` returns a dictionary
+ and :cfunc:`PyFloat_GetMin` returns the minimum
+ positive value. :cfunc:`PyFloat_GetInfo` returns a dictionary
containing more information from the :file:`float.h` file, such as
``"mant_dig"`` (number of digits in the mantissa), ``"epsilon"``
(smallest difference between 1.0 and the next largest value
representable), and several others.
(Contributed by Christian Heimes; :issue:`1534`.)
+* C functions and methods that use
+ :cfunc:`PyComplex_AsCComplex` will now accept arguments that
+ have a :meth:`__complex__` method. In particular, the functions in the
+ :mod:`cmath` module will now accept objects with this method.
+ This is a backport of a Python 3.0 change.
+ (Contributed by Mark Dickinson; :issue:`1675423`.)
+
* Python's C API now includes two functions for case-insensitive string
comparisons, ``PyOS_stricmp(char*, char*)``
and ``PyOS_strnicmp(char*, char*, Py_ssize_t)``.
(Contributed by Christian Heimes; :issue:`1635`.)
-* Many C extensions define their own little macro for adding
- integers and strings to the module's dictionary in the
- ``init*`` function. Python 2.6 finally defines standard macros
+* Many C extensions define their own little macro for adding
+ integers and strings to the module's dictionary in the
+ ``init*`` function. Python 2.6 finally defines standard macros
for adding values to a module, :cmacro:`PyModule_AddStringMacro`
- and :cmacro:`PyModule_AddIntMacro()`. (Contributed by
+ and :cmacro:`PyModule_AddIntMacro()`. (Contributed by
Christian Heimes.)
* Some macros were renamed in both 3.0 and 2.6 to make it clearer that
they are macros,
not functions. :cmacro:`Py_Size()` became :cmacro:`Py_SIZE()`,
:cmacro:`Py_Type()` became :cmacro:`Py_TYPE()`, and
- :cmacro:`Py_Refcnt()` became :cmacro:`Py_REFCNT()`.
+ :cmacro:`Py_Refcnt()` became :cmacro:`Py_REFCNT()`.
The mixed-case macros are still available
in Python 2.6 for backward compatibility.
(:issue:`1629`)
-* Distutils now places C extensions it builds in a
+* Distutils now places C extensions it builds in a
different directory when running on a debug version of Python.
(Contributed by Collin Winter; :issue:`1530959`.)
@@ -2536,7 +2726,7 @@ Changes to Python's build process and to the C API include:
always defined.
* A new Makefile target, "make check", prepares the Python source tree
- for making a patch: it fixes trailing whitespace in all modified
+ for making a patch: it fixes trailing whitespace in all modified
``.py`` files, checks whether the documentation has been changed,
and reports whether the :file:`Misc/ACKS` and :file:`Misc/NEWS` files
have been updated.
@@ -2556,35 +2746,40 @@ Port-Specific Changes: Windows
* The support for Windows 95, 98, ME and NT4 has been dropped.
Python 2.6 requires at least Windows 2000 SP4.
-* The :mod:`msvcrt` module now supports
+* The :mod:`msvcrt` module now supports
both the normal and wide char variants of the console I/O
- API. The :func:`getwch` function reads a keypress and returns a Unicode
+ API. The :func:`getwch` function reads a keypress and returns a Unicode
value, as does the :func:`getwche` function. The :func:`putwch` function
takes a Unicode character and writes it to the console.
(Contributed by Christian Heimes.)
-* :func:`os.path.expandvars` will now expand environment variables
- in the form "%var%", and "~user" will be expanded into the
+* :func:`os.path.expandvars` will now expand environment variables
+ in the form "%var%", and "~user" will be expanded into the
user's home directory path. (Contributed by Josiah Carlson.)
-* The :mod:`socket` module's socket objects now have an
- :meth:`ioctl` method that provides a limited interface to the
+* The :mod:`socket` module's socket objects now have an
+ :meth:`ioctl` method that provides a limited interface to the
:cfunc:`WSAIoctl` system interface.
-* The :mod:`_winreg` module now has a function,
- :func:`ExpandEnvironmentStrings`,
+* The :mod:`_winreg` module now has a function,
+ :func:`ExpandEnvironmentStrings`,
that expands environment variable references such as ``%NAME%``
in an input string. The handle objects provided by this
- module now support the context protocol, so they can be used
+ module now support the context protocol, so they can be used
in :keyword:`with` statements. (Contributed by Christian Heimes.)
- :mod:`_winreg` also has better support for x64 systems,
+ :mod:`_winreg` also has better support for x64 systems,
exposing the :func:`DisableReflectionKey`, :func:`EnableReflectionKey`,
and :func:`QueryReflectionKey` functions, which enable and disable
registry reflection for 32-bit processes running on 64-bit systems.
(:issue:`1753245`)
-* The new default compiler on Windows is Visual Studio 2008 (VS 9.0). The
+* The :mod:`msilib` module's :class:`Record` object
+ gained :meth:`GetInteger` and :meth:`GetString` methods that
+ return field values as an integer or a string.
+ (Contributed by Floris Bruynooghe; :issue:`2125`.)
+
+* The new default compiler on Windows is Visual Studio 2008 (VS 9.0). The
build directories for Visual Studio 2003 (VS7.1) and 2005 (VS8.0)
were moved into the PC/ directory. The new PCbuild directory supports
cross compilation for X64, debug builds and Profile Guided Optimization
@@ -2617,7 +2812,7 @@ Python 2.5 and 2.6. Both figures are likely to be underestimates.
Some of the more notable changes are:
-* It's now possible to prevent Python from writing any :file:`.pyc`
+* It's now possible to prevent Python from writing any :file:`.pyc`
or :file:`.pyo` files by either supplying the :option:`-B` switch
or setting the :envvar:`PYTHONDONTWRITEBYTECODE` environment variable
to any non-empty string when running the Python interpreter. These
@@ -2638,23 +2833,23 @@ that may require changes to your code:
* The :meth:`__init__` method of :class:`collections.deque`
now clears any existing contents of the deque
before adding elements from the iterable. This change makes the
- behavior match that of ``list.__init__()``.
+ behavior match that of ``list.__init__()``.
-* The :class:`Decimal` constructor now accepts leading and trailing
+* The :class:`Decimal` constructor now accepts leading and trailing
whitespace when passed a string. Previously it would raise an
:exc:`InvalidOperation` exception. On the other hand, the
:meth:`create_decimal` method of :class:`Context` objects now
- explicitly disallows extra whitespace, raising a
+ explicitly disallows extra whitespace, raising a
:exc:`ConversionSyntax` exception.
-* Due to an implementation accident, if you passed a file path to
+* Due to an implementation accident, if you passed a file path to
the built-in :func:`__import__` function, it would actually import
- the specified file. This was never intended to work, however, and
- the implementation now explicitly checks for this case and raises
+ the specified file. This was never intended to work, however, and
+ the implementation now explicitly checks for this case and raises
an :exc:`ImportError`.
* C API: the :cfunc:`PyImport_Import` and :cfunc:`PyImport_ImportModule`
- functions now default to absolute imports, not relative imports.
+ functions now default to absolute imports, not relative imports.
This will affect C extensions that import other modules.
* The :mod:`socket` module exception :exc:`socket.error` now inherits
@@ -2663,21 +2858,21 @@ that may require changes to your code:
(Implemented by Gregory P. Smith; :issue:`1706815`.)
* The :mod:`xmlrpclib` module no longer automatically converts
- :class:`datetime.date` and :class:`datetime.time` to the
+ :class:`datetime.date` and :class:`datetime.time` to the
:class:`xmlrpclib.DateTime` type; the conversion semantics were
not necessarily correct for all applications. Code using
- :mod:`xmlrpclib` should convert :class:`date` and :class:`time`
+ :mod:`xmlrpclib` should convert :class:`date` and :class:`time`
instances. (:issue:`1330538`)
-* (3.0-warning mode) The :class:`Exception` class now warns
- when accessed using slicing or index access; having
+* (3.0-warning mode) The :class:`Exception` class now warns
+ when accessed using slicing or index access; having
:class:`Exception` behave like a tuple is being phased out.
* (3.0-warning mode) inequality comparisons between two dictionaries
or two objects that don't implement comparison methods are reported
as warnings. ``dict1 == dict2`` still works, but ``dict1 < dict2``
is being phased out.
-
+
Comparisons between cells, which are an implementation detail of Python's
scoping rules, also cause warnings because such comparisons are forbidden
entirely in 3.0.
@@ -2691,6 +2886,6 @@ Acknowledgements
================
The author would like to thank the following people for offering suggestions,
-corrections and assistance with various drafts of this article:
+corrections and assistance with various drafts of this article:
Georg Brandl, Jim Jewett.