[CentralOH] Singleton

Eric Floehr eric at intellovations.com
Thu Sep 30 15:38:35 CEST 2010


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/


<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/
).

-Eric




On Thu, Sep 30, 2010 at 9:27 AM, Mark Erbaugh <mark at microenh.com> wrote:

> Would the following code be appropriate to implement a singleton instance?
>
>
> class Singleton(object):
>        """ class that will have only one instance in the application """
>
> singleton = Singleton()
> del Singleton
>
>
> The single instance of the class would be instantiated the first time the
> module is imported. It would be impossible for any other code to instantiate
> another instance.
>
> I had originally thought of a slightly shorter, but less Pythonic version
>
> class singleton(object)
>        """ note the non-standard lowercase class name """
>
> singleton = singleton()
>
>
>
> Comments are welcome.
>
> Mark
> _______________________________________________
> CentralOH mailing list
> CentralOH at python.org
> http://mail.python.org/mailman/listinfo/centraloh
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/mailman/private/centraloh/attachments/20100930/dc442706/attachment.html>


More information about the CentralOH mailing list