[Tutor] singleton pattern

Michael P. Reilly arcege@speakeasy.net
Thu, 17 May 2001 07:40:04 -0400 (EDT)


alan.gauld@bt.com wrote
> Then we could do:
> 
> class SingletonClass(Exception):
>   def __init__(self, obj):
>      self.instance = obj

How about trying not to fake out the mechanisms and just using Python
classes?

class SingletonInstance:
  instance = None  # class member for the singleton instance
  def __init__(self, klass):
    if self.__class__.instance is None:
      self.__class__.instance = klass() # make the instance
  # attribute methods to access the singleton instance
  def __getattr__(self, attr):
    return getattr(self.__class__.instance, attr)
  def __setattr__(self, attr, value):
    return setattr(self.__class__.instance, attr, value)
  def __delattr__(self, attr):
    delattr(self.__class__.instance, attr)

def Factory(klass):
  return SingletonInstance(klass)

Guido once also suggested that replacing __class__ (which is something I
believe Alan was attempting to do) is not a good thing (thought it work).

All this has already been discussed at length in the c.l.p newsgroup a few
years ago.  IMO, Factory classes are not something that new programmers
(reading the tutor list to learn) should be grappling.

  -Arcege

-- 
+----------------------------------+-----------------------------------+
| Michael P. Reilly                | arcege@speakeasy.net              |