小编Ron*_*uya的帖子

如何在异步 Python 函数中指定返回类型?

在 TypeScript 中,你会做类似的事情

async function getString(word: string): Promise<string> {
   return word;
}
Run Code Online (Sandbox Code Playgroud)

我如何在 Python 中做同样的事情?我尝试了以下方法:

async def get_string(word: str) -> Coroutine[str]:
    return word
Run Code Online (Sandbox Code Playgroud)

并得到了这个回溯:

TypeError: Too few parameters for typing.Coroutine; actual 1, expected 3
Run Code Online (Sandbox Code Playgroud)

所以Coroutine预计有 3 种类型。但为什么?在这种情况下,它们应该是什么?

这也在文档中指定,但我仍然不明白

python types python-asyncio mypy

6
推荐指数
2
解决办法
2732
查看次数

如何在异步循环关闭之前等待对象的__del__完成?

我有一个将在其中包含aiohttp.ClientSession对象的类。

通常当您使用

async with aiohttp.ClientSession() as session:  
   # some code
Run Code Online (Sandbox Code Playgroud)

由于调用了会话的__aexit__方法,因此该会话将关闭。

我无法使用上下文管理器,因为我想在对象的整个生命周期中保持会话的持久性。

这有效:

import asyncio
import aiohttp

class MyAPI:
    def __init__(self):
        self.session = aiohttp.ClientSession()

    def __del__(self):
        # Close connection when this object is destroyed
        print('In __del__ now')
        asyncio.shield(self.session.__aexit__(None, None, None))



async def main():
    api = MyAPI()

asyncio.run(main())
Run Code Online (Sandbox Code Playgroud)

但是,如果在某些地方引发了异常,则在完成__aexit__方法之前将关闭事件循环。我该如何克服?

堆栈跟踪:

Traceback (most recent call last):
  File "/home/ron/.PyCharm2018.3/config/scratches/async.py", line 19, in <module>
    asyncio.run(main())
  File "/usr/local/lib/python3.7/asyncio/runners.py", line 43, in run
    return loop.run_until_complete(main)
  File "/usr/local/lib/python3.7/asyncio/base_events.py", line 568, in run_until_complete
    return future.result()
  File "/home/ron/.PyCharm2018.3/config/scratches/async.py", line …
Run Code Online (Sandbox Code Playgroud)

python contextmanager python-asyncio aiohttp

1
推荐指数
2
解决办法
416
查看次数

标签 统计

python ×2

python-asyncio ×2

aiohttp ×1

contextmanager ×1

mypy ×1

types ×1