whatsnew.pdf

(233 KB) Pobierz
What’s New in Python
Release2.7.6
A. M. Kuchling
March 17, 2014
Python Software Foundation
Email:docs@python.org
Contents
1
The Future for Python 2.x
ii
2
Python 3.1 Features
ii
3
PEP 372: Adding an Ordered Dictionary to collections
iii
4
PEP 378: Format Specifier for Thousands Separator
iv
5
PEP 389: The argparse Module for Parsing Command Lines
v
6
PEP 391: Dictionary-Based Configuration For Logging
vi
7
PEP 3106: Dictionary Views
vii
8
PEP 3137: The memoryview Object
viii
9
Other Language Changes
ix
9.1
Interpreter Changes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
xii
9.2
Optimizations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
xii
10 New and Improved Modules xiii
10.1 New module: importlib . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xxi
10.2 New module: sysconfig . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xxi
10.3 ttk: Themed Widgets for Tk . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xxi
10.4 Updated module: unittest . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xxii
10.5 Updated module: ElementTree 1.3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xxiv
11 Build and C API Changes xxv
11.1 Capsules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xxvi
11.2 Port-Specific Changes: Windows . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xxvii
11.3 Port-Specific Changes: Mac OS X . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xxvii
11.4 Port-Specific Changes: FreeBSD . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xxvii
12 Other Changes and Fixes
xxviii
13 Porting to Python 2.7
xxviii
14 Acknowledgements
xxix
Index xxxi
1276745399.001.png
 
Author A.M. Kuchling (amk at amk.ca)
This article explains the new features in Python 2.7. Python 2.7 was released on July 3, 2010.
Numeric handling has been improved in many ways, for both floating-point numbers and for the Decimal class.
There are some useful additions to the standard library, such as a greatly enhanced unittest module, the
argparse module for parsing command-line options, convenient OrderedDict and Counter classes in the
collections module, and many other improvements.
Python 2.7 is planned to be the last of the 2.x releases, so we worked on making it a good release for the long
term. To help with porting to Python 3, several new features from the Python 3.x series have been included in 2.7.
This article doesn’t attempt to provide a complete specification of the new features, but instead provides a conve-
nient overview. For full details, you should refer to the documentation for Python 2.7 at http://docs.python.org .
If you want to understand the rationale for the design and implementation, refer to the PEP for a particular new
feature or the issue on http://bugs.python.org in which a change was discussed. Whenever possible, “What’s New
in Python” links to the bug/patch item for each change.
1 The Future for Python 2.x
Python 2.7 is intended to be the last major release in the 2.x series. The Python maintainers are planning to focus
their future efforts on the Python 3.x series.
This means that 2.7 will remain in place for a long time, running production systems that have not been ported to
Python 3.x. Two consequences of the long-term significance of 2.7 are:
• It’s very likely the 2.7 release will have a longer period of maintenance compared to earlier 2.x versions.
Python 2.7 will continue to be maintained while the transition to 3.x continues, and the developers are
planning to support Python 2.7 with bug-fix releases beyond the typical two years.
• A policy decision was made to silence warnings only of interest to developers. DeprecationWarning
and its descendants are now ignored unless otherwise requested, preventing users from seeing warnings trig-
gered by an application. This change was also made in the branch that will become Python 3.2. (Discussed
on stdlib-sig and carried out in issue 7319 . )
In previous releases, DeprecationWarning messages were enabled by default, providing Python de-
velopers with a clear indication of where their code may break in a future major version of Python.
However, there are increasingly many users of Python-based applications who are not directly involved in
the development of those applications. DeprecationWarning messages are irrelevant to such users,
making them worry about an application that’s actually working correctly and burdening application devel-
opers with responding to these concerns.
You can re-enable display of DeprecationWarning messages by running Python with the
-Wdefault (short form: -Wd ) switch, or by setting the PYTHONWARNINGS environment variable
to "default" (or "d" ) before running Python.
Python code can also re-enable them by calling
warnings.simplefilter(’default’) .
2 Python 3.1 Features
Much as Python 2.6 incorporated features from Python 3.0, version 2.7 incorporates some of the new features in
Python 3.1. The 2.x series continues to provide tools for migrating to the 3.x series.
A partial list of 3.1 features that were backported to 2.7:
• The syntax for set literals ( {1,2,3} is a mutable set).
• Dictionary and set comprehensions ( {i:i * 2foriinrange(3)} ).
• Multiple context managers in a single with statement.
• A new version of the io library, rewritten in C for performance.
• The ordered-dictionary type described in PEP 372: Adding an Ordered Dictionary to collections .
• The new "," format specifier described in PEP 378: Format Specifier for Thousands Separator .
• The memoryview object.
• A small subset of the importlib module, described below .
• The repr() of a float x is shorter in many cases: it’s now based on the shortest decimal string that’s
guaranteed to round back to x . As in previous versions of Python, it’s guaranteed that float(repr(x))
recovers x .
• Float-to-string and string-to-float conversions are correctly rounded. The round() function is also now
correctly rounded.
• The PyCapsule type, used to provide a C API for extension modules.
• The PyLong_AsLongAndOverflow() C API function.
Other new Python3-mode warnings include:
operator.isCallable() and operator.sequenceIncludes() , which are not supported in
3.x, now trigger warnings.
• The -3 switch now automatically enables the -Qwarn switch that causes warnings about using classic
division with integers and long integers.
3 PEP 372: Adding an Ordered Dictionary to collections
Regular Python dictionaries iterate over key/value pairs in arbitrary order. Over the years, a number of authors
have written alternative implementations that remember the order that the keys were originally inserted. Based on
the experiences from those implementations, 2.7 introduces a new OrderedDict class in the collections
module.
The OrderedDict API provides the same interface as regular dictionaries but iterates over keys and values in a
guaranteed order depending on when a key was first inserted:
>>> from collections import OrderedDict
>>> d = OrderedDict([( ’first’ , 1 ),
... ( ’second’ , 2 ),
... ( ’third’ , 3 )])
>>> d . items()
[(’first’,1),(’second’,2),(’third’,3)]
If a new entry overwrites an existing entry, the original insertion position is left unchanged:
>>> d[ ’second’ ] = 4
>>> d . items()
[(’first’,1),(’second’,4),(’third’,3)]
Deleting an entry and reinserting it will move it to the end:
>>> del d[ ’second’ ]
>>> d[ ’second’ ] = 5
>>> d . items()
[(’first’,1),(’third’,3),(’second’,5)]
The popitem() method has an optional last argument that defaults to True. If last is True, the most recently
added key is returned and removed; if it’s False, the oldest key is selected:
>>> od = OrderedDict([(x, 0 ) for x in range ( 20 )])
>>> od . popitem()
(19,0)
>>> od . popitem()
(18,0)
>>> od . popitem(last = False )
(0,0)
>>> od . popitem(last = False )
(1,0)
Comparing two ordered dictionaries checks both the keys and values, and requires that the insertion order was the
same:
>>> od1 = OrderedDict([( ’first’ , 1 ),
... ( ’second’ , 2 ),
... ( ’third’ , 3 )])
>>> od2 = OrderedDict([( ’third’ , 3 ),
...
( ’first’ , 1 ),
...
( ’second’ , 2 )])
>>> od1 == od2
False
>>> #Move’third’keytotheend
>>> del od2[ ’third’ ];od2[ ’third’ ] = 3
>>> od1 == od2
True
Comparing an OrderedDict with a regular dictionary ignores the insertion order and just compares the keys
and values.
How does the OrderedDict work? It maintains a doubly-linked list of keys, appending new keys to the list as
they’re inserted. A secondary dictionary maps keys to their corresponding list node, so deletion doesn’t have to
traverse the entire linked list and therefore remains O(1).
The standard library now supports use of ordered dictionaries in several modules.
• The ConfigParser module uses them by default, meaning that configuration files can now be read,
modified, and then written back in their original order.
• The _asdict() method for collections.namedtuple() now returns an ordered dictionary with
the values appearing in the same order as the underlying tuple indices.
• The json module’s JSONDecoder class constructor was extended with an object_pairs_hook parameter
to allow OrderedDict instances to be built by the decoder. Support was also added for third-party tools
like PyYAML .
See Also:
PEP 372 - Adding an ordered dictionary to collections PEP written by Armin Ronacher and Raymond Het-
tinger; implemented by Raymond Hettinger.
4 PEP 378: Format Specifier for Thousands Separator
To make program output more readable, it can be useful to add separators to large numbers, rendering them as
18,446,744,073,709,551,616 instead of 18446744073709551616.
The fully general solution for doing this is the locale module, which can use different separators (”,” in North
America, ”.” in Europe) and different grouping sizes, but locale is complicated to use and unsuitable for multi-
threaded applications where different threads are producing output for different locales.
Therefore, a simple comma-grouping mechanism has been added to the mini-language used by the
str.format() method. When formatting a floating-point number, simply include a comma between the width
and the precision:
>>> ’{:20,.2f}’ . format( 18446744073709551616.0 )
’18,446,744,073,709,551,616.00’
When formatting an integer, include the comma after the width:
>>> ’{:20,d}’ . format( 18446744073709551616 )
’18,446,744,073,709,551,616’
This mechanism is not adaptable at all; commas are always used as the separator and the grouping is always into
three-digit groups. The comma-formatting mechanism isn’t as general as the locale module, but it’s easier to
use.
See Also:
PEP 378 - Format Specifier for Thousands Separator PEP written by Raymond Hettinger; implemented by
Eric Smith.
5 PEP 389: The argparse Module for Parsing Command Lines
The argparse module for parsing command-line arguments was added as a more powerful replacement for the
optparse module.
This means Python now supports three different modules for parsing command-line arguments: getopt ,
optparse , and argparse . The getopt module closely resembles the C library’s getopt() function, so it
remains useful if you’re writing a Python prototype that will eventually be rewritten in C. optparse becomes
redundant, but there are no plans to remove it because there are many scripts still using it, and there’s no automated
way to update these scripts. (Making the argparse API consistent with optparse ‘s interface was discussed
but rejected as too messy and difficult.)
In short, if you’re writing a new script and don’t need to worry about compatibility with earlier versions of Python,
use argparse instead of optparse .
Here’s an example:
import argparse
parser = argparse . ArgumentParser(description = ’Command-lineexample.’ )
#Addoptionalswitches
parser . add_argument( ’-v’ ,action = ’store_true’ ,dest = ’is_verbose’ ,
help = ’produceverboseoutput’ )
parser . add_argument( ’-o’ ,action = ’store’ ,dest = ’output’ ,
metavar = ’FILE’ ,
help = ’directoutputtoFILEinsteadofstdout’ )
parser . add_argument( ’-C’ ,action = ’store’ , type = int ,dest = ’context’ ,
metavar = ’NUM’ ,default = 0 ,
help = ’displayNUMlinesofaddedcontext’ )
#Allowanynumberofadditionalarguments.
parser . add_argument(nargs = * ,action = ’store’ ,dest = ’inputs’ ,
help = ’inputfilenames(defaultisstdin)’ )
args = parser . parse_args()
print args . __dict__
Unless you override it, -h and --help switches are automatically added, and produce neatly formatted output:
->./python.exeargparse-example.py--help
usage:argparse-example.py[-h][-v][-oFILE][-CNUM][inputs[inputs...]]
Command-lineexample.
positionalarguments:
inputs inputfilenames(defaultisstdin)
optionalarguments:
Zgłoś jeśli naruszono regulamin