title: Python: thinking of a module and its variables as a singleton — Clean approach?
body: <p>I'd like to implement some sort of singleton pattern in my Python program. I was thinking of doing it without using classes; that is, I'd like to put all the singleton-related functions and variables within a module and consider it an actual singleton.</p>
  
  <p>For example, say this is to be in the file 'singleton_module.py':</p>
  
  
  
  <pre class="lang-py prettyprint-override"><code># singleton_module.py
  
  # Singleton-related variables
  foo = 'blah'
  bar = 'stuff'
  
  # Functions that process the above variables
  def work(some_parameter):
      global foo, bar
      if some_parameter:
          bar = ...
      else:
          foo = ...
  </code></pre>
  
  <p>Then, the rest of the program (i.e., other modules) would use this singleton like so:</p>
  
  
  
  <pre class="lang-py prettyprint-override"><code># another_module.py
  
  import singleton_module
  
  # process the singleton variables,
  # which changes them across the entire program
  singleton_module.work(...)
  
  # freely access the singleton variables
  # (at least for reading)
  print singleton_module.foo
  </code></pre>
  
  <p>This seemed to be a pretty good idea to me, because it <em>looks</em> pretty clean in the modules that use the singleton.</p>
  
  <p>However, all these tedious 'global' statements in the singleton module are ugly. They occur in every function that processes the singleton-related variables. That's not much in this particular example, but when you have 10+ variables to manage across several functions, it's not pretty.</p>
  
  <p>Also, this is pretty error-prone if you happen to forget the global statements: variables local to the function will be created, and the module's variables won't be changed, which is not what you want!</p>
  
  <p>So, would this be considered to be clean? Is there an approach similar to mine that manages to do away with the 'global' mess?</p>
  
  <p>Or is this simply not the way to go?</p>