title: Python Jython global variable usage
body: <p>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.  </p>
  
  <p>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. </p>
  
  <pre><code>#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()
  </code></pre>
  
  <p>Failing code  </p>
  
  <pre><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()
  </code></pre>
  
  <p>Footnote:
  the Listener2 class works correctly if I move the first reference to the global variable <strong>chosen2</strong> to the line before the class definition instead of the line after. </p>
  
  <p>Thanks to the answers below, code rewritten as:</p>
  
  <pre><code>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'}
  </code></pre>
  
  <p>And apart from being much simpler, is now working perfectly.</p>