Singletons

Jack Diederich jack at performancedrivers.com
Sat Apr 12 08:47:19 CEST 2003


On Fri, Apr 11, 2003 at 11:28:23PM -0400, Roy Smith wrote:
> Hunting around for ideas on implementing the singleton pattern in 
> Python, I found
> 

If you are using python 2.2 or above writing a singleton is much easier

class World(object):
  real_world = None
  def __new__(cls, *args, **opts):
    if (World.real_world is None):
      World.real_world = object.__new__(cls)
      World.first_init(World.real_world, *args, **opts)
    return World.real_world

  def first_init(self, *args, **opts):
    """this will only be called the first time"""
    # do stuff
    return

-jack





More information about the Python-list mailing list