文章來源
https://docs.python.org/3/whatsnew/3.5.html
python3.5 新特性
標準庫的重大改進:
collections.OrderedDict 改用C實現,性能快4到100倍。
ssl模塊獲得了 對 Memory BIO 的支持,它將SSL協議處理與網絡IO分離。
os.scandir()函數提供了一種更快速的目錄遍歷方式。
functools.lru_cache() 中大部分方法在C中重新實現,產生了更好的性能。
subprocess.run()函數提供了一種簡化的方法來運行子進程。
traceback模塊性能顯着增強。
新功能
PEP 492通過添加awaitable objects, coroutine functions, asynchronous iteration, asynchronous context managers,改進了Python中異步編程的支持。
使用新語法聲明協程函數:
聲明協程函數:async def
異步迭代: async for
異步上下文管理器:async with
注意點:
1、await表達式可用於暫停協程執行,直到結果可用。只要通過定義__await__()方法實現等待協議,就可以等待任何對象。
2、async for 和 async with只能用在async def聲明的函數中使用。
使用新語法編寫的基本HTTP客戶端示例:
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()
異步上下文管理器舉例:
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(coros)
finally:
loop.close()
輸出:
coro 2: waiting for lock
coro 2: holding the lock
coro 1: waiting for lock
coro 2: releasing the lock
coro 1: holding the lock
coro 1: releasing the lock
PEP 448 擴展了*和**的拆包使用範圍。現在可以在函數調用中使用任意數量的拆包:
>>> print(*[1], *[2], 3, *[4, 5])
1 2 3 4 5
>>> def fn(a, b, c, d):
... print(a, b, c, d)
>>> fn(**{'a': 1, 'c': 3}, **{'b': 2, 'd': 4})
1 2 3 4
類似地,元組,列表,集和字典顯示允許多個解包(請參閱表達式列表和字典顯示):
>>> *range(4), 4
(0, 1, 2, 3, 4)
>>> [*range(4), 4]
[0, 1, 2, 3, 4]
>>> {*range(4), 4, *(5, 6, 7)}
{0, 1, 2, 3, 4, 5, 6, 7}
>>> {'x': 1, **{'y': 2}}
{'x': 1, 'y': 2}
PEP 484 - 類型提示
從Python3.0開始,函數註釋語法一直是Python的特性,然而PEP 3107並沒有定義註釋的語法。
PEP 484引入了provisional module,以提供這些標準定義和工具,以及一些不適用註釋的情況的約定。
例如,這是一個簡單的函數,其參數和返回類型在註釋中聲明:
def greeting(name: str) -> str:
return 'Hello ' + name
在運行時註釋實現了__annotations__方法,但是並不會進行類型檢查。
PEP 471 - os.scandir()函數 - 更好更快的目錄迭代器
os.scandir()返回一個迭代器,而不是返回文件名列表。os.walk()也使用scandir實現。
舉例,打印出指定目錄path下文件名以‘測試’開頭的文件:
for entry in os.scandir(path):
if not entry.name.startswith(‘測試’) and entry.is_file():
print(entry.name)
PEP 479:更改生成器內的StopIteration處理
Python 3.4 版本以及之前,當生成器迭代結束時會拋出 StopIteration 異常,可能會引起一些未知的bug, 在3.5 以後該異常會替換爲 RuntimeError 異常。
這是一個向後不兼容的更改,必須導入__future__:
>>> from __future__ import generator_stop
>>> def gen():
... next(iter([]))
... yield
...
>>> next(gen())
Traceback (most recent call last):
File "<stdin>", line 2, in gen
StopIteration
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
RuntimeError: generator raised StopIteration
如果沒有__future__導入,只要在生成器內引發StopIteration異常,就會引發PendingDeprecationWarning。
PEP 485:用於測試近似值的函數
PEP 485 添加了math.isclose()和cmath.isclose(),根據給定的兩個值,絕對公差或相對公差來判斷確定是否被認爲是接近的。絕對公差或相對公差是isclose方法的參數,是給定的兩個值之間允許的最大差異:
>>> import math
>>> a = 5.0
>>> b = 4.99998
>>> math.isclose(a, b, rel_tol=1e-5)
True
>>> math.isclose(a, b, rel_tol=1e-6)
False
也可以使用絕對公差來比較兩個值,絕對容差必須是非負值:
>>> import math
>>> a = 5.0
>>> b = 4.99998
>>> math.isclose(a, b, abs_tol=0.00003)
True
>>> math.isclose(a, b, abs_tol=0.00001)
False
不推薦內容
- async 和 await 將成爲Python 3.7中的關鍵字。
- CPython 3.5不支持Microsoft Windows XP 操作系統。
- 不推薦使用的Python模塊,函數和方法:
- formatter模塊現已逐漸完全棄用,將在Python 3.6中刪除。
- asyncio.async()函數已棄用,新增 asyncio.ensure_future()。
- 不推薦使用format(format_string, *args, **kwargs)傳入format_string的形式格式化字符串。