1. 程式人生 > >Python 協程 - Coroutines

Python 協程 - Coroutines

back tor __enter__ ref 兼容 參數 error lin 關鍵字

 1 協程 - Coroutines
 2 
 3 Awaitable Objects,
 4     Awaitable Objects 通常由 __await__() 生成, 而
 5     Coroutine objects 是由 async def 關鍵字定義的函數 return 的 Awaitable Objects.
 6     Note,
 7         被 types.coroutine() or asyncio.coroutine() 裝飾的生成器叠代器對象(generator iterator objects)
 8         是沒有通過 __await__
() 生成的 Awaitable Objects. 9 10 object.__await__(self) 必須 return 一個 iterator, 用來生成 Awaitable Objects. 11 如, asyncio.Future 執行這個方法一兼容 await 表達式. 12 See also PEP 492 for additional information about awaitable objects. 13 14 Coroutine Objects, 15 Coroutine objects 是 awaitable objects, 是一個 __await__
() return 的 iterator, 16 Coroutine 的執行就是對 __await__() return 的 iterator 的叠代. 跟 iterator 一樣, 17 當 coroutine 執行完畢後 raises StopIteration, 這個異常的 value 屬性是執行返回的結果. 18 如果 coroutine raises an exception, 這個異常會被冒泡式 返回. Coroutines 不可以直接 19 raise 一個未加工過的 StopIteration exceptions. 20 21 Coroutines 有如下方法(與 generator 相似), 但是與 generators 不同的是 coroutines 不對
22 叠代提供直接的支持. Python version 3.5.2, 之後 在一個 coroutine 上多次 await 返回 23 RuntimeError exception. 24 25 coroutine.send(value) 26 開始或者恢復 coroutine 的執行. 如果參數 value = None, 為對 coroutine 的預激活. 27 若 value 不是 None, 這個方法相當於 iterator 的 send() 方法, 將使 coroutine 暫停. 28 方法的返回 (return value, StopIteration, or other exception) 上面已經描述過. 29 30 coroutine.throw(type[, value[, traceback]]) 31 在 coroutine raise specified exception. 32 這個方法對應 iterator 中的 throw() 方法, 會使 coroutine 暫停 33 34 coroutine.close() 35 使 coroutine 去初始化並退出. 對應 iterator 的 close() 方法. 36 37 Asynchronous Iterators 38 一個 asynchronous iterable 通過調用 __aiter__() 得到一個 asynchronous iterator. 39 Asynchronous iterators 可以被用在一個 async 聲明中. 40 41 object.__aiter__(self) 42 返回一個 asynchronous iterator 對象. 43 44 object.__anext__(self) 45 從 iterator 中返回一個 awaitable 對象. 當 iterator 結束的時候 46 raise StopAsyncIteration error exception 47 48 asynchronous iterable object 的例子, 49 50 class Reader: 51 async def readline(self): 52 ... 53 54 def __aiter__(self): 55 return self 56 57 async def __anext__(self): 58 val = await self.readline() 59 if val == b‘‘: 60 raise StopAsyncIteration 61 return val 62 63 Asynchronous Context Managers, 64 asynchronous context manager 是一個能夠暫停執行的 context manager . 65 Asynchronous context managers 可以通過 async with 關鍵字聲明. 66 object.__aenter__(self) 67__enter__() 類似, 不同之處在於 方法必須返回一個 awaitable 對象. 68 69 object.__aexit__(self, exc_type, exc_value, traceback), 70__exit__() 類似, 不同之處在於 方法必須返回一個 awaitable 對象. 71 72 asynchronous context manager 的例子, 73 class AsyncContextManager: 74 async def __aenter__(self): 75 await log(entering context) 76 77 async def __aexit__(self, exc_type, exc, tb): 78 await log(exiting context) 79 80 Reference, 81 Python doc. https://docs.python.org/3/reference/datamodel.html#coroutines

Python 協程 - Coroutines