[Tutor] Need info regd Singleton class implementation

Kent Johnson kent37 at tds.net
Thu Jun 15 14:05:30 CEST 2006


Akanksha Govil wrote:
> I need to implement a singleton class in python.
> Please give me some refernce sites which can help me with the same.

Singletons are not used that much in Python, perhaps because the general 
culture of "we're all adults here" is biased against enforcing usage 
patterns.

If you want to have a master reference to an object you can just make it 
a module attribute. Then any client that needs access to the object just 
imports the module.

Why do you need a singleton? Is this homework?

> Also i want to know to call a destructor for a singleton class.

In Python, destructors (__del__() methods) are called on an object when 
it is garbage-collected. The details of when this happens vary between 
different Python implementations. In CPython (the standard Python from 
python.org), an object is garbage-collected when its reference count 
goes to 0 - when there are no names that refer to the object. So if you 
want the __del__() method of an object to be called, you have to ensure 
that there are no references to the object. In the case of a singleton, 
this would mean deleting or assigning None to the name that holds the 
master reference, and ensuring that no users of the singleton retain 
references to it.

Kent



More information about the Tutor mailing list