Python 3.8新特徵之asyncio REPL

我最近都在寫一些Python 3.8的新功能介紹的文章,在自己的項目中也在提前體驗新的Python版本。這篇文章主要介紹了Python 3.8新特徵之asyncio REPL,需要的朋友可以參考下

前言

我最近都在寫一些Python 3.8的新功能介紹的文章,在自己的項目中也在提前體驗新的Python版本。爲什麼我對這個Python 3.8這麼有興趣呢?主要是因爲在Python 2停止官方維護的2020年來臨之前,Python 3.8是最後一個大版本,雖然還沒有公佈Python 3.9的發佈時間表,但是按過去的經驗,我覺得至少等Python 3.8.4發佈之後纔可能發佈Python 3.9.0,那會應該已經在2020年年末了。所以大家最近2年的話題都會是Python 3.8。本週五(2019-05-31)將發佈3.8.0 beta 1,這幾天開發者們都在抓緊時間合併代碼趕上Python 3.8最後一班車。這幾天我將陸續分享幾個新合併的特性。今天先說 asyncio REPL

REPL

REPL是 Read-Eval-Print Loop 的縮寫,是一種簡單的,交互式的編程環境:

  • Read。獲得用戶輸入
  • Eval。對輸入求值
  • Print。打印,輸出求值的結果
  • Loop。循環,可以不斷的重複Read-Eval-Print

REPL對於學習一門新的編程語言非常有幫助,你可以再這個交互環境裏面通過輸出快速驗證你的理解是不是正確。CPython自帶了一個這樣的編程環境:

 python
Python 3.7.1 (default, Dec 13 2018, 22:28:16)
[Clang 10.0.0 (clang-1000.11.45.5)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> def a():
...   return 'A'
...
>>> a()
'A'

不過官方自帶的這個環境功能非常有限,有經驗的Python開發者通常會使用IPython,我寫的大部分文章裏面的代碼都在IPython裏面執行的, 而且IPython從 7.0開始支持了Async REPL:

ipython

defPython 3.7.1 (default, Dec 13 2018, 22:28:16)
Type 'copyright', 'credits' or 'license' for more information
IPython 7.5.0 -- An enhanced Interactive Python. Type '?' for help.
In [1]: def a():
  ...:   return 'A'
  ...:
In [2]: a()
Out[2]: 'A'
In [3]: import asyncio
In [4]: async def b():
  ...:   await asyncio.sleep(1)
  ...:   return 'B'
  ...:
In [5]: await b()
Out[5]: 'B'

In [6]: asyncio.run(b())
Out[6]: 'B'

簡單地說,就是在IPython裏面可以直接使用await,而不必用 asyncio.run(b()) 。這個在官方REPL裏面是不行的:

python

Python 3.7.1 (default, Dec 13 2018, 22:28:16)
[Clang 10.0.0 (clang-1000.11.45.5)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import asyncio
>>> async def b():
...   await asyncio.sleep(1)
...   return 'B'
...
>>> await b()
 File "<stdin>", line 1
SyntaxError: 'await' outside function

是的,await只能在異步函數裏面纔可以使用。

Python 3.8的asyncio REPL

好消息是官方REPL也與時俱進,支持asyncio REPL了。具體細節可以看延伸閱讀鏈接1: 

./python.exe -m asyncio
asyncio REPL 3.8.0a4+ (heads/master:8cd5165ba0, May 27 2019, 22:28:15)
[Clang 10.0.0 (clang-1000.11.45.5)] on darwin
Use "await" directly instead of "asyncio.run()".
Type "help", "copyright", "credits" or "license" for more information.
>>> import asyncio
>>> async def b():
...   await asyncio.sleep(1)
...   return 'B'
...
>>> await b()
'B'
>>> async def c():
...   await asyncio.sleep(1)
...   return 'C'
...
>>> task = asyncio.create_task(c())
>>> await task
'C'
>>> await asyncio.sleep(1)

注意激活REPL不是直接輸入python,而是要用 python -m asyncio ,另外那個 import asyncio 是激活REPL時自動幫你輸入的。

延伸閱讀

先別看代碼,看看你能不能實現這個功能 :yum:

https://github.com/python/cpython/pull/13472

總結

以上所述是小編給大家介紹的Python 3.8新特徵之asyncio REPL,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回覆大家的。在此也非常感謝大家對神馬文庫網站的支持!
如果你覺得本文對你有幫助,歡迎轉載,煩請註明出處,謝謝!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章