在 Python __init__ 方法中使用异步等待

psi*_*dex 3 python async-await discord.py

我正在编写一个类,并希望在该__init__方法中使用一个异步函数来设置该类所需的一些变量。问题是,我不能这样做,因为__init__必须是同步的。

这是我的代码的相关部分(为简单起见进行了编辑,逻辑保持不变):

# This has to be called outside of the class
asyncDatabaseConnection = startDBConnection()

class discordBot(discord.Client):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        # Init is only run once, but we cant use async stuff here
        self.firstRun = True

    async def on_ready(self):
        # Other stuff happens here but it doesen't involve this question

        # on_ready is called when bot is ready, but can be called multiple times when running
        # (if bot has to reconnect to API), so we have to check
        if self.firstRun:
            await asyncDatabaseConnection.setValue("key", "value")
            self.firstRun = False

if __name__ == "__main__":
    # Instance class and start async stuff
    bot = discordBot()
    bot.run()
Run Code Online (Sandbox Code Playgroud)

如您所见,它适用于 Discord 机器人,但这并不重要,更多的是关于逻辑。

我要调用的函数是asyncDatabaseConnection.setValue("key", "value").

就像我说的,我不能调用它,__init__因为__init__它必须是同步的,所以我在 init 调用期间设置firstRunTrue,然后我可以稍后使用它来判断代码之前是否已运行过

on_ready是一个在机器人准备开始发送/接收数据时调用的函数,因此我可以将其用作第二个__init__. 问题来自于在on_ready整个程序运行过程中可以多次调用的事实,这意味着我必须进行firstRun我之前描述的检查。

这似乎有很多代码只是为了在启动时做一件事(以及在on_ready调用时增加开销,无论多小)。有没有更干净的方法来做到这一点?

Pat*_*ugh 8

这有点尴尬,但你可以创建一个Task,然后运行它并得到它的结果。如果你经常这样做,写一个辅助函数可能会有所帮助:

def run_and_get(coro):
    task = asyncio.create_task(coro)
    asyncio.get_running_loop().run_until_complete(task)
    return task.result()

class discordBot(discord.Client):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        run_and_get(asyncDatabaseConnection.setValue("key", "value"))
Run Code Online (Sandbox Code Playgroud)

这取决于有一个正在运行的事件循环,我相信它会Client.__init__设置

  • 我得到这个事件循环已经在运行 (2认同)