当前位置:网站首页>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
边栏推荐
- Traversal of tree
- 学习笔记:Unity CustomSRP-10-Point and Spot Shadows
- Informatics Olympiad 1955: [11noip popularization group] Swiss round | openjudge 4.1 4363: Swiss round | Luogu p1309 [noip2011 popularization group] Swiss round
- 深度学习笔记 —— 物体检测和数据集 + 锚框
- Details related to fingerprint payment
- A trinomial expression that causes a null pointer
- Where, on when MySQL external connection is used
- Jupyter notebook crawling web pages
- At pgconf Asia Chinese technology forum, listen to Tencent cloud experts' in-depth understanding of database technology
- 青岛敏捷之旅,来了!
猜你喜欢
One month countdown, pgconf What are the highlights of the latest outlook of asia2021 Asian Conference?
[2022 ICLR] Pyramid: low complexity pyramid attention for long range spatiotemporal sequence modeling and prediction
DevOps生命周期,你想知道的全都在这里了!
MySQL foreign key constraint
青岛敏捷之旅,来了!
低代码和无代码的注意事项
At pgconf Asia Chinese technology forum, listen to Tencent cloud experts' in-depth understanding of database technology
Cross border e-commerce | Facebook and instagram: which social media is more suitable for you?
Thoughts on a small program
何时适合进行自动化测试?(下)
随机推荐
7-4 is it too fat (10 points) PTA
看板快速启动指南
Redis persistence
A trinomial expression that causes a null pointer
云计算与云原生 — OpenShift 的架构设计
On distributed lock
深度学习笔记 —— 语义分割和数据集
Luogu p2731 horse riding fence repair
Use AES encryption - reuse the wisdom of predecessors
DIY is an excel version of subnet calculator
What are the redis data types
Locks and transactions in MySQL
PHP counts the number of files in the specified folder
2022/4/22
Using MySQL with Oracle
Thoughts on a small program
Chapter III project schedule management of information system project manager summary
MySQL slow query
Summary of MySQL knowledge points
[WinUI3]编写一个仿Explorer文件管理器