首頁  >  文章  >  後端開發  >  詳解Python3.6正式版新特性

詳解Python3.6正式版新特性

高洛峰
高洛峰原創
2017-03-24 17:51:151590瀏覽

依照Python官網上的計劃,Python3.6正式版期望在2016-12-16號發布,也就是這週五。從去年的5月開始,Python3.6版本就已經動手開發了,期間也斷斷續續的發布了4個Alpha版,4個Beta版,以及一個Candidate版本。
新的語法特性
1、格式化字串(Formatted string literals)
即在普通字串前面加上f 或F 前綴,其效果類似於str.format( )。例如

name = "Fred"
print(f"He said his name is {name}.") # 'He said his name is Fred.'


其效果相當於:

print("He said his name is {name}.".format(**locals()))


此外,此特性也支援嵌套字段,例如:

width = 10
precision = 4
value = decimal.Decimal("12.34567")
print(f"result: {value:{width}.{precision}}") #'result:   12.35'

##2、變數宣告語法(variable annotations)
即從Python3.5開始就有的Typehints。在Python3.5中,是這麼使用的:

from typing import List
def test(a: List[int], b: int) -> int:
  return a[0] + b
print(test([3, 1], 2))

這裡的語法檢查只在編輯器(例如Pycharm)中產生,在實際的使用中,並不進行嚴格檢查。
在Python3.6中,引入了新的語法:

from typing import List, Dict
primes: List[int] = []
captain: str  # 此时没有初始值
class Starship:
  stats: Dict[str, int] = {}

3、數字的下劃線寫法(Underscores in Numeric Literals)
即允許在數字中使用下劃線,以提高多位數字的可讀性。

a = 1_000_000_000_000_000    # 1000000000000000
b = 0x_FF_FF_FF_FF       # 4294967295

除此之外,「字串格式化」也支援「_」選項,以列印出更易讀的數字字串:

'{:_}'.format(1000000)     # '1_000_000'
'{:_x}'.format(0xFFFFFFFF)   # 'ffff_ffff'

4、非同步生成器(Asynchronous Generators)
在Python3.5中,引入了新的語法async 和await 來實現協同程序。但有個限制,不能在同一個函數體內同時使用yield 和await,在Python3.6中,這個限制被放開了,Python3.6中允許定義非同步產生器:

async def ticker(delay, to):
"""Yield numbers from 0 to *to* every *delay* seconds."""
  for i in range(to):
    yield i
    await asyncio.sleep(delay)

5、非同步解析器(Asynchronous Comprehensions)
即允許在清單list、集合set 和字典dict 解析器中使用async for 或await 語法。

result = [i async for i in aiter() if i % 2]
result = [await fun() for fun in funcs if await condition()]


新增加模組Python標準函式庫(The Standard Library)中增加了一個新的模組:secrets。這個模組用來產生一些安全性較高的隨機數,以用來管理數據,例如passwords, account authentication, security tokens, 以及related secrets等。具體用法可參考官方文件:secrets

其他新特性1、新的 PYTHONMALLOC 環境變數允許開發者設定記憶體分配器,以及註冊debug鉤子等。
2、asyncio模組更穩定、更有效率,而且不再是臨時模組,其中的API也都是穩定版的了。
3、typing模組也有了一定改進,並且不再是臨時模組。
4、datetime.strftime 和 date.strftime 開始支援ISO 8601的時間識別碼%G, %u, %V。
5、hashlib 和 ssl 模組開始支援OpenSSL1.1.0。
6、hashlib模組開始支援新的hash演算法,例如BLAKE2, SHA-3 和 SHAKE。
7、Windows上的 filesystem 和 console 預設編碼改為UTF-8。
8、json模組中的 json.load() 和 json.loads() 函數開始支援 binary 類型輸入。


以上是詳解Python3.6正式版新特性的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn