'Call async function in Enum
I want to refactor my code from sync to async. I use Python and FastAPI.
I use the method which calls async function in Enumaration.
For example:
from enum import Enum
from app.story import get_story
StoriesEnum = Enum(
"StoriesEnum", {story: story for story in get_story.story_list},
)
get_story is an async function that returns Story class and it has story_list.
How can I await the get_story.story_list?
I tried:
- asyncio.run()
- get_event_loop()
- async generator
with no successful result. They don't work because await is outside the async function.
Solution 1:[1]
As per the documentation:
You might have noticed that
awaitcan only be used inside of functions defined withasync def.But at the same time, functions defined with
async defhave to be "awaited". So, functions withasync defcan only be called inside of functions defined withasync deftoo.
Thus, what you could do is:
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})
P.S. It would really help though, if you provided a minimal reproducible example.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
