I have a problem with my understanding of python global variables and their correct usage. The first bit of code works fine, the second bit throws the exceptions "NameError: global name 'chosen' is not defined". I am sure I am missing something simple here, but I can not see what it is.
I want to associate a Listener with each of many event generators and then use the getChoices method to get a dictionary of the choice made be each generator.
#Working code
class Listener1():
chosen = "0"
def __init__(self, choice):
self.choice = choice
def actionPerformed(self, event):
global chosen
chosen = self.choice
@staticmethod
def getChoices():
return chosen
e1 = Listener1('evt1')
e1.actionPerformed('abc')
print Listener1.getChoices()
Failing code
class Listener2():
chosen2 = {'a':-1}
def __init__(self, choice):
self.choice = choice
global chosen2
chosen2[self.choice] = 'unset'
def actionPerformed(self, event):
val = event
global chosen2
chosen2[self.choice] = val
@staticmethod
def getChoices():
return chosen2
e2 = Listener2('evt2')
e2.actionPerformed('def')
e3 = Listener2('evt3')
e3.actionPerformed('ghi')
print Listener2.getChoices()
Footnote: the Listener2 class works correctly if I move the first reference to the global variable chosen2 to the line before the class definition instead of the line after.
Thanks to the answers below, code rewritten as:
class Listener3():
chosen3 = {}
def __init__(self, choice):
self.choice = choice
if choice is not None:
self.chosen3[self.choice] = 'unset'
def actionPerformed(self, event):
val = event
self.chosen3[self.choice] = val
def getChoices(self):
return self.chosen3
e1 = Listener3('evt1')
e1.actionPerformed('abc')
e2 = Listener3('evt2')
e2.actionPerformed('def')
e3 = Listener3('evt3')
print Listener3(None).getChoices()
{'evt1': 'abc', 'evt2': 'def', 'evt3':'unset'}
And apart from being much simpler, is now working perfectly.