10

I'm making a Discord bot in Python using discord.py. I'd like to set/modify a global variable from an async thread.

message = ""

@bot.command()
async def test(ctx, msg):
    message = msg

However this doesn't work. How can I achieve something that does this?

Máté Varga
  • 171
  • 1
  • 3
  • 12
  • What exactly do you mean by it doesn't work ? In another function the value is not reflected that you are setting in test ? The global variables should be available in async functions and the value would change. Most likely its getting overwritten somewhere else. – PraveenB Mar 17 '20 at 19:07
  • Does this answer your question? [Using global variables in a function](https://stackoverflow.com/questions/423379/using-global-variables-in-a-function) – Ture Pålsson Mar 17 '20 at 19:07
  • @TurePålsson thanks for pointing it out and obviously you have to use the keyword global in all the functions wherever you are changing it . – PraveenB Mar 17 '20 at 19:17

1 Answers1

20

As I said in the comment you have to use the keyword global in the functions wherever you are modifying the global variable. If you are just reading it in function than you don't need it.

message = ""

@bot.command()
async def test(ctx, msg):
    global message
    message = msg
PraveenB
  • 1,270
  • 10
  • 11
  • 2
    While valid, this is not actually the correct answer to the OPs question. The OP wants to modify an outer scoped variables from an inner scoped function. While global can be used, it's not necessarily the right answer: what if the variable should not be global but only be mutable within the required scopes? The answer is to use a mutable type - dict, array, etc. rather than str. Python's rules for scope shadowing are non-intuitive to folks coming from other languages. – verveguy May 18 '23 at 12:20
  • 1
    I agree that there are different ways to modify an outer scoped variable but the OP's question states directly that he wants to modify the global variable. My answer is based on the code snippet provided. – PraveenB Jun 02 '23 at 03:41