[CentralOH] Singleton

Mark Erbaugh mark at microenh.com
Thu Sep 30 21:50:18 CEST 2010

On Sep 30, 2010, at 9:38 AM, Eric Floehr wrote:

> It's really not the *class* you want one instance of, but the *state*.  In C++ and Java, where the Singleton gained prominence, you can't separate the two.  But in Python you can.
> The "Borg" pattern is generally accepted as the Pythonic approach to the singleton:
> 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!
> Of course, there are a number of folks (including Tarek Ziade, in Expert Python Programming) who don't believe a singleton-like pattern is necessary at all (http://tarekziade.wordpress.com/2009/01/22/singletons-and-borg-are-unpythonic-well-imvho/).


Thanks for the reply and the links. IYou are correct, I'm mostly concerned with state. In fact, the code that led to this was originally a simple global function. As the usage developed, I needed the function to save some simple state information between calls. Originally, I just added a global variable to the module and accessed that within the function using the global keyword. That worked, but classes seemed like a more elegant way of encapsulating things.

The discussion on the recipes page is interesting. One of the points that makes sense to me is that with the Borg pattern you end up with multiple objects while with a Singleton there is only one. The latter seems more efficient.

Another interesting comment in the initial discussion of the recipe is that the code quote above only works with classic Python classes. I though classic classes are on their way out and should be avoided in new code.  In the discussion of the recipe, someone does propose a version of Borg that works with new style classes.

Thanks for finding the edge cases in deleting the class variable.  As someone pointed out in one of the threads, even if you do that, the class can still be gotten by taking the class (or type) of the singleton instance.


-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/mailman/private/centraloh/attachments/20100930/89324cc0/attachment.html>

More information about the CentralOH mailing list