Why Does Globalising A Boolean Not Work But Globalising A Dictionary Does
This is just a question wondering why this doesn't work. I have figured out a better way, but I don't know why previously it wasn't working. global mydict mydict = {} This seems t
Solution 1:
The code you've posted does not produce the error you claim it does. However using the global
keyword outside of a function has no effect, so it's not surprising that it doesn't work like you expect.
I assume that in your real code, you're actually trying to assign to haveamessage
inside on_message
. If so, you need a global
statement inside that method.
Basically the rule is: If you try to assign a global variable from within a function, you need to use the global
keyword within that function. Otherwise you don't need the global
keyword at all. Whether or not the variable is a boolean makes no difference.
Solution 2:
I believe what you want to do is define the global variables, but then in your function reference them so you can use them locally:
import chatbot
mydict = {}
haveamessage = FalseclassMyBot(chatbot.ChatBot):
def__init__(self, username, password, site):
chatbot.ChatBot.__init__(self,username,password,site)
defon_message(self, c, e):
global mydict
global haveamessage
print mydict
print haveamessage
Post a Comment for "Why Does Globalising A Boolean Not Work But Globalising A Dictionary Does"