Singleton in Python Cookbook

Alex Popescu nospam.themindstorm at gmail.com
Thu Jul 26 01:23:46 CEST 2007


Alex Popescu <nospam.themindstorm at gmail.com> wrote in 
news:Xns9979172DC38F1themindstorm at 80.91.229.5:

> "Diez B. Roggisch" <deets at nospam.web.de> wrote in
> news:5gq00tF3fm71gU1 at mid.uni-berlin.de: 
> 
>> Alex Popescu schrieb:
>>> Hi all!
>>> 
>>> I was reading through Python Cookbook the Singleton recipe. At this
>>> moment I am a bit puzzled as the example in the book is not working
>>> resulting in: 
>>> 
>>> TypeError: type.__new__(SingleSpam): SingleSpam is not a subtype of
>>> type 
>>> 
>>> (I haven't presented the original code as I am not sure about
>>> copyrights). 
>> 
>> AFAIK the cookbook is completely found online at ASPN. So no sweat 
>> publishing it here.
>> 
>> 
>> And regarding the problem: is it possible that you forgot to subclass 
>> SingleSpam from object?
>> 
>> Diez
> 
> The exact code:
> class Singleton(object):
>     """ A Pythonic Singleton """
>     def _ _new_ _(cls, *args, **kwargs):
>         if '_inst' not in vars(cls):
>             cls._inst = type._ _new_ _(cls, *args, **kwargs)
>         return cls._inst
> 
> if _ _name_ _ == '_ _main_ _':
>     class SingleSpam(Singleton):
>         def _ _init_ _(self, s): self.s = s
>         def _ _str_ _(self): return self.s
>     s1 = SingleSpam('spam')
>     print id(s1), s1.spam( )
>     s2 = SingleSpam('eggs')
>     print id(s2), s2.spam( )
> 
> ./alex
> --
> .w( the_mindstorm )p.
> 
I got it working in 2 ways:

class Singleton(object):
  """ A Pythonic Singleton """
  def __new__(cls, *args, **kwargs):
    if '_singletoninstance' not in vars(cls):
      #variant 1: cls._singletoninstance = object.__new__(cls, *args, 
**kwargs)
      #variant 2: cls._singletoninstance = super(type, cls).__new__(cls, 
*args, **kwargs)
    return cls._singletoninstance

Both of these seem to work.

./alex
--
.w( the_mindstorm )p.




More information about the Python-list mailing list