Python: Singleton (1)

June 21, 2017


Python singleton is very useful data structure in many cases. This type of data structures allow us to reuse / share the same instance across multiple modules. There is a detailed explanation on this here, where many approaches are introduced. However, the basic idea is the same: since Python class is uniquely named and declared, developers can use the class directly instead of an object as a singleton.


Let's have a look at my favorite example:

Using the above way for singleton, we can try the following code:

The result will be:

This result is easy to understand. Notice the function __new__() will only create the new instance once, and keep reusing the same class instance. Therefore the object a and b share the same singleton and return always the same result.


What if we want a class inheriting from another class to add even more attributes? What if we also want __init__() function to be a non-trivial one? Let's look at the following example:

This is an interesting example. All the Boy class objects are actually sharing the same instance. In the real world, we can assume there is always this one boy, and he keeps changing his name, his age, and his hair color (not gender). We can try the following code:

What are we expecting? Let's see:

Interesting, right? It is obvious that there is only 1 boy inheriting from his parent. Every time we instantiate it, we are just about to get the same instance with some changes on the attribute values. We can instantiate Boy() for 100 times, but all of those instances will just share the same attribute values. It is even more interesting to see the new attribute haircolor is also shared among all the instances.


As I said, there are many ways to realize a similar behavior. Maybe I will introduce the use of MetaClass in the future.