×
Namespaces

Variants
Actions

How to make a singleton in Python

From Nokia Developer Wiki
Jump to: navigation, search
Article Metadata
Article
Created: lfd (22 May 2007)
Last edited: hamishwillee (08 May 2013)

There are few more or less complicated ways to make singleton in Python.

One of them is to nest a class into a class and override the attributes getters and setters:

## Singleton class
#
class Foo( object ):
## Stores the unique Singleton instance-
_iInstance = None
 
## Class used with this Python singleton design pattern
# @todo Add all variables, and methods needed for the Singleton class below
class Singleton:
def __init__(self):
## a foo class variable
self.foo = None
 
## The constructor
# @param self The object pointer.
def __init__( self ):
# Check whether we already have an instance
if Foo._iInstance is None:
# Create and remember instanc
Foo._iInstance = Foo.Singleton()
 
# Store instance reference as the only member in the handle
self._EventHandler_instance = Foo._iInstance
 
 
## Delegate access to implementation.
# @param self The object pointer.
# @param attr Attribute wanted.
# @return Attribute
def __getattr__(self, aAttr):
return getattr(self._iInstance, aAttr)
 
 
## Delegate access to implementation.
# @param self The object pointer.
# @param attr Attribute wanted.
# @param value Vaule to be set.
# @return Result of operation.
def __setattr__(self, aAttr, aValue):
return setattr(self._iInstance, aAttr, aValue)
 
 
## Test script to prove that it actually works
if __name__ == "__main__":
 
# create a first object
a = Foo()
 
# get and print class variable foo
print a.foo
 
# create a second object
b = Foo()
 
# set a string to the class variable foo
b.foo = "Hello Folks"
 
# create a third object
c = Foo()
 
# get and print class variable foo for object a
print a.foo
 
# get and print class variable foo for object c
print c.foo

And you get:

None
Hello Folks
Hello Folks


But the method is not perfect because there will be incompatibilities and issues if you try to inherit that class because __getattr__ and __setattr__ are overridden.

This page was last modified on 8 May 2013, at 07:01.
190 page views in the last 30 days.