singleton decorator

Chaz Ginger cginboston at hotmail.com
Tue Aug 8 02:58:05 EDT 2006


bearophileHUGS at lycos.com wrote:
> Andre Meyer:
>> What is the preferred pythonic way of implementing singleton elegantly?
> 
> Maybe to just use a module.
> 
> Bye,
> bearophile
> 
Here is some sample code for both singleton classes and named classes 
that I use:

> class Singleton(type):
>     """
>     This class will allow only one instance of a type
>     regardless of the initialization arguments.
>     """
>     def __init__(self, *args, **kwargs):
>         """
>         This is done when the class is defined.
>         """
>         type.__init__(self, *args, **kwargs)
>         self._instance = None
> 
>     def __call__(self, *args, **kwargs):
>         """
>         This is called when the class is instantiated.
>         """
>         if not self._instance : self._instance = type.__call__(self,*args,**kwargs)
>         return self._instance
> 
> class namedSingleton(type):
>     """
>     This class will allow a different singleton per initialization
>     argument list.  This implementation does not take into account
>     variations in the keyword args.
>     """
>     def __init__(self, *args, **kwargs):
>         """
>         This is executed when the class is first defined.
>         """
>         type.__init__(self, *args, **kwargs)
>         self._instances = {}
> 
>     def __call__(self, *args, **kwargs):
>         """
>         This is called when the class is instantiated.
>         """
>         if not args in self._instances:
>             self._instances[args] = type.__call__(self, *args,**kwargs )
>         return self._instances[args]



More information about the Python-list mailing list