-1

I'm building a Discord bot but I think this has more to do with Python than it has to do with discord.py

I have this function, built for identifying a server member:

async def targetIdentificator(ctx):
    targetArgument = ctx.message.content.lower().replace(">target", "")

    for member in ctx.message.guild.members:
        if targetArgument.lower() in member.name.lower():
            targetID = member.id
            targetName =  targetArgument
            print("targetID")
    if targetID != "":
        return targetID
    else:
        return None

And about 200 lines above in the code, I define two variables as such:

targetName = ""
targetID = ""

I've used these variables a lot of times throughout the code, in various other functions. In this function, what happens is that when I mention targetID, it references a new local variable instead of referencing the global variable. Therefore if the if statement inside the for cycle never goes through, I get this error:

UnboundLocalError: local variable 'targetID' referenced before assignment

This is probably a really simple mistake, and I apologize if so, but I've been scratching my head for so long on it and can't seem to understand why...

Thanks in advance.

zeval
  • 147
  • 1
  • 10
  • 2
    I believe this answers your question: [Python function global variables?](https://stackoverflow.com/questions/10588317/python-function-global-variables) – mkrieger1 Jul 12 '20 at 15:39

2 Answers2

2

Use the global keyword to explicitly tell Python you're referring to the global variable inside the function, like this:

async def targetIdentificator(ctx):
    global targetID
    global targetName

    targetArgument = ctx.message.content.lower().replace(">target", "")

    for member in ctx.message.guild.members:
        if targetArgument.lower() in member.name.lower():
            targetID = member.id
            targetName =  targetArgument
            print("targetID")
    if targetID != "":
        return targetID
    else:
        return None
jschnurr
  • 1,181
  • 6
  • 8
1

In order to change a global variable inside a local function, you need to tell python that the variable is global with the global statement

In this case, it should look something like:

async def targetIdentificator(ctx):
    global targetID
    global targetName
    ....
Jason K Lai
  • 1,500
  • 5
  • 15