13518219792

建站动态

根据您的个性需求进行定制 先人一步 抢占小程序红利时代

创新互联Python教程:Python2.7有什么新变化

python 2.7 有什么新变化

作者

专注于为中小企业提供成都网站设计、成都网站建设服务,电脑端+手机端+微信端的三站合一,更高效的管理,为中小企业宿松免费做网站提供优质的服务。我们立足成都,凝聚了一批互联网行业人才,有力地推动了1000+企业的稳健成长,帮助中小企业通过网站建设实现规模扩充和转变。

A.M. Kuchling (amk at amk.ca)

本文介绍了Python 2.7 的新功能。 Python 2.7 于2010年7月3日发布。

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 convenient overview. For full details, you should refer to the documentation for Python 2.7 at https://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 https://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.

Python 2.x的未来

Python 2.7 是 2.x 系列中的最后一个主版本,因为Python 维护人员已将新功能开发工作的重点转移到了 Python 3.x 系列中。这意味着,尽管 Python 2 会继续修复bug并更新,以便在新的硬件和支持操作系统版本上正确构建,但不会有新的功能发布。

然而,尽管在 Python 2.7 和 Python 3 之间有一个很大的公共子集,并且迁移到该公共子集或直接迁移到 Python 3 所涉及的许多更改可以安全地自动化完成。但是一些其他更改(特别是那些与Unicode处理相关的更改)可能需要仔细考虑,并且最好用自动化回归测试套件进行健壮性测试,以便有效地迁移。

这意味着 Python2.7 将长期保留,为尚未移植到 Python 3 的生产系统提供一个稳定且受支持的基础平台。Python 2.7系列的预期完整生命周期在 PEP 373 中有详细介绍。

长期保留 2.7 版的的一些关键后果:

对于希望从 Python2 迁移到 Python3 的项目,或者对于希望同时支持 Python2 和 Python3 用户的库和框架开发人员,可以使用各种工具和指南来帮助决定合适的方法并管理所涉及的一些技术细节。建议从 将 Python 2 代码迁移到 Python 3 操作指南开始。

对于弃用警告处理方式的改变

For Python 2.7, a policy decision was made to silence warnings only of interest to developers by default. DeprecationWarning and its descendants are now ignored unless otherwise requested, preventing users from seeing warnings triggered by an application. This change was also made in the branch that became Python 3.2. (Discussed on stdlib-sig and carried out in bpo-7319.)

In previous releases, DeprecationWarning messages were enabled by default, providing Python developers 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 developers 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').

The unittest module also automatically reenables deprecation warnings when running tests.

Python 3.1 特性

就像 Python2.6 集成了 Python3.0 的特性一样,2.7版也集成了 Python3.1 中的一些新特性。2.x 系列继续提供迁移到3.x系列的工具。

3.1 功能的部分列表,这些功能已反向移植到 2.7:

Other new Python3-mode warnings include:

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:

 
 
 
 
  1. >>> from collections import OrderedDict
  2. >>> d = OrderedDict([('first', 1),
  3. ... ('second', 2),
  4. ... ('third', 3)])
  5. >>> d.items()
  6. [('first', 1), ('second', 2), ('third', 3)]

If a new entry overwrites an existing entry, the original insertion position is left unchanged:

 
 
 
 
  1. >>> d['second'] = 4
  2. >>> d.items()
  3. [('first', 1), ('second', 4), ('third', 3)]

Deleting an entry and reinserting it will move it to the end:

 
 
 
 
  1. >>> del d['second']
  2. >>> d['second'] = 5
  3. >>> d.items()
  4. [('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:

 
 
 
 
  1. >>> od = OrderedDict([(x,0) for x in range(20)])
  2. >>> od.popitem()
  3. (19, 0)
  4. >>> od.popitem()
  5. (18, 0)
  6. >>> od.popitem(last=False)
  7. (0, 0)
  8. >>> od.popitem(last=False)
  9. (1, 0)

Comparing two ordered dictionaries checks both the keys and values, and requires that the insertion order was the same:

 
 
 
 
  1. >>> od1 = OrderedDict([('first', 1),
  2. ... ('second', 2),
  3. ... ('third', 3)])
  4. >>> od2 = OrderedDict([('third', 3),
  5. ... ('first', 1),
  6. ... ('second', 2)])
  7. >>> od1 == od2
  8. False
  9. >>> # Move 'third' key to the end
  10. >>> del od2['third']; od2['third'] = 3
  11. >>> od1 == od2
  12. 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.

参见

PEP 372 - 将有序词典添加到集合中

PEP 由 Armin Ronacher 和 Raymond Hettinger 撰写,由 Raymond Hettinger 实现。

PEP 378: 千位分隔符的格式说明符

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:

 
 
 
 
  1. >>> '{:20,.2f}'.format(18446744073709551616.0)
  2. '18,446,744,073,709,551,616.00'

When formatting an integer, include the comma after the width:

 
 
 
 
  1. >>> '{:20,d}'.format(18446744073709551616)
  2. '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.

参见

PEP 378 - 千位分隔符的格式说明符

PEP 由 Raymond Hettinger 撰写,由 Eric Smith 实现

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.

以下是为示例代码:

 
 
 
 
  1. import argparse
  2. parser = argparse.ArgumentParser(description='Command-line example.')
  3. # Add optional switches
  4. parser.add_argument('-v', action='store_true', dest='is_verbose',
  5. help='produce verbose output')
  6. parser.add_argument('-o', action='store', dest='output',
  7. metavar='FILE',
  8. help='direct output to FILE instead of stdout')
  9. parser.add_argument('-C', action='store', type=int, dest='context',
  10. metavar='NUM', default=0,
  11. help='display NUM lines of added context')
  12. # Allow any number of additional arguments.
  13. parser.add_argument(nargs='*', action='store', dest='inputs',
  14. help='input filenames (default is stdin)')
  15. args = parser.parse_args()
  16. print args.__dict__

Unless you override it, -h and --help switches are automatically added, and produce neatly formatted output:

 
 
 
 
  1. -> ./python.exe argparse-example.py --help
  2. usage: argparse-example.py [-h] [-v] [-o FILE] [-C NUM] [inputs [inputs ...]]
  3. Command-line example.
  4. positional arguments:
  5. inputs input filenames (default is stdin)
  6. optional arguments:
  7. -h, --help show this help message and exit
  8. -v produce verbose output
  9. -o FILE direct output to FILE instead of stdout
  10. -C NUM display NUM lines of added context

As with optparse, the command-line switches and arguments are returned as an object with attributes named by the dest parameters:

 
 
 
 
  1. -> ./python.exe argparse-example.py -v
  2. {'output': None,
  3. 'is_verbose': True,
  4. 'context': 0,
  5. 'inputs': []}
  6. -> ./python.exe argparse-example.py -v -o /tmp/output -C 4 file1 file2
  7. {'output': '/tmp/output',
  8. 'is_verbose': True,
  9. 'context': 4,
  10. 'inputs': ['file1', 'file2']}

argparse has much fancier validation than optparse; you can specify an exact number of arguments as an integer, 0 or more arguments by passing '*', 1 or more by passing '+', or an optional argument with '?'. A top-level parser can contain sub-parsers to define subcommands that have different sets of switches, as in svn commit, svn checkout, etc. You can specify an argument’s type as FileType, which will automatically open files for you and understands that '-' means standard input or output.

参见

argparse documentation

argparse 模块的文档页面。

升级 optparse 代码

Part of the Python documentation, describing how to convert code that uses optparse.

PEP 389 - argparse - 新的命令行解析模块

PEP 由 Steven Bethard 撰写并实现。

PEP 391: Dictionary-Based Configuration For Logging

The logging module is very flexible; applications can define a tree of logging subsystems, and each logger in this tree can filter out certain messages, format them differently, and direct messages to a varying number of handlers.

All this flexibility can require a lot of configuration. You can write Python statements to create objects and set their properties, but a complex set-up requires verbose but boring code. logging also supports a fileConfig() function that parses a file, but the file format doesn’t support configuring filters, and it’s messier to generate programmatically.

Python 2.7 adds a dictConfig() function that uses a dictionary to configure logging. There are many ways to produce a dictionary from different sources: construct one with code; parse a file containing JSON; or use a YAML parsing library if one is installed. For more information see 配置函数.

The following example configures two loggers, the root logger and a logger named “network”. Messages sent to the root logger will be sent to the system log using the syslog protocol, and messages to the “network” logger will be written to a network.log file that will be rotated once the log reaches 1MB.

 
 
 
 
  1. import logging
  2. import logging.config
  3. configdict = {
  4. 'version': 1, # Configuration schema in use; must be 1 for now
  5. 'formatters': {
  6. 'standard': {
  7. 'format': ('%(asctime)s %(name)-15s '
  8. '%(levelname)-8s %(message)s')}},
  9. 'handlers': {'netlog': {'backupCount': 10,
  10. 'class': 'logging.handlers.RotatingFileHandler',
  11. 'filename': '/logs/network.log',
  12. 'formatter': 'standard',
  13. 'level': 'INFO',
  14. 'maxBytes': 1000000},
  15. 'syslog': {'class': 'logging.handlers.SysLogHandler',
  16. 'formatter': 'standard',
  17. 'level': 'ERROR'}},
  18. # Specify all the subordinate loggers
  19. 'loggers': {
  20. 'network': {
  21. 'handlers': ['netlog']
  22. }
  23. },
  24. # Specify properties of the root logger
  25. 'root': {
  26. 'handlers': ['syslog']
  27. },
  28. }
  29. # Set up configuration
  30. logging.config.dictConfig(configdict)
  31. # As an example, log two error messages
  32. logger = logging.getLogger('/')
  33. logger.error('Database not found')
  34. netlogger = logging.getLogger('network')
  35. netlogger.error('Connection failed')

Three smaller enhancements to the logging module, all implemented by Vinay Sajip, are:

参见

PEP 391 - 基于字典的日志配置

PEP 由 Vinay Sajip 撰写并实现

PEP 3106: 字典视图

The dictionary methods keys(), values(), and items() are different in Python 3.x. They return an object called a view instead of a fully materialized list.

It’s not possible to change the return values of keys(), values(), and items() in Python 2.7 because too much code would break. Instead the 3.x versions were added under the new names viewkeys(), viewvalues(), and viewitems().

 
 
 
 
  1. >>> d = dict((i*10, chr(65+i)) for i in range(26))
  2. >>> d
  3. {0: 'A', 130: 'N', 10: 'B', 140: 'O', 20: ..., 250: 'Z'}
  4. >>> d.viewkeys()
  5. dict_keys([0, 130, 10, 140, 20, 150, 30, ..., 250])

Views can be iterated over, but the key and item views also behave like sets. The & operator performs intersection, and | performs a union:

 
 
 
 
  1. >>> d1 = dict((i*10, chr(65+i)) for i in range(26))
  2. >>> d2 = dict((i**.5, i) for i in range(1000))
  3. >>> d1.viewkeys() & d2.viewkeys()
  4. set([0.0, 10.0, 20.0, 30.0])
  5. >>> d1.viewkeys() | range(0, 30)
  6. set([0, 1, 130, 3, 4, 5, 6, ..., 120, 250])

The view keeps track of the dictionary and its contents change as the dictionary is modified:

 
 
 
 
  1. >>> vk = d.viewkeys()
  2. >>> vk
  3. dict_keys([0, 130, 10, ..., 250])
  4. >>> d[260] = '&'
  5. >>> vk
  6. dict_keys([0, 130, 260, 10, ..., 250])

However, note that you can’t add or remove keys while you’re iterating over the view:

 
 
 
 
  1. >>> for k in vk:
  2. ... d[k*2] = k
  3. ...
  4. Traceback (most recent call last):
  5. File "", line 1, in
  6. RuntimeError: dictionary changed size during iteration

You can use the view methods in Python 2.x code, and the 2to3 converter will change them to the standard keys(), values(), and items() methods.

参见

PEP 3106 - 改造 dict.keys(), .values() 和 .items()

PEP written by Guido van Rossum. Backported to 2.7 by Alexandre Vassalotti; bpo-1967.

PEP 3137: memoryview 对象

The memoryview object provides a view of another object’s memory content that matches the bytes type’s interface.

 
 
 
 
  1. >>> import string
  2. >>> m = memoryview(string.letters)
  3. >>> m
  4. >>> len(m) # Returns length of underlying object
  5. 52
  6. >>> m[0], m[25], m[26] # Indexing returns one byte
  7. ('a', 'z', 'A')
  8. >>> m2 = m[0:26] # Slicing returns another memoryview
  9. >>> m2

The content of the view can be converted to a string of bytes or a list of integers:

 
 
 
 
  1. >>> m2.tobytes()
  2. 'abcdefghijklmnopqrstuvwxyz'
  3. >>> m2.tolist()
  4. [97, 98, 99, 100, 101, 102, 103, ... 121, 122]
  5. >>>

memoryview objects allow modifying the underlying object if it’s a mutable object.

 
 
 
 
  1. >>> m2[0] = 75
  2. Traceback (most recent call last):
  3. File "", line 1, in
  4. TypeError: cannot modify read-only memory
  5. >>> b = bytearray(string.letters) # Creating a mutable object
  6. >>> b
  7. bytearray(b'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ')
  8. >>> mb = memoryview(b)
  9. >>> mb[0] = '*' # Assign to view, changing the bytearray.
  10. >>> b[0:5] # The bytearray has been changed.
  11. bytearray(b'*bcde')
  12. >>>

参见

PEP 3137 - 不变字节和可变缓冲区

PEP written by Guido van Rossum. Implemented by Travis Oliphant, Antoine Pitrou and others. Backported to 2.7 by Antoine Pitrou; bpo-2396.

其他语言特性修改

对Python 语言核心进行的小改动:

Interpreter Changes

A new environment variable, PYTHONWARNINGS, allows controlling warnings. It should be set to a string containing warning settings, equivalent to those used with the -W switch, separated by commas. (Contributed by Brian Curtin; bpo-7301.)

For example, the following setting will print warnings every time they occur, but turn warnings from the Cookie module into an error. (The exact syntax for setting an environment variable varies across operating systems and shells.)

 
 
 
 
  1. export PYTHONWARNINGS=all,error:::Cookie:0

性能优化

Several performance enhancements have been added:

其他资讯

让你的专属顾问为你服务