用async / await重新分配变量?

时间:2017-02-07 01:57:52

标签: python python-3.x async-await

我正在尝试使用discord.py创建一个简单的discord bot,以获得乐趣。 我正在努力完全理解asyncio的工作方式,并且我在覆盖/重新分配变量时遇到了问题。

log_channel = "8765327525217520521501"

@client.event
async def on_message(message):
    if message.author == client.user:
        return

    if message.content.startswith('!logchannel'):
        if message.content == "!logchannel":
            await client.send_message(message.channel, "```\n logchannel: 
            \r - Changes the channel this bot logs to. 
            \r - Takes the numerical channel ID as an argument 
            \r - E.g. !logchannel 123456789 ```")
        else:
            nc = message.content.split()[1]
            try:
                await client.send_message(client.get_channel(nc), "Testing new channel to be used for logs...")
            except discord.NotFound:
                await client.send_message(message.channel, "No channel was found with that ID.")
            except discord.Forbidden:
                await client.send_message(message.channel, "I Don't have permissions to use that channel!")
            except discord.HTTPException:
                await client.send_message(message.channel, "There was an error communciating with the server, please try again.")
            except InvalidArgument:
                await client.send_message(message.channel, "No channel was found with that ID.")
            else:
                await client.send_message(client.get_channel(log_channel), "Logging Channel Updated.")
                await client.send_message(message.channel, "Logging Channel Updated.")
                lmsg = 'Logging channel was updated to {} on {}'
                log.write(lmsg.format(message.channel,logtime))
                log_channel = nc

尝试覆盖log_channel变量会导致“在赋值前引用”异常。如果我不尝试覆盖,那么它可以获得变量的值。

我认为这是因为异步的工作原理,但是我并不完全理解这一点,我使用的是示例作为指南。

1 个答案:

答案 0 :(得分:0)

这与async / await无关。如果在函数范围内的任何位置分配名称,则该名称对于整个函数是本地的(甚至在您实际分配给它之前)。所以你有两个版本的log_channel:本地版本和全局版本(本地掩码)。导致异常的原因是您尝试将本地作为else案例中的第一行,只有在else案例的最后一行分配时才会这样做。

如果您想避免为该名称创建本地覆盖,请添加:

global log_channel

作为函数内的第一行,log_channel的所有引用(加载和存储)将使用全局版本。