Python 3.5 有什麼新功能¶
- 編輯者:
Elvis Pranskevichus <elvis@magic.io>, Yury Selivanov <yury@magic.io>
本文介紹了 Python 3.5 與 3.4 相比多了哪些新功能。Python 3.1 已於 2015 年 9 月 13 日發布。完整詳情請見 changelog。
也參考
PEP 478 - Python 3.5 發佈時程
發布重點摘要¶
新增語法特性:
PEP 492,使用 async 和 await 語法的協程
PEP 465, a new matrix multiplication operator:
a @ b.PEP 448, additional unpacking generalizations.
新的函式庫模組:
新的內建功能
bytes % args,bytearray % args: PEP 461 -- Adding%formatting to bytes and bytearray.New
bytes.hex(),bytearray.hex()andmemoryview.hex()methods. (Contributed by Arnon Yaari in bpo-9951.)memoryviewnow supports tuple indexing (including multi-dimensional). (Contributed by Antoine Pitrou in bpo-23632.)Generators have a new
gi_yieldfromattribute, which returns the object being iterated byyield fromexpressions. (Contributed by Benno Leslie and Yury Selivanov in bpo-24450.)A new
RecursionErrorexception is now raised when maximum recursion depth is reached. (Contributed by Georg Brandl in bpo-19235.)
CPython 實作改進:
When the
LC_TYPElocale is the POSIX locale (Clocale),sys.stdinandsys.stdoutnow use thesurrogateescapeerror handler, instead of thestricterror handler. (Contributed by Victor Stinner in bpo-19977.).pyofiles are no longer used and have been replaced by a more flexible scheme that includes the optimization level explicitly in.pycname. (See PEP 488 overview.)Builtin and extension modules are now initialized in a multi-phase process, which is similar to how Python modules are loaded. (See PEP 489 overview.)
標準函式庫中的顯著改進
collections.OrderedDictis now implemented in C, which makes it 4 to 100 times faster.The
sslmodule gained support for Memory BIO, which decouples SSL protocol handling from network IO.The new
os.scandir()function provides a better and significantly faster way of directory traversal.functools.lru_cache()has been mostly reimplemented in C, yielding much better performance.The new
subprocess.run()function provides a streamlined way to run subprocesses.The
tracebackmodule has been significantly enhanced for improved performance and developer convenience.
安全性改進:
SSLv3 is now disabled throughout the standard library. It can still be enabled by instantiating a
ssl.SSLContextmanually. (See bpo-22638 for more details; this change was backported to CPython 3.4 and 2.7.)HTTP cookie parsing is now stricter, in order to protect against potential injection attacks. (Contributed by Antoine Pitrou in bpo-22796.)
Windows 改進:
Windows 的新安裝程式取代了舊的 MSI。詳情請參見 在 Windows 上使用 Python。
Windows builds now use Microsoft Visual C++ 14.0, and extension modules should use the same.
Please read on for a comprehensive list of user-facing changes, including many other smaller improvements, CPython optimizations, deprecations, and potential porting issues.
新增功能¶
PEP 492 - 使用 async 和 await 語法的協程¶
PEP 492 greatly improves support for asynchronous programming in Python by adding awaitable objects, coroutine functions, asynchronous iteration, and asynchronous context managers.
Coroutine functions are declared using the new async def syntax:
>>> async def coro():
... return 'spam'
Inside a coroutine function, the new await expression can be used
to suspend coroutine execution until the result is available. Any object
can be awaited, as long as it implements the awaitable protocol by
defining the __await__() method.
PEP 492 also adds async for statement for convenient iteration
over asynchronous iterables.
An example of a rudimentary HTTP client written using the new syntax:
import asyncio
async def http_get(domain):
reader, writer = await asyncio.open_connection(domain, 80)
writer.write(b'\r\n'.join([
b'GET / HTTP/1.1',
b'Host: %b' % domain.encode('latin-1'),
b'Connection: close',
b'', b''
]))
async for line in reader:
print('>>>', line)
writer.close()
loop = asyncio.get_event_loop()
try:
loop.run_until_complete(http_get('example.com'))
finally:
loop.close()
Similarly to asynchronous iteration, there is a new syntax for asynchronous context managers. The following script:
import asyncio
async def coro(name, lock):
print('coro {}: waiting for lock'.format(name))
async with lock:
print('coro {}: holding the lock'.format(name))
await asyncio.sleep(1)
print('coro {}: releasing the lock'.format(name))
loop = asyncio.get_event_loop()
lock = asyncio.Lock()
coros = asyncio.gather(coro(1, lock), coro(2, lock))
try:
loop.run_until_complete(