cpython/Doc/whatsnew/2.6.rst

1443 lines
54 KiB
ReStructuredText
Raw Normal View History

2007-08-15 11:28:01 -03:00
****************************
What's New in Python 2.6
****************************
2007-12-29 06:57:00 -04:00
.. XXX mention switch to Roundup for bug tracking
2007-09-13 19:49:34 -03:00
2007-08-15 11:28:01 -03:00
:Author: A.M. Kuchling
:Release: |release|
:Date: |today|
2007-12-29 06:57:00 -04:00
.. $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 as a comment:
% Patch 12345
XXX Describe the transmogrify() function added to the socket
module.
(Contributed by P.Y. Developer.)
This saves the maintainer the effort of going through the SVN log
when researching a change.
2007-08-15 11:28:01 -03:00
This article explains the new features in Python 2.6. No release date for
Python 2.6 has been set; it will probably be released in mid 2008.
This article doesn't attempt to provide a complete specification of the new
features, but instead provides a convenient overview. For full details, you
should refer to the documentation for Python 2.6. If you want to understand the
complete implementation and design rationale, refer to the PEP for a particular
new feature.
2007-12-29 06:57:00 -04:00
.. Compare with previous release in 2 - 3 sentences here.
add hyperlink when the documentation becomes available online.
2007-08-15 11:28:01 -03:00
2007-12-29 06:57:00 -04:00
.. ========================================================================
.. Large, PEP-level features and changes should be described here.
.. Should there be a new section here for 3k migration?
.. Or perhaps a more general section describing module changes/deprecation?
.. ========================================================================
2007-08-15 11:28:01 -03:00
2007-09-13 19:49:34 -03:00
Python 3.0
================
2007-09-24 21:09:42 -03:00
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
a number of features in 2.6.
Python 3.0 is a far-ranging redesign of Python that breaks
compatibility with the 2.x series. This means that existing Python
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
are:
* A :meth:`__complex__` method for converting objects to a complex number.
* Alternate syntax for catching exceptions: ``except TypeError as exc``.
* The addition of :func:`functools.reduce` as a synonym for the built-in
:func:`reduce` function.
2007-09-13 19:49:34 -03:00
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
2007-12-18 22:02:04 -04:00
code to 3.0. The value of this switch is available
to Python code as the boolean variable ``sys.py3kwarning``,
and to C extension code as :cdata:`Py_Py3kWarningFlag`.
2007-09-13 19:49:34 -03:00
.. seealso::
The 3xxx series of PEPs, which describes the development process for
Python 3.0 and various features that have been accepted, rejected,
or are still under consideration.
2007-12-18 22:02:04 -04:00
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
Roundup installation, and the documentation was converted from
LaTeX to reStructured Text.
New Issue Tracker: Roundup
--------------------------------------------------
XXX write this.
New Documentation Format: ReStructured Text
--------------------------------------------------
Python's documentation had been written using LaTeX since the
project's inception around 1989. At that time, most documentation was
printed out for later study, not viewed online. LaTeX was widely used
because it provided attractive printed output while
remaining straightforward to write, once the basic rules
of the markup have been learned.
LaTeX is still used today for writing technical publications destined
for printing, but the landscape for programming tools has shifted. We
no longer print out reams of documentation; instead, we browse through
it online and HTML is 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
and no one pursued the task to completion.
During the 2.6 development cycle, Georg Brandl put a substantial
effort into building a new toolchain called Sphinx
for processing the documentation.
The input format is reStructured Text,
a markup commonly used in the Python community that supports
custom extensions and directives. Sphinx concentrates
2007-12-22 13:27:02 -04:00
on HTML output, producing attractively styled
and modern HTML, but printed output is still supported through
conversion to LaTeX as an output format.
2007-12-18 22:02:04 -04:00
.. seealso::
`Docutils <http://docutils.sf.net>`__: The fundamental
reStructured Text parser and toolset.
2007-12-29 06:57:00 -04:00
:ref:`documenting-index`: Describes how to write for
2007-12-18 22:02:04 -04:00
Python's documentation.
2007-09-13 19:49:34 -03:00
PEP 343: The 'with' statement
=============================
The previous version, Python 2.5, added the ':keyword:`with`'
statement an optional feature, to be enabled by a ``from __future__
2007-12-03 17:28:41 -04:00
import with_statement`` directive. In 2.6 the statement no longer needs to
2007-09-13 19:49:34 -03:00
be specially enabled; this means that :keyword:`with` is now always a
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.
The ':keyword:`with`' statement clarifies code that previously would use
``try...finally`` blocks to ensure that clean-up code is executed. In this
section, I'll discuss the statement as it will commonly be used. In the next
section, I'll examine the implementation details and show how to write objects
for use with this statement.
The ':keyword:`with`' statement is a new control-flow structure whose basic
structure is::
with expression [as variable]:
with-block
The expression is evaluated, and it should result in an object that supports the
context management protocol (that is, has :meth:`__enter__` and :meth:`__exit__`
methods.
The object's :meth:`__enter__` is called before *with-block* is executed and
therefore can run set-up code. It also may return a value that is bound to the
name *variable*, if given. (Note carefully that *variable* is *not* assigned
the result of *expression*.)
After execution of the *with-block* is finished, the object's :meth:`__exit__`
method is called, even if the block raised an exception, and can therefore run
clean-up code.
Some standard Python objects now support the context management protocol and can
be used with the ':keyword:`with`' statement. File objects are one example::
with open('/etc/passwd', 'r') as f:
for line in f:
print line
... more processing code ...
After this statement has executed, the file object in *f* will have been
automatically closed, even if the :keyword:`for` loop raised an exception part-
way through the block.
.. note::
In this case, *f* is the same object created by :func:`open`, because
:meth:`file.__enter__` returns *self*.
The :mod:`threading` module's locks and condition variables also support the
':keyword:`with`' statement::
lock = threading.Lock()
with lock:
# Critical section of code
...
The lock is acquired before the block is executed and always released once the
block is complete.
The new :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::
from decimal import Decimal, Context, localcontext
# Displays with default precision of 28 digits
v = Decimal('578')
print v.sqrt()
with localcontext(Context(prec=16)):
# All code in this block uses a precision of 16 digits.
# The original context is restored on exiting the block.
print v.sqrt()
.. _new-26-context-managers:
Writing Context Managers
------------------------
Under the hood, the ':keyword:`with`' statement is fairly complicated. Most
people will only use ':keyword:`with`' in company with existing objects and
don't need to know these details, so you can skip the rest of this section if
you like. Authors of new objects will need to understand the details of the
underlying implementation and should keep reading.
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:`__enter__` and :meth:`__exit__`
methods.
* The context manager's :meth:`__enter__` method is called. The value returned
2007-12-16 19:15:07 -04:00
is assigned to *VAR*. If no ``as VAR`` clause is present, the value is simply
2007-09-13 19:49:34 -03:00
discarded.
* The code in *BLOCK* is executed.
* If *BLOCK* raises an exception, the :meth:`__exit__(type, value, traceback)`
is called with the exception details, the same values returned by
:func:`sys.exc_info`. The method's return value controls whether the exception
is re-raised: any false value re-raises the exception, and ``True`` will result
in suppressing it. You'll only rarely want to suppress the exception, because
if you do the author of the code containing the ':keyword:`with`' statement will
never realize anything went wrong.
* If *BLOCK* didn't raise an exception, the :meth:`__exit__` method is still
called, but *type*, *value*, and *traceback* are all ``None``.
Let's think through an example. I won't present detailed code but will only
sketch the methods necessary for a database that supports transactions.
(For people unfamiliar with database terminology: a set of changes to the
database are grouped into a transaction. Transactions can be either committed,
meaning that all the changes are written into the database, or rolled back,
meaning that the changes are all discarded and the database is unchanged. See
any database textbook for more information.)
Let's assume there's an object representing a database connection. Our goal will
be to let the user write code like this::
db_connection = DatabaseConnection()
with db_connection as cursor:
cursor.execute('insert into ...')
cursor.execute('delete from ...')
# ... more operations ...
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:
# Database interface
2007-12-16 19:13:29 -04:00
def cursor(self):
2007-09-13 19:49:34 -03:00
"Returns a cursor object and starts a new transaction"
2007-12-16 19:13:29 -04:00
def commit(self):
2007-09-13 19:49:34 -03:00
"Commits current transaction"
2007-12-16 19:13:29 -04:00
def rollback(self):
2007-09-13 19:49:34 -03:00
"Rolls back current transaction"
The :meth:`__enter__` method is pretty easy, having only to start a new
transaction. For this application the resulting cursor object would be a useful
result, so the method will return it. The user can then add ``as cursor`` to
their ':keyword:`with`' statement to bind the cursor to a variable name. ::
class DatabaseConnection:
...
2007-12-16 19:13:29 -04:00
def __enter__(self):
2007-09-13 19:49:34 -03:00
# Code to start a new transaction
cursor = self.cursor()
return cursor
The :meth:`__exit__` method is the most complicated because it's where most of
the work has to be done. The method has to check if an exception occurred. If
there was no exception, the transaction is committed. The transaction is rolled
back if there was an exception.
In the code below, execution will just fall off the end of the function,
returning the default value of ``None``. ``None`` is false, so the exception
will be re-raised automatically. If you wished, you could be more explicit and
add a :keyword:`return` statement at the marked location. ::
class DatabaseConnection:
...
2007-12-16 19:13:29 -04:00
def __exit__(self, type, value, tb):
2007-09-13 19:49:34 -03:00
if tb is None:
# No exception, so commit
self.commit()
else:
# Exception occurred, so rollback.
self.rollback()
# return False
.. _module-contextlib:
The contextlib module
---------------------
The new :mod:`contextlib` module provides some functions and a decorator that
are useful for 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:`__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:`__exit__` method. Any exception raised in the block will
be raised by the :keyword:`yield` statement.
Our database example from the previous section could be written using this
decorator as::
from contextlib import contextmanager
@contextmanager
2007-12-16 19:13:29 -04:00
def db_transaction(connection):
2007-09-13 19:49:34 -03:00
cursor = connection.cursor()
try:
yield cursor
except:
connection.rollback()
raise
else:
connection.commit()
db = DatabaseConnection()
with db_transaction(db) as cursor:
...
The :mod:`contextlib` module also has a :func:`nested(mgr1, mgr2, ...)` function
that combines a number of context managers so you don't need to write nested
':keyword:`with`' statements. In this example, the single ':keyword:`with`'
statement both starts a database transaction and acquires a thread lock::
lock = threading.Lock()
with nested (db_transaction(db), lock) as (cursor, locked):
...
Finally, the :func:`closing(object)` function returns *object* so that it can be
bound to a variable, and calls ``object.close`` at the end of the block. ::
import urllib, sys
from contextlib import closing
with closing(urllib.urlopen('http://www.yahoo.com')) as f:
for line in f:
sys.stdout.write(line)
.. seealso::
:pep:`343` - The "with" statement
PEP written by Guido van Rossum and Nick Coghlan; implemented by Mike Bland,
Guido van Rossum, and Neal Norwitz. The PEP shows the code generated for a
':keyword:`with`' statement, which can be helpful in learning how the statement
works.
The documentation for the :mod:`contextlib` module.
2007-12-29 06:57:00 -04:00
.. ======================================================================
2007-09-13 19:49:34 -03:00
2007-12-18 22:02:04 -04:00
.. _pep-0366:
PEP 366: Explicit Relative Imports From a Main Module
============================================================
Python's :option:`-m` switch allows running a module as a script.
When you ran a module that was located inside a package, relative
imports didn't work correctly.
The fix in Python 2.6 adds a :attr:`__package__` attribute to modules.
When present, relative imports will be relative to the value of this
attribute instead of the :attr:`__name__` attribute. PEP 302-style
importers can then set :attr:`__package__`. The :mod:`runpy` module
that implements the :option:`-m` switch now does this, so relative imports
can now be used in scripts running from inside a package.
2008-01-14 21:47:32 -04:00
.. ======================================================================
.. ::
.. _pep-0370:
PEP 370: XXX
=====================================================
When you run Python, the module search page ``sys.modules`` usually
includes a directory whose path ends in ``"site-packages"``. This
directory is intended to hold locally-installed packages available to
all users on a machine or using a particular site installation.
Python 2.6 introduces a convention for user-specific site directories.
.. seealso::
:pep:`370` - XXX
PEP written by XXX; implemented by Christian Heimes.
2007-12-29 06:57:00 -04:00
.. ======================================================================
2007-12-18 22:02:04 -04:00
2007-09-13 19:49:34 -03:00
.. _pep-3110:
PEP 3110: Exception-Handling Changes
=====================================================
One error that Python programmers occasionally make
is the following::
try:
...
except TypeError, ValueError:
...
The author is probably trying to catch both
:exc:`TypeError` and :exc:`ValueError` exceptions, but this code
actually does something different: it will catch
:exc:`TypeError` and bind the resulting exception object
to the local name ``"ValueError"``. The correct code
would have specified a tuple::
try:
...
except (TypeError, ValueError):
...
This error is possible because the use of the comma here is ambiguous:
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
exception object in the variable ``exc``, you must write::
try:
...
except TypeError as exc:
...
Python 3.0 will only support the use of "as", and therefore interprets
the first example as catching two different exceptions. Python 2.6
supports both the comma and "as", so existing code will continue to
work.
.. seealso::
:pep:`3110` - Catching Exceptions in Python 3000
PEP written and implemented by Collin Winter.
2007-12-29 06:57:00 -04:00
.. ======================================================================
2007-09-13 19:49:34 -03:00
.. _pep-3119:
PEP 3119: Abstract Base Classes
=====================================================
XXX
2008-01-03 22:31:40 -04:00
How to identify a file object?
ABCs are a collection of classes describing various interfaces.
Classes can derive from an ABC to indicate they support that ABC's
interface. Concrete classes should obey the semantics specified by
an ABC, but Python can't check this; it's up to the implementor.
A metaclass lets you declare that an existing class or type
derives from a particular ABC. You can even
class AppendableSequence:
__metaclass__ = ABCMeta
AppendableSequence.register(list)
assert issubclass(list, AppendableSequence)
assert isinstance([], AppendableSequence)
@abstractmethod decorator -- you can't instantiate classes w/
an abstract method.
2008-01-04 14:24:41 -04:00
::
@abstractproperty decorator
@abstractproperty
def readonly(self):
return self._x
2008-01-03 22:31:40 -04:00
2007-09-13 19:49:34 -03:00
.. seealso::
:pep:`3119` - Introducing Abstract Base Classes
PEP written by Guido van Rossum and Talin.
Implemented by XXX.
2007-12-18 22:02:04 -04:00
Backported to 2.6 by Benjamin Aranguren, with Alex Martelli.
2007-08-15 11:28:01 -03:00
2008-01-15 23:17:25 -04:00
.. ======================================================================
.. _pep-3141:
PEP 3141: A Type Hierarchy for Numbers
=====================================================
In Python 3.0, several abstract base classes for numeric types,
inspired by Scheme's numeric tower, are being added.
2008-01-15 23:17:25 -04:00
This change was backported to 2.6 as the :mod:`numbers` module.
The most general ABC is :class:`Number`. It defines no operations at
all, and only exists to allow checking if an object is a number by
doing ``isinstance(obj, Number)``.
Numbers are further divided into :class:`Exact` and :class:`Inexact`.
Exact numbers can represent values precisely and operations never
round off the results or introduce tiny errors that may break the
communtativity and associativity properties; inexact numbers may
perform such rounding or introduce small errors. Integers, long
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
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:`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
in the :mod:`rational` module.
:class:`Integral` numbers derive from :class:`Rational`, 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:`math.floor`, :func:`math.ceil`, :func:`round`, and adds a new
one, :func:`trunc`, that's been backported to Python 2.6.
:func:`trunc` rounds toward zero, returning the closest
:class:`Integral` that's between the function's argument and zero.
2008-01-15 23:17:25 -04:00
.. seealso::
2008-01-15 23:17:25 -04:00
XXX link: Discusses Scheme's numeric tower.
2008-01-15 23:17:25 -04:00
2008-01-15 23:17:25 -04:00
The Rational Module
--------------------------------------------------
To fill out the hierarchy of numeric types, a rational-number class
has been added as the :mod:`rational` module. Rational numbers are
represented as a fraction; rational numbers can exactly represent
numbers such as two-thirds that floating-point numbers can only
approximate.
The :class:`Rational` constructor takes two :class:`Integral` values
that will be the numerator and denominator of the resulting fraction. ::
>>> from rational import Rational
>>> a = Rational(2, 3)
>>> b = Rational(2, 5)
>>> float(a), float(b)
(0.66666666666666663, 0.40000000000000002)
>>> a+b
rational.Rational(16,15)
>>> a/b
rational.Rational(5,3)
The :mod:`rational` module is based upon an implementation by Sjoerd
Mullender that was in Python's :file:`Demo/classes/` directory for a
long time. This implementation was significantly updated by Jeffrey
Yaskin.
2007-08-15 11:28:01 -03:00
Other Language Changes
======================
Here are all of the changes that Python 2.6 makes to the core Python language.
2007-09-13 19:49:34 -03:00
* 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'
>>> f(**ud)
['a', 'b']
2007-12-29 06:57:00 -04:00
.. Patch 1686487
2007-09-13 19:49:34 -03:00
2007-09-24 21:09:42 -03:00
* The built-in types now have improved support for extended slicing syntax,
where various combinations of ``(start, stop, step)`` are supplied.
Previously, the support was partial and certain corner cases wouldn't work.
(Implemented by Thomas Wouters.)
2007-12-29 06:57:00 -04:00
.. Revision 57619
2007-09-24 21:09:42 -03:00
* Properties now have three attributes, :attr:`getter`,
2007-12-18 22:02:04 -04:00
:attr:`setter` and :attr:`deleter`, that are useful shortcuts for
adding or modifying a getter, setter or deleter function to an
existing property. You would use them like this::
2007-12-18 22:02:04 -04:00
class C(object):
@property
def x(self):
return self._x
@x.setter
def x(self, value):
self._x = value
@x.deleter
def x(self):
del self._x
class D(C):
@C.x.getter
def x(self):
return self._x * 2
@x.setter
def x(self, value):
self._x = value / 2
2007-12-18 22:02:04 -04:00
2007-09-24 21:09:42 -03:00
* 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.)
2007-12-29 06:57:00 -04:00
.. Patch #1675423
2007-09-24 21:09:42 -03:00
2007-12-18 22:02:04 -04:00
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.
2007-12-29 06:57:00 -04:00
.. Patch 1507
2007-12-18 22:02:04 -04:00
2008-01-03 21:16:12 -04:00
* More floating-point features were also added. The :func:`float` function
will now turn the strings ``+nan`` and ``-nan`` into the corresponding
2008-01-03 22:31:40 -04:00
IEEE 754 Not A Number values, and ``+inf`` and ``-inf`` into
2008-01-03 21:16:12 -04:00
positive or negative infinity. This works on any platform with
2008-01-03 22:03:25 -04:00
IEEE 754 semantics. (Contributed by Christian Heimes.)
2008-01-03 21:16:12 -04:00
.. Patch 1635.
2008-01-03 22:31:40 -04:00
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.
.. Patch 1640
The ``math.copysign(x, y)`` function
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.)
2007-09-24 21:09:42 -03:00
* Changes to the :class:`Exception` interface
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.
2007-12-18 22:02:04 -04:00
* 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`.
(Contributed by Chad Austin.)
2007-12-29 06:57:00 -04:00
.. Patch #1537
2007-12-18 22:02:04 -04:00
2007-09-13 19:49:34 -03:00
* The :func:`compile` built-in function now accepts keyword arguments
2007-09-24 21:09:42 -03:00
as well as positional parameters. (Contributed by Thomas Wouters.)
2007-09-13 19:49:34 -03:00
2007-12-29 06:57:00 -04:00
.. Patch 1444529
2007-09-13 19:49:34 -03:00
2007-09-01 17:43:36 -03:00
* 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).
2007-12-29 06:57:00 -04:00
.. Patch 1491866
2007-09-01 17:43:36 -03:00
2007-09-01 18:18:31 -03:00
* 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.)
2007-12-29 06:57:00 -04:00
.. Patch 1193128
2007-09-01 18:18:31 -03:00
2007-09-13 19:49:34 -03:00
* The built-in :func:`dir` function now checks for a :meth:`__dir__`
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__`
2007-12-03 15:49:54 -04:00
methods can use this to advertise pseudo-attributes they will honor.
2007-09-13 19:49:34 -03:00
2007-12-29 06:57:00 -04:00
.. Patch 1591665
2007-09-13 19:49:34 -03:00
2007-08-15 11:28:01 -03:00
* An obscure change: when you use the the :func:`locals` function inside a
:keyword:`class` statement, the resulting dictionary no longer returns free
variables. (Free variables, in this case, are variables referred to in the
:keyword:`class` statement that aren't attributes of the class.)
2007-12-29 06:57:00 -04:00
.. ======================================================================
2007-08-15 11:28:01 -03:00
Optimizations
-------------
2008-01-15 02:55:56 -04:00
* Type objects now have a cache of methods that can reduce
2008-01-14 21:47:32 -04:00
the amount of work required to find the correct method implementation
2008-01-14 21:55:32 -04:00
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
nature.
2008-01-14 21:47:32 -04:00
(Original optimization implemented by Armin Rigo, updated for
Python 2.6 by Kevin Jacobs.)
.. % Patch 1700288
2008-01-03 22:31:40 -04:00
* All of the functions in the :mod:`struct` module have been rewritten in
C, thanks to work at the Need For Speed sprint.
(Contributed by Raymond Hettinger.)
2007-08-15 11:28:01 -03:00
* Internally, a bit is now set in type objects to indicate some of the standard
built-in types. This speeds up checking if an object is a subclass of one of
these types. (Contributed by Neal Norwitz.)
The net result of the 2.6 optimizations is that Python 2.6 runs the pystone
benchmark around XX% faster than Python 2.5.
2007-12-29 06:57:00 -04:00
.. ======================================================================
2007-08-15 11:28:01 -03:00
New, Improved, and Deprecated Modules
=====================================
As usual, Python's standard library received a number of enhancements and bug
fixes. Here's a partial list of the most notable changes, sorted alphabetically
by module name. Consult the :file:`Misc/NEWS` file in the source tree for a more
complete list of changes, or look through the CVS logs for all the details.
2007-10-16 19:58:03 -03:00
* The :mod:`bsddb.dbshelve` module now uses the highest pickling protocol
available, instead of restricting itself to protocol 1.
(Contributed by W. Barnes.)
2007-12-29 06:57:00 -04:00
.. Patch 1551443
2007-10-16 19:58:03 -03:00
2007-10-23 17:55:47 -03:00
* A new data type in the :mod:`collections` module: :class:`namedtuple(typename,
2007-08-15 11:28:01 -03:00
fieldnames)` is a factory function that creates subclasses of the standard tuple
whose fields are accessible by name as well as index. For example::
2007-10-23 17:55:47 -03:00
>>> var_type = collections.namedtuple('variable',
2007-09-24 21:09:42 -03:00
... 'id name type size')
# Names are separated by spaces or commas.
# 'id, name, type, size' would also work.
2007-12-14 14:12:21 -04:00
>>> var_type._fields
2007-09-24 21:09:42 -03:00
('id', 'name', 'type', 'size')
>>> var = var_type(1, 'frequency', 'int', 4)
>>> print var[0], var.id # Equivalent
1 1
>>> print var[2], var.type # Equivalent
int int
2007-12-14 14:12:21 -04:00
>>> var._asdict()
2007-10-16 19:58:03 -03:00
{'size': 4, 'type': 'int', 'id': 1, 'name': 'frequency'}
2007-12-14 14:12:21 -04:00
>>> v2 = var._replace('name', 'amplitude')
2007-09-24 21:09:42 -03:00
>>> v2
variable(id=1, name='amplitude', type='int', size=4)
2007-08-15 11:28:01 -03:00
2008-01-14 21:47:32 -04:00
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
:attr:`sign`, :attr:`digits`, and :attr:`exponent` fields.
2007-08-15 11:28:01 -03:00
(Contributed by Raymond Hettinger.)
2007-10-16 19:58:03 -03:00
* Another change to the :mod:`collections` module is that the
:class:`deque` type now supports an optional *maxlen* parameter;
2007-10-16 19:58:03 -03:00
if supplied, the deque's size will be restricted to no more
than *maxlen* items. Adding more items to a full deque causes
2007-10-16 19:58:03 -03:00
old items to be discarded.
::
>>> from collections import deque
>>> dq=deque(maxlen=3)
>>> dq
deque([], maxlen=3)
>>> dq.append(1) ; dq.append(2) ; dq.append(3)
>>> dq
deque([1, 2, 3], maxlen=3)
>>> dq.append(4)
>>> dq
deque([2, 3, 4], maxlen=3)
(Contributed by Raymond Hettinger.)
2007-09-24 21:09:42 -03:00
* The :mod:`ctypes` module now supports a :class:`c_bool` datatype
that represents the C99 ``bool`` type. (Contributed by David Remahl.)
2007-12-29 06:57:00 -04:00
.. Patch 1649190
2007-09-24 21:09:42 -03:00
2007-10-16 19:58:03 -03:00
The :mod:`ctypes` string, buffer and array types also have improved
support for extended slicing syntax,
where various combinations of ``(start, stop, step)`` are supplied.
(Implemented by Thomas Wouters.)
2007-12-29 06:57:00 -04:00
.. Revision 57769
2007-10-16 19:58:03 -03:00
2007-08-15 11:28:01 -03:00
* A new method in the :mod:`curses` module: for a window, :meth:`chgat` changes
2007-09-24 21:09:42 -03:00
the display characters for a certain number of characters on a single line.
::
2007-08-15 11:28:01 -03:00
# Boldface text starting at y=0,x=21
# and affecting the rest of the line.
stdscr.chgat(0,21, curses.A_BOLD)
(Contributed by Fabian Kreutz.)
2007-09-24 21:09:42 -03:00
* 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`::
>>> Decimal(1).exp()
Decimal("2.718281828459045235360287471")
>>> Decimal("2.7182818").ln()
Decimal("0.9999999895305022877376682436")
>>> Decimal(1000).log10()
Decimal("3")
2008-01-14 21:47:32 -04:00
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.
In addition to behaving like tuples, the returned values
also have :attr:`a`, :attr:`b`, and :attr:`size` attributes.
(Contributed by Raymond Hettinger.)
2007-09-24 21:09:42 -03:00
2007-09-01 18:18:31 -03:00
* 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.)
2007-09-24 21:09:42 -03:00
* 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
Christian Heimes.)
2007-12-29 06:57:00 -04:00
.. Patch 1739906
2007-09-24 21:09:42 -03:00
2007-08-15 11:28:01 -03:00
* The :func:`glob.glob` function can now return Unicode filenames if
a Unicode path was used and Unicode filenames are matched within the directory.
2007-12-29 06:57:00 -04:00
.. Patch #1001604
2007-08-15 11:28:01 -03:00
* The :mod:`gopherlib` module has been removed.
* 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::
heapq.merge([1, 3, 5, 9], [2, 8, 16]) ->
[1, 2, 3, 5, 8, 9, 16]
(Contributed by Raymond Hettinger.)
2007-09-13 19:49:34 -03:00
* An optional ``timeout`` parameter was added to the
:class:`httplib.HTTPConnection` and :class:`HTTPSConnection`
class constructors, specifying a timeout measured in seconds.
(Added by Facundo Batista.)
2008-01-14 21:47:32 -04:00
* 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.)
2007-08-15 11:28:01 -03:00
* A new function in the :mod:`itertools` module: ``izip_longest(iter1, iter2,
...[, fillvalue])`` makes tuples from each of the elements; if some of the
iterables are shorter than others, the missing values are set to *fillvalue*.
For example::
itertools.izip_longest([1,2,3], [1,2,3,4,5]) ->
[(1, 1), (2, 2), (3, 3), (None, 4), (None, 5)]
(Contributed by Raymond Hettinger.)
* The :mod:`macfs` module has been removed. This in turn required the
:func:`macostools.touched` function to be removed because it depended on the
:mod:`macfs` module.
2007-12-29 06:57:00 -04:00
.. Patch #1490190
2007-08-15 11:28:01 -03:00
2007-12-18 22:02:04 -04:00
* The :mod:`new` module has been removed from Python 3.0.
Importing it therefore
triggers a warning message when Python is running in 3.0-warning
mode.
* 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
of a symlink.
(Contributed by Georg Brandl and Christian Heimes.)
2007-09-24 21:09:42 -03:00
* The :func:`os.walk` function now has a ``followlinks`` parameter. If
2007-09-13 19:49:34 -03:00
set to True, it will follow symlinks pointing to directories and
visit the directory's contents. For backward compatibility, the
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.
2007-12-29 06:57:00 -04:00
.. Patch 1273829
2007-09-13 19:49:34 -03:00
2007-10-16 19:58:03 -03:00
* The ``os.environ`` object's :meth:`clear` method will now unset the
environment variables using :func:`os.unsetenv` in addition to clearing
2007-10-20 16:35:18 -03:00
the object's keys. (Contributed by Martin Horcicka.)
2007-10-16 19:58:03 -03:00
2007-12-29 06:57:00 -04:00
.. Patch #1181
2007-10-16 19:58:03 -03:00
2007-09-01 17:43:36 -03:00
* In the :mod:`os.path` module, the :func:`splitext` function
has been changed to not split on leading period characters.
This produces better results when operating on Unix's dot-files.
For example, ``os.path.splitext('.ipython')``
now returns ``('.ipython', '')`` instead of ``('', '.ipython')``.
2007-12-29 06:57:00 -04:00
.. Bug #115886
2007-09-01 17:43:36 -03:00
2007-09-01 18:18:31 -03:00
A new function, :func:`relpath(path, start)` returns a relative path
from the ``start`` path, if it's supplied, or from the current
working directory to the destination ``path``. (Contributed by
Richard Barran.)
2007-12-29 06:57:00 -04:00
.. Patch 1339796
2007-09-01 18:18:31 -03:00
2007-09-13 19:49:34 -03:00
On Windows, :func:`os.path.expandvars` will now expand environment variables
in the form "%var%", and "~user" will be expanded into the
2007-09-24 21:09:42 -03:00
user's home directory path. (Contributed by Josiah Carlson.)
2007-09-13 19:49:34 -03:00
2007-12-29 06:57:00 -04:00
.. Patch 957650
2007-09-13 19:49:34 -03:00
2007-09-24 21:09:42 -03:00
* 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.)
2007-12-29 06:57:00 -04:00
.. Patch #1393667
2007-09-24 21:09:42 -03:00
2007-08-15 11:28:01 -03:00
* New functions in the :mod:`posix` module: :func:`chflags` and :func:`lchflags`
are wrappers for the corresponding system calls (where they're available).
Constants for the flag values are defined in the :mod:`stat` module; some
possible values include :const:`UF_IMMUTABLE` to signal the file may not be
changed and :const:`UF_APPEND` to indicate that data can only be appended to the
file. (Contributed by M. Levinson.)
* The :mod:`pyexpat` module's :class:`Parser` objects now allow setting
their :attr:`buffer_size` attribute to change the size of the buffer
used to hold character data.
(Contributed by Achim Gaedke.)
.. Patch 1137
2007-12-18 22:02:04 -04:00
* The :mod:`random` module's :class:`Random` objects can
now be pickled on a 32-bit system and unpickled on a 64-bit
system, and vice versa. Unfortunately, this change also means
that Python 2.6's :class:`Random` objects can't be unpickled correctly
on earlier versions of Python.
(Contributed by Shawn Ligocki.)
2007-12-29 06:57:00 -04:00
.. Issue 1727780
2007-12-18 22:02:04 -04:00
2008-01-14 21:47:32 -04:00
* 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.
(Contributed by Josh Hoyt and Ralf Schmitt.)
.. % Patch 846388
2007-08-15 11:28:01 -03:00
* The :mod:`rgbimg` module has been removed.
2007-10-20 16:35:18 -03:00
* The :mod:`sets` module has been deprecated; it's better to
use the built-in :class:`set` and :class:`frozenset` types.
2007-12-22 13:27:02 -04:00
* 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. Thi
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
file descriptor. There's also a C-level function,
:cfunc:`PySignal_SetWakeupFd`, for setting the descriptor.
Event loops will use this by opening a pipe to create two descriptors,
one for reading and one for writing. The writeable descriptor
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
will be woken up, without the need to poll.
Contributed by Adam Olsen.
.. % Patch 1583
2007-09-01 17:43:36 -03:00
* The :mod:`smtplib` module now supports SMTP over SSL thanks to the
addition of the :class:`SMTP_SSL` class. This class supports an
2007-09-01 18:18:31 -03:00
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.
An implementation of the LMTP protocol (:rfc:`2033`) was also added to
2007-09-01 17:43:36 -03:00
the module. LMTP is used in place of SMTP when transferring e-mail
between agents that don't manage a mail queue.
2007-09-01 18:18:31 -03:00
(SMTP over SSL contributed by Monty Taylor; timeout parameter
added by Facundo Batista; LMTP implemented by Leif
2007-09-01 17:43:36 -03:00
Hedstrom.)
2007-12-29 06:57:00 -04:00
.. Patch #957003
2007-08-15 11:28:01 -03:00
* In the :mod:`smtplib` module, SMTP.starttls() now complies with :rfc:`3207`
and forgets any knowledge obtained from the server not obtained from
the TLS negotiation itself. Patch contributed by Bill Fenner.
.. Issue 829951
2008-01-14 21:47:32 -04:00
* The :mod:`socket` module now supports TIPC (http://tipc.sf.net),
a high-performance non-IP-based protocol designed for use in clustered
environments. TIPC addresses are 4- or 5-tuples.
(Contributed by Alberto Bertogli.)
.. Patch #1646
2007-12-18 22:02:04 -04:00
* A new variable in the :mod:`sys` module,
2008-01-14 10:48:43 -04:00
:attr:`float_info`, is an object
2007-12-18 22:02:04 -04:00
containing information about the platform's floating-point support
2008-01-14 10:48:43 -04:00
derived from the :file:`float.h` file. Attributes of this object
include
:attr:`mant_dig` (number of digits in the mantissa), :attr:`epsilon`
2007-12-18 22:02:04 -04:00
(smallest difference between 1.0 and the next largest value
representable), and several others. (Contributed by Christian Heimes.)
2007-12-29 06:57:00 -04:00
.. Patch 1534
2007-12-18 22:02:04 -04:00
Another new variable, :attr:`dont_write_bytecode`, controls whether Python
writes any :file:`.pyc` or :file:`.pyo` files on importing a module.
If this variable is true, the compiled files are not written. The
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
change the value of this variable to control whether bytecode files
are written or not.
(Contributed by Neal Norwitz and Georg Brandl.)
2008-01-14 21:47:32 -04:00
Information about the command-line arguments supplied to the Python
interpreter are available as attributes of a ``sys.flags`` named
tuple. For example, the :attr:`verbose` attribute is true if Python
was executed in verbose mode, :attr:`debug` is true in debugging mode, etc.
These attributes are all read-only.
(Contributed by Christian Heimes.)
2007-09-17 22:36:16 -03:00
* 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
is GNU tar; specify the ``format`` parameter to open a file
using a different format::
tar = tarfile.open("output.tar", "w", format=tarfile.PAX_FORMAT)
The new ``errors`` parameter lets you specify an error handling
scheme for character conversions: the three standard ways Python can
handle errors ``'strict'``, ``'ignore'``, ``'replace'`` , or the
special value ``'utf-8'``, which replaces bad characters with their
UTF-8 representation. Character conversions occur because the PAX
format supports Unicode filenames, defaulting to UTF-8 encoding.
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
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
constructor. (Contributed by Damien Miller.)
2007-12-29 06:57:00 -04:00
.. Patch #1537850
2007-09-17 22:36:16 -03:00
* 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.
Another context manager, :class:`TransientResource`, can surround calls
to resources that may or may not be available; it will catch and
ignore a specified list of exceptions. For example,
a network test may ignore certain failures when connecting to an
external web site::
with test_support.TransientResource(IOError, errno=errno.ETIMEDOUT):
f = urllib.urlopen('https://sf.net')
...
(Contributed by Brett Cannon.)
2007-09-13 19:49:34 -03:00
* 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::
>>> S = """This sentence has a bunch of extra whitespace."""
>>> print textwrap.fill(S, width=15)
This sentence
has a bunch
of extra
whitespace.
>>> print textwrap.fill(S, drop_whitespace=False, width=15)
This sentence
has a bunch
of extra
whitespace.
>>>
2007-12-29 06:57:00 -04:00
.. Patch #1581073
2007-09-13 19:49:34 -03:00
2007-09-01 17:43:36 -03:00
* 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
``timeit(stmt, setup, time, number)`` create an instance and call
the corresponding method. (Contributed by Erik Demaine.)
2007-12-29 06:57:00 -04:00
.. Patch #1533909
2007-09-01 17:43:36 -03:00
2007-09-13 19:49:34 -03:00
* An optional ``timeout`` parameter was added to the
:func:`urllib.urlopen` function and the
:class:`urllib.ftpwrapper` class constructor, as well as the
:func:`urllib2.urlopen` function. The parameter specifies a timeout
measured in seconds. For example::
>>> u = urllib2.urlopen("http://slow.example.com", timeout=3)
Traceback (most recent call last):
...
urllib2.URLError: <urlopen error timed out>
>>>
(Added by Facundo Batista.)
2007-09-24 21:09:42 -03:00
* The XML-RPC classes :class:`SimpleXMLRPCServer` and :class:`DocXMLRPCServer`
2007-10-20 16:35:18 -03:00
classes can now be prevented from immediately opening and binding to
2007-09-24 21:09:42 -03:00
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
open the socket and begin listening for connections.
(Contributed by Peter Parente.)
2007-12-29 06:57:00 -04:00
.. Patch 1599845
2007-09-24 21:09:42 -03:00
2007-10-20 16:35:18 -03:00
: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
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
project for Google's Summer of Code 2007.)
2008-01-14 21:47:32 -04:00
* 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')
# Unpack a single file, writing it relative to the /tmp directory.
z.extract('Python/sysmodule.c', '/tmp')
# Unpack all the files in the archive.
z.extractall()
(Contributed by Alan McIntyre.)
.. % Patch 467924
2007-12-29 06:57:00 -04:00
.. ======================================================================
.. whole new modules get described in subsections here
2007-10-20 16:35:18 -03:00
Improved SSL Support
2007-10-20 16:39:35 -03:00
--------------------------------------------------
2007-10-20 16:35:18 -03:00
Bill Janssen made extensive improvements to Python 2.6's support for
SSL.
XXX use ssl.sslsocket - subclass of socket.socket.
XXX Can specify if certificate is required, and obtain certificate info
by calling getpeercert method.
XXX sslwrap() behaves like socket.ssl
XXX Certain features require the OpenSSL package to be installed, notably
the 'openssl' binary.
.. seealso::
SSL module documentation.
2007-08-15 11:28:01 -03:00
2007-12-29 06:57:00 -04:00
.. ======================================================================
2007-08-15 11:28:01 -03:00
Build and C API Changes
=======================
Changes to Python's build process and to the C API include:
2007-11-23 09:37:39 -04:00
* Python 2.6 can be built with Microsoft Visual Studio 2008.
See the :file:`PCbuild9` directory for the build files.
(Implemented by Christian Heimes.)
2007-10-16 19:58:03 -03:00
* 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.)
2007-12-29 06:57:00 -04:00
.. Patch 1551895
2007-10-16 19:58:03 -03:00
2007-12-18 22:02:04 -04:00
* 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
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.
2008-01-03 22:03:25 -04:00
(Contributed by Christian Heimes.)
2007-12-18 22:02:04 -04:00
2007-12-29 06:57:00 -04:00
.. Issue 1534
2007-08-15 11:28:01 -03:00
2008-01-03 21:16:12 -04:00
* Python's C API now includes two functions for case-insensitive string
comparisions, ``PyOS_stricmp(char*, char*)``
and ``PyOS_strnicmp(char*, char*, Py_ssize_t)``.
2008-01-03 22:03:25 -04:00
(Contributed by Christian Heimes.)
2008-01-03 21:16:12 -04:00
.. Issue 1635
2008-01-03 22:31:40 -04:00
* Some macros were renamed to make it clearer that they are macros,
not functions. :cmacro:`Py_Size()` became :cmacro:`Py_SIZE()`,
2008-01-03 21:16:12 -04:00
:cmacro:`Py_Type()` became :cmacro:`Py_TYPE()`, and
:cmacro:`Py_Refcnt()` became :cmacro:`Py_REFCNT()`. Macros for backward
2008-01-03 22:03:25 -04:00
compatibility are still available for Python 2.6.
2008-01-03 21:16:12 -04:00
2008-01-03 22:31:40 -04:00
.. Issue 1629
2008-01-03 21:16:12 -04:00
2007-12-29 06:57:00 -04:00
.. ======================================================================
2007-08-15 11:28:01 -03:00
2008-01-03 21:16:12 -04:00
Port-Specific Changes: Windows
-----------------------------------
* 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
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.)
2007-08-15 11:28:01 -03:00
* :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
:cfunc:`WSAIoctl` system interface.
2008-01-14 21:47:32 -04:00
* 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
in :keyword:`with` statements. (Contributed by Christian Heimes.)
* 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
(PGO). PGO builds are roughly 10% faster than normal builds.
(Contributed by Christian Heimes with help from Amaury Forgeot d'Arc and
Martin von Loewis.)
2007-08-15 11:28:01 -03:00
2007-12-29 06:57:00 -04:00
.. ======================================================================
2007-08-15 11:28:01 -03:00
.. _section-other:
Other Changes and Fixes
=======================
2008-01-14 21:47:32 -04:00
As usual, there were a bunch of other improvements and bugfixes
scattered throughout the source tree. A search through the change
logs finds there were XXX patches applied and YYY bugs fixed between
Python 2.5 and 2.6. Both figures are likely to be underestimates.
2007-08-15 11:28:01 -03:00
Some of the more notable changes are:
2008-01-14 21:47:32 -04:00
* 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
2008-01-15 02:58:15 -04:00
are also used to set the :data:`sys.dont_write_bytecode` attribute;
Python code can change this variable to control whether bytecode
files are subsequently written.
2008-01-14 21:47:32 -04:00
(Contributed by Neal Norwitz and Georg Brandl.)
2007-08-15 11:28:01 -03:00
2007-12-29 06:57:00 -04:00
.. ======================================================================
2007-08-15 11:28:01 -03:00
Porting to Python 2.6
=====================
2008-01-03 21:16:12 -04:00
This section lists previously described changes, and a few
esoteric bugfixes, that may require changes to your
2007-08-15 11:28:01 -03:00
code:
2008-01-04 14:24:41 -04:00
* The :meth:`__init__` method of :class:`collections.deque`
2008-01-03 21:16:12 -04:00
now clears any existing contents of the deque
before adding elements from the iterable. This change makes the
behavior match that of ``list.__init__()``.
2008-01-14 21:47:32 -04:00
* 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
:exc:`ConversionSyntax` exception.
* 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
an :exc:`ImportError`.
2007-10-20 16:35:18 -03:00
* The :mod:`socket` module exception :exc:`socket.error` now inherits
from :exc:`IOError`. Previously it wasn't a subclass of
:exc:`StandardError` but now it is, through :exc:`IOError`.
(Implemented by Gregory P. Smith.)
2007-12-29 06:57:00 -04:00
.. Issue 1706815
2007-08-15 11:28:01 -03:00
2007-12-29 06:57:00 -04:00
.. ======================================================================
2007-08-15 11:28:01 -03:00
.. _acks:
Acknowledgements
================
The author would like to thank the following people for offering suggestions,
corrections and assistance with various drafts of this article: .