当前位置:网站首页>Asynchronous iterator & asynchronous generator & asynchronous context manager
Asynchronous iterator & asynchronous generator & asynchronous context manager
2022-04-23 05:14:00 【zzzzls~】
List of articles
Asynchronous iterator
Similar to iterators , Realized __aiter__() and __anext__() Method , And return to a awaitable object
obj.__aiter__(self):
return Asynchronous iterator
obj.__anext__(self):
return Iterator next result value , Thrown at the end `StopAsyncIteration` error
# Example
import asyncio
class Reader:
def __init__(self):
self.i = 0
def __aiter__(self):
return self
async def get_next(self):
self.i += 1
if self.i >= 100:
return None
else:
return self.i
async def __anext__(self):
next = await self.get_next()
if next:
return next
else:
raise StopAsyncIteration
async def main():
# async for It needs to be written in the coprocessor function
async for item in Reader():
print(item)
asyncio.run(main())
Asynchronous context manager
Realization __aenter__() and __aexit__() The method is an asynchronous context manager
import asyncio
class AsyncContextManager:
def __init__(self):
self.conn = None
async def __aenter__(self):
print(' Enter the context ...')
self.conn = await asyncio.sleep(1)
return self
async def __aexit__(self, exc_type, exc, tb):
print(' Leave the context ...')
# self.conn.close()
async def dosomething(self):
print(' perform xxx')
return '666'
async def main():
async with AsyncContextManager() as f:
res = await f.dosomething()
print(res)
asyncio.run(main())
Asynchronous generator
import asyncio
async def gener():
for i in range(1, 100):
yield i
await asyncio.sleep(1)
async def test():
async for item in gener():
print(item)
async def main():
tasks = [asyncio.create_task(test()) for _ in range(3)]
await asyncio.wait(tasks)
asyncio.run(main())
版权声明
本文为[zzzzls~]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204220547252139.html
边栏推荐
- 低代码和无代码的注意事项
- Golang memory escape
- 好的测试数据管理,到底要怎么做?
- QPushButton slot function is triggered multiple times
- Details related to fingerprint payment
- Get the number of days between dates, get the Chinese date, get the date of the next Monday of the date, get the working day, get the rest day
- PHP counts the number of files in the specified folder
- Luogu p2731 horse riding fence repair
- Use the built-in function of win to transfer files between two computers in the same LAN (the speed is the same as that between local disks)
- Flip coin (Blue Bridge Cup)
猜你喜欢

Backup MySQL database with Navicat
![[winui3] Écrivez une copie du gestionnaire de fichiers Explorer](/img/3e/62794f1939da7f36f7a4e9dbf0aa7a.png)
[winui3] Écrivez une copie du gestionnaire de fichiers Explorer

工具在数字化转型中扮演了什么样的角色?

MySQL memo (for your own query)
![[untitled] kimpei kdboxpro's cool running lantern coexists with beauty and strength](/img/94/37d80984fe6fad84e73c2f8e6b2d52.jpg)
[untitled] kimpei kdboxpro's cool running lantern coexists with beauty and strength

MySQL circularly adds sequence numbers according to the values of a column

Jupyter notebook crawling web pages

Servlet3 0 + event driven for high performance long polling

跨境电商 | Facebook 和 Instagram:哪个社交媒体更适合你?

改进DevSecOps框架的 5 大关键技术
随机推荐
Interesting prime number problem hdu5750
独立站运营 | FaceBook营销神器——聊天机器人ManyChat
Use the built-in function of win to transfer files between two computers in the same LAN (the speed is the same as that between local disks)
Detailed explanation of concurrent topics
MySQL realizes row to column SQL
改进DevSecOps框架的 5 大关键技术
SCP command details
What are instruction cycles, machine cycles, and clock cycles?
C. Tree Infection(模拟+贪心)
[2022 ICLR] Pyraformer: Low-Complexity Pyramidal Attention for Long-Range 时空序列建模和预测
TypeError: ‘Collection‘ object is not callable. If you meant to call the ......
MySQL circularly adds sequence numbers according to the values of a column
和谐宿舍(线性dp / 区间dp)
《2021多多阅读报告》发布,95后、00后图书消费潜力攀升
2022/4/22
Define defines constants and macros, pointers and structures
One month countdown, pgconf What are the highlights of the latest outlook of asia2021 Asian Conference?
Day.js 常用方法
scp命令详解
What are the redis data types