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 to work fine, and has made the mydict dictionary global. I even print mydict and it works. However, doing this:
global bool
bool = False
Does not seem to work. If trying to print bool in my code, I get:
UnboundLocalError: local variable 'bool' referenced before assignment
So why does it work for the dictionary and not the boolean?
Oh, also, if anyone was wondering how I figured out a better way, I initialised a class and made bool global in the class by doing: self.bool = False which worked. I got it from this question: Making all variables global
EDIT: As requested, I’ll post the necessary code:
import chatbot
global mydict
mydict = {}
global haveamessage
haveamessage = False
class MyBot(chatbot.ChatBot):
def __init__(self, username, password, site):
chatbot.ChatBot.__init__(self,username,password,site)
def on_message(self, c, e):
print mydict
print haveamessage
if __name__ == '__main__':
bot = MyBot("MyUsername", "MyPassword", "MySite")
bot.start()
I’ll try explain this code. Pretty much the chatbot module is to allow users to create bots in wikis on Wikia, a company that allows wikis to be created which anyone can edit. On a wiki there is a chat extension where users can talk to. This script allows a bot to join the chat and do commands. on_message() goes off when someone posts something in the Chat.
So this prints:
{}
Traceback (most recent call last):
File "file.py", line 146, in <module>
bot.start()
File "/Library/Python/2.7/site-packages/chatbot.py", line 371, in start
self.on_message(self.c, e)
File "file.py", line 12, in on_message
print haveamessage
UnboundLocalError: local variable 'haveamessage' referenced before assignment
I’d like to clarify that the reason this isn’t producing an error for all of you is because you are not in a Wikia chat. the function on_message() only runs when someone posts something in the Chat. For example, I may have:
def on_message(self, c, e):
if e.text == 'hello': # e.text is what a user posts in the chat. e = event
c.send('Hello!') # c.send simply sends back a message in the chat. c = connection
So when someone posts in chat hello, the Bot posts back Hello!
The code you’ve posted does not produce the error you claim it does. However using the
globalkeyword 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
haveamessageinsideon_message. If so, you need aglobalstatement inside that method.Basically the rule is: If you try to assign a global variable from within a function, you need to use the
globalkeyword within that function. Otherwise you don’t need theglobalkeyword at all. Whether or not the variable is a boolean makes no difference.