【问题标题】:reassigning variables with async/await?使用异步/等待重新分配变量?
【发布时间】:2017-02-07 11:14:09
【问题描述】:

我正在尝试使用 discord.py 创建一个简单的 discord 机器人来获得乐趣。 我正在努力完全理解 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 变量会导致“分配前引用”异常。如果我不尝试覆盖,那么它可以很好地获取变量的值。

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

【问题讨论】:

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


    【解决方案1】:

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

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

    global log_channel
    

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

    【讨论】:

      猜你喜欢
      • 2019-10-29
      • 1970-01-01
      • 1970-01-01
      • 2023-03-04
      • 1970-01-01
      • 1970-01-01
      • 2011-10-10
      • 1970-01-01
      • 2020-07-16
      相关资源
      最近更新 更多