如何在Python Enum中调用异步函数?

问题描述 投票:0回答:1

我想将我的代码从

sync
重构为
async
。我使用 Python 和 FastAPI。 我使用在枚举中调用
async
函数的方法。

例如:

from enum import Enum
from app.story import get_story

    StoriesEnum = Enum(
        "StoriesEnum", {story: story  for story in get_story.story_list},
    )

get_story
是一个
async
函数,返回
Story
类,并且它具有
story_list

我怎样才能

await
get_story.story_list

我尝试过:

  • asyncio.run()
  • get_event_loop()
  • async
    发电机

没有成功的结果。它们不起作用,因为

await
位于
async
函数之外。

python async-await enums python-asyncio fastapi
1个回答
0
投票

根据文档

您可能已经注意到,

await
只能在函数内部使用 用
async def
定义。

但同时,用

async def
定义的函数必须是 “等待”。因此,具有
async def
的函数只能在 内部调用 也用
async def
定义函数。

因此,你可以做的是:

import asyncio

async def go(): 
    return Enum("StoriesEnum", {s:s for s in (await get_story()).story_list.value})

StoriesEnum = asyncio.run(go())
print({e:e.value for e in StoriesEnum})

请查看这个答案,了解有关 FastAPI 和 Python 中的

async
/
await
的更多详细信息。

© www.soinside.com 2019 - 2024. All rights reserved.