Python3.8 特性介紹

簡(jiǎn)介

Python3.8 已經(jīng)發(fā)布了, 官方文檔看這里
What’s New In Python 3.8.

介紹一些 Python3.8 中的新特性.

海象表達(dá)式 :=

新的語(yǔ)法 := 將給變量賦值, 這個(gè)變量是更大的表達(dá)式的一部分.

if (n := len(a)) > 10:
  print(f"List is too long ({n} elements, expected <= 10)")

用在 if 判斷中, 避免調(diào)用 len() 兩次.

discount = 0.0
if (mo := re.search(r'(\d+)% discount', advertisement)):
  discount = float(mo.group(1)) / 100.0

正則表達(dá)式匹配和獲取結(jié)果的時(shí)候.

# Loop over fixed length blocks
while (block := f.read(256)) != '':
  process(block)

用在 while 循環(huán)中, 可以同時(shí)取值, 并判斷是否為空.

[clean_name.title() for name in names
 if (clean_name := normalize('NFC', name)) in allowed_names]

用在列表推導(dǎo)中.

完整介紹看 PEP 572.

僅位置參數(shù) /

新的函數(shù)參數(shù)語(yǔ)法 / 指明有些函數(shù)參數(shù)必須被指定為位置參數(shù), 不能被用作關(guān)鍵字參數(shù).

def f(a, b, /, c, d, *, e, f):
  print(a, b, c, d, e, f)

在上面的例子中, a 和 b 是僅位置參數(shù), c 和 d 既可以是位置參數(shù)又可以是關(guān)鍵字參數(shù),
e 和 f 必須是關(guān)鍵字參數(shù).

>>> def f(a, b, /, **kwargs):
...     print(a, b, kwargs)
...
>>> f(10, 20, a=1, b=2, c=3)         # a and b are used in two ways
10 20 {'a': 1, 'b': 2, 'c': 3}

僅位置參數(shù)的參數(shù)名在 **kwargs 中仍舊可用.

class Counter(dict):
  def __init__(self, iterable=None, /, **kwds):
    # Note "iterable" is a possible keyword argument

完整介紹看 PEP 570.

f-strings 說(shuō)明符 =

f-strings 增加了 = 說(shuō)明符, f'{expr=}' 會(huì)被擴(kuò)展為表達(dá)式的文本,
加上一個(gè)等號(hào), 和一個(gè)執(zhí)行表達(dá)式的結(jié)果.

>>> user = 'eric_idle'
>>> member_since = date(1975, 7, 31)
>>> f'{user=} {member_since=}'
"user='eric_idle' member_since=datetime.date(1975, 7, 31)"

啟動(dòng)異步 REPL

使用 python -m asyncio 啟動(dòng)一個(gè)異步的 REPL,
可以直接在 top-level 級(jí)別使用 await,
不用在封裝到函數(shù)中了.

unittest 支持異步

import unittest

class TestRequest(unittest.IsolatedAsyncioTestCase):

    async def asyncSetUp(self):
        self.connection = await AsyncConnection()

    async def test_get(self):
        response = await self.connection.get("https://example.com")
        self.assertEqual(response.status_code, 200)

    async def asyncTearDown(self):
        await self.connection.close()


if __name__ == "__main__":
    unittest.main()
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容