Python: thinking of a module and its variables as a singleton — Clean approach?
Question: 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.

For example, say this is to be in the file 'singleton_module.py':

    
    
    # 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 = ...
    

Then, the rest of the program (i.e., other modules) would use this singleton
like so:

    
    
    # 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
    

This seemed to be a pretty good idea to me, because it _looks_ pretty clean in
the modules that use the singleton.

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.

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!

So, would this be considered to be clean? Is there an approach similar to mine
that manages to do away with the 'global' mess?

Or is this simply not the way to go?


Answer: A common alternative to using a module as a singleton is Alex Martelli's [Borg
pattern](http://code.activestate.com/recipes/66531-singleton-we-dont-need-no-
stinkin-singleton-the-bo/):

    
    
    class Borg:
        __shared_state = {}
        def __init__(self):
            self.__dict__ = self.__shared_state
        # and whatever else you want in your class -- that's all!
    

There can be multiple instances of this class, but they all share the same
state.

