创新互联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 版的的一些关键后果:

  • 如上所述,与早期的2.x版本相比,2.7版本的维护时间更长。目前,预计核心开发团队将继续支持Python 2.7(接收安全更新和其他错误修复),直到至少2020年(首次发布后10年,相比之下,通常的支持期为18—24个月)。

  • 随着 Python 2.7 标准库的老化,有效地利用 Python 包索引(直接或通过重新分发者)对 Python 2 用户来说变得更加重要。除了各种任务的第三方包之外,可用的包还包括与 Python 2 兼容的 Python 3 标准库中的新模块和功能的后端移植,以及各种工具和库,这些工具和库可以让用户更容易迁移到 Python 3。 Python 包用户指南 提供了从 Python 包索引的下载和安装软件的指导。

  • 虽然现在增强 Python 2 的首选方法是在Python包索引上发布新包,但这种方法不一定适用于所有情况,尤其是与网络安全相关的情况。在一些特殊情况下,如果在PyPI上发布新的或更新的包无法得到充分的处理,则可以使用Python增强建议过程来提出直接在Python 2标准库中添加新功能。任何此类添加及其添加的维护版本将在下面的 New Features Added to Python 2.7 Maintenance Releases 部分中注明。

对于希望从 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:

  • 用于集合字面值的语法 ({1,2,3} 是一个可变集合)。

  • 字典与集合推导式 ({i: i*2 for i in range(3)})。

  • 单个 with 语句中使用多个上下文管理器。

  • 一个 io 库的新版本,用 C 重写以提升性能。

  • PEP 372: Adding an Ordered Dictionary to collections 所描述的有序字典类型。

  • PEP 378: 千位分隔符的格式说明符 所描述的新的 "," 格式说明符。

  • memoryview 对象。

  • importlib 模块的一个较小子集,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.

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.

  • 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.

参见

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:

  • The SysLogHandler class now supports syslogging over TCP. The constructor has a socktype parameter giving the type of socket to use, either socket.SOCK_DGRAM for UDP or socket.SOCK_STREAM for TCP. The default protocol remains UDP.

  • Logger instances gained a getChild() method that retrieves a descendant logger using a relative path. For example, once you retrieve a logger by doing log = getLogger('app'), calling log.getChild('network.listen') is equivalent to getLogger('app.network.listen').

  • The LoggerAdapter class gained an isEnabledFor() method that takes a level and returns whether the underlying logger would process a message of that level of importance.

参见

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 语言核心进行的小改动:

  • The syntax for set literals has been backported from Python 3.x. Curly brackets are used to surround the contents of the resulting mutable set; set literals are distinguished from dictionaries by not containing colons and values. {} continues to represent an empty dictionary; use set() for an empty set.

       
       
       
       
    1. >>> {1, 2, 3, 4, 5}
    2. set([1, 2, 3, 4, 5])
    3. >>> set() # empty set
    4. set([])
    5. >>> {} # empty dict
    6. {}

    Backported by Alexandre Vassalotti; bpo-2335.

  • Dictionary and set comprehensions are another feature backported from 3.x, generalizing list/generator comprehensions to use the literal syntax for sets and dictionaries.

       
       
       
       
    1. >>> {x: x*x for x in range(6)}
    2. {0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
    3. >>> {('a'*x) for x in range(6)}
    4. set(['', 'a', 'aa', 'aaa', 'aaaa', 'aaaaa'])

    Backported by Alexandre Vassalotti; bpo-2333.

  • The with statement can now use multiple context managers in one statement. Context managers are processed from left to right and each one is treated as beginning a new with statement. This means that:

       
       
       
       
    1. with A() as a, B() as b:
    2. ... suite of statements ...

    相当于:

       
       
       
       
    1. with A() as a:
    2. with B() as b:
    3. ... suite of statements ...

    The contextlib.nested() function provides a very similar function, so it’s no longer necessary and has been deprecated.

    (Proposed in https://codereview.appspot.com/53094; implemented by Georg Brandl.)

  • Conversions between floating-point numbers and strings are now correctly rounded on most platforms. These conversions occur in many different places: str() on floats and complex numbers; the float and complex constructors; numeric formatting; serializing and deserializing floats and complex numbers using the marshal, pickle and json modules; parsing of float and imaginary literals in Python code; and Decimal-to-float conversion.

    Related to this, the repr() of a floating-point number x now returns a result based on the shortest decimal string that’s guaranteed to round back to x under correct rounding (with round-half-to-even rounding mode). Previously it gave a string based on rounding x to 17 decimal digits.

    The rounding library responsible for this improvement works on Windows and on Unix platforms using the gcc, icc, or suncc compilers. There may be a small number of platforms where correct operation of this code cannot be guaranteed, so the code is not used on such systems. You can find out which code is being used by checking sys.float_repr_style, which will be short if the new code is in use and legacy if it isn’t.

    Implemented by Eric Smith and Mark Dickinson, using David Gay’s dtoa.c library; bpo-7117.

  • Conversions from long integers and regular integers to floating point now round differently, returning the floating-point number closest to the number. This doesn’t matter for small integers that can be converted exactly, but for large numbers that will unavoidably lose precision, Python 2.7 now approximates more closely. For example, Python 2.6 computed the following:

       
       
       
       
    1. >>> n = 295147905179352891391
    2. >>> float(n)
    3. 2.9514790517935283e+20
    4. >>> n - long(float(n))
    5. 65535L

    Python 2.7’s floating-point result is larger, but much closer to the true value:

       
       
       
       
    1. >>> n = 295147905179352891391
    2. >>> float(n)
    3. 2.9514790517935289e+20
    4. >>> n - long(float(n))
    5. -1L

    (Implemented by Mark Dickinson; bpo-3166.)

    Integer division is also more accurate in its rounding behaviours. (Also implemented by Mark Dickinson; bpo-1811.)

  • Implicit coercion for complex numbers has been removed; the interpreter will no longer ever attempt to call a __coerce__() method on complex objects. (Removed by Meador Inge and Mark Dickinson; bpo-5211.)

  • The str.format() method now supports automatic numbering of the replacement fields. This makes using str.format() more closely resemble using %s formatting:

       
       
       
       
    1. >>> '{}:{}:{}'.format(2009, 04, 'Sunday')
    2. '2009:4:Sunday'
    3. >>> '{}:{}:{day}'.format(2009, 4, day='Sunday')
    4. '2009:4:Sunday'

    The auto-numbering takes the fields from left to right, so the first {...} specifier will use the first argument to str.format(), the next specifier will use the next argument, and so on. You can’t mix auto-numbering and explicit numbering — either number all of your specifier fields or none of them — but you can mix auto-numbering and named fields, as in the second example above. (Contributed by Eric Smith; bpo-5237.)

    Complex numbers now correctly support usage with format(), and default to being right-aligned. Specifying a precision or comma-separation applies to both the real and imaginary parts of the number, but a specified field width and alignment is applied to the whole of the resulting 1.5+3j output. (Contributed by Eric Smith; bpo-1588 and bpo-7988.)

    The ‘F’ format code now always formats its output using uppercase characters, so it will now produce ‘INF’ and ‘NAN’. (Contributed by Eric Smith; bpo-3382.)

    A low-level change: the object.__format__() method now triggers a PendingDeprecationWarning if it’s passed a format string, because the __format__() method for object converts the object to a string representation and formats that. Previously the method silently applied the format string to the string representation, but that could hide mistakes in Python code. If you’re supplying formatting information such as an alignment or precision, presumably you’re expecting the formatting to be applied in some object-specific way. (Fixed by Eric Smith; bpo-7994.)

  • The int() and long() types gained a bit_length method that returns the number of bits necessary to represent its argument in binary:

       
       
       
       
    1. >>> n = 37
    2. >>> bin(n)
    3. '0b100101'
    4. >>> n.bit_length()
    5. 6
    6. >>> n = 2**123-1
    7. >>> n.bit_length()
    8. 123
    9. >>> (n+1).bit_length()
    10. 124

    (Contributed by Fredrik Johansson and Victor Stinner; bpo-3439.)

  • The import statement will no longer try an absolute import if a relative import (e.g. from .os import sep) fails. This fixes a bug, but could possibly break certain import statements that were only working by accident. (Fixed by Meador Inge; bpo-7902.)

  • It’s now possible for a subclass of the built-in unicode type to override the __unicode__() method. (Implemented by Victor Stinner; bpo-1583863.)

  • The bytearray type’s translate() method now accepts None as its first argument. (Fixed by Georg Brandl; bpo-4759.)

  • When using @classmethod and @staticmethod to wrap methods as class or static methods, the wrapper object now exposes the wrapped function as their __func__ attribute. (Contributed by Amaury Forgeot d’Arc, after a suggestion by George Sakkis; bpo-5982.)

  • When a restricted set of attributes were set using __slots__, deleting an unset attribute would not raise AttributeError as you would expect. Fixed by Benjamin Peterson; bpo-7604.)

  • Two new encodings are now supported: “cp720”, used primarily for Arabic text; and “cp858”, a variant of CP 850 that adds the euro symbol. (CP720 contributed by Alexander Belchenko and Amaury Forgeot d’Arc in bpo-1616979; CP858 contributed by Tim Hatch in bpo-8016.)

  • The file object will now set the filename attribute on the IOError exception when trying to open a directory on POSIX platforms (noted by Jan Kaliszewski; bpo-4764), and now explicitly checks for and forbids writing to read-only file objects instead of trusting the C library to catch and report the error (fixed by Stefan Krah; bpo-5677).

  • The Python tokenizer now translates line endings itself, so the compile() built-in function now accepts code using any line-ending convention. Additionally, it no longer requires that the code end in a newline.

  • Extra parentheses in function definitions are illegal in Python 3.x, meaning that you get a syntax error from def f((x)): pass. In Python3-warning mode, Python 2.7 will now warn about this odd usage. (Noted by James Lingard; bpo-7362.)

  • It’s now possible to create weak references to old-style class objects. New-style classes were always weak-referenceable. (Fixed by Antoine Pitrou; bpo-8268.)

  • When a module object is garbage-collected, the module’s dictionary is now only cleared if no one else is holding a reference to the dictionary (bpo-7140).

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:

  • A new opcode was added to perform the initial setup for with statements, looking up the __enter__() and __exit__() methods. (Contributed by Benjamin Peterson.)

  • The garbage collector now performs better for one common usage pattern: when many objects are being allocated without deallocating any of them. This would previously take quadratic time for garbage collection, but now the number of full garbage collections is reduced as the number of objects on the heap grows. The new logic only performs a full garbage collection pass when the middle generation has been collected 10 times and when the number of survivor objects from the middle generation exceeds 10% of the number of objects in the oldest generation. (Suggested by Martin von Löwis and implemented by Antoine Pitrou; bpo-4074.)

  • The garbage collector tries to avoid tracking simple containers which can’t be part of a cycle. In Python 2.7, this is now true for tuples and dicts containing atomic types (such as ints, strings, etc.). Transitively, a dict containing tuples of atomic types won’t be tracked either. This helps reduce the cost of each garbage collection by decreasing the number of objects to be considered and traversed by the collector. (Contributed by Antoine Pitrou; bpo-4688.)

  • Long integers are now stored internally either in base 2**15 or in base 2**30, the base being determined at build time. Previously, they were always stored in base 2**15. Using base 2**30 gives significant performance improvements on 64-bit machines, but benchmark results on 32-bit machines have been mixed. Therefore, the default is to use base 2**30 on 64-bit machines and base 2**15 on 32-bit machines; on Unix, there’s a new configure option --enable-big-digits that can be used to override this default.

    Apart from the performance improvements this change should be invisible to end users, with one exception: for testing and debugging purposes there’s a new structseq sys.long_info that provides information about the internal format, giving the number of bits per digit and the size in bytes of the C type used to store each digit:

       
       
       
       
    1. >>> import sys
    2. >>> sys.long_info
    3. sys.long_info(bits_per_digit=30, sizeof_digit=4)

    (由 Mark Dickinson在 bpo-4258 贡献)

    Another set of changes made long objects a few bytes smaller: 2 bytes smaller on 32-bit systems and 6 bytes on 64-bit. (Contributed by Mark Dickinson; bpo-5260.)

  • The division algorithm for long integers has been made faster by tightening the inner loop, doing shifts instead of multiplications, and fixing an unnecessary extra iteration. Various benchmarks show speedups of between 50% and 150% for long integer divisions and modulo operations. (Contributed by Mark Dickinson; bpo-5512.) Bitwise operations are also significantly faster (initial patch by Gregory Smith; bpo-1087418).

  • The implementation of % checks for the left-side operand being a Python string and special-cases it; this results in a 1—3% performance increase for applications that frequently use % with strings, such as templating libraries. (Implemented by Collin Winter; bpo-5176.)

  • List comprehensions with an if condition are compiled into faster bytecode. (Patch by Antoine Pitrou, back-ported to 2.7 by Jeffrey Yasskin; bpo-4715.)

  • Converting an integer or long integer to a decimal string was made faster by special-casing base 10 instead of using a generalized conversion function that supports arbitrary bases. (Patch by Gawain Bolton; bpo-6713.)

  • The split(), replace(), rindex(), rpartition(), and rsplit() methods of string-like types (strings, Unicode strings, and bytearray objects) now use a fast reverse-search algorithm instead of a character-by-character scan. This is sometimes faster by a factor of

    分享名称:创新互联Python教程:Python2.7有什么新变化
    URL链接:http://www.hantingmc.com/qtweb/news7/555057.html

    网站建设、网络推广公司-创新互联,是专注品牌与效果的网站制作,网络营销seo公司;服务项目有等

    广告

    声明:本网站发布的内容(图片、视频和文字)以用户投稿、用户转载内容为主,如果涉及侵权请尽快告知,我们将会在第一时间删除。文章观点不代表本网站立场,如需处理请联系客服。电话:028-86922220;邮箱:631063699@qq.com。内容未经允许不得转载,或转载时需注明来源: 创新互联