Singleton suggestions requested

Steve Purcell stephen_purcell at yahoo.com
Tue Apr 17 02:41:34 EDT 2001


Chris Green wrote:
> I'm revisiting python after several years away and implementing a
> medium sized project with it.  One of the first things I'm doing is
> trying to get a few helper util functions working
> 
> After doing some websearches for OO Singleton implementations, I came
> across http://www-md.fsl.noaa.gov/eft/developer/python/hints/ftul.html
> which has Fredrik Lundh's code.
> 
> How would one improve upon this?  I'm still not fully in the python
> mindset and I'd like to brainwash myself somemore before I get deep
> into the project and realize I wanted better basics.


I found an interesting way of dealing with singletons recently. You can
use a handle class that wraps and lazily instantiates your singleton object:

    class LazyHandle:
	def __init__(self, constructor, *args, **kwargs):
	    self.__construct = (constructor, args, kwargs)
	def __call__(self):       
            try:
                return self.__instance
            except AttributeError:
		self.__instance = apply(apply, self.__construct)
                return self.__instance


    import time

    class MySingleton:
	def __init__(self):
	    self.created = time.time()


    mysingleton = LazyHandle(MySingleton)

    # now we can just call mysingleton() to get the singleton
    print mysingleton().created   # lazily creates object

    time.sleep(3)

    print mysingleton().created   # prints the same time again


By placing such singletons in a central place, you can construct a
singleton registry. As a simple example:

    class SingletonRegistry:
        pass

    registry = SingletonRegistry()

    registry.mysingleton = mysingleton

    creation_time = registry.mysingleton().created


-Steve

-- 
Steve Purcell, Pythangelist
Get testing at http://pyunit.sourceforge.net/
Any opinions expressed herein are my own and not necessarily those of Yahoo




More information about the Python-list mailing list