SINGLETON DESIGN PATTERN — PYTHON USE CASE

Bukunmi Adewale
Analytics Vidhya
Published in
2 min readMay 14, 2021

--

Heard about the singleton design pattern but haven’t figured how, when and why to use it? Well, that was me a couple of days ago.

Anyways, the singleton design pattern is a simple pattern that allows you to share a single resource or best put, manage a shared resource. It allows you to instantiate just a single instance of your class and restrict multiple instantiations of the said class.

You would use a singleton when you want to retrieve and store information on external configuration files, manage the connection to a database or external files or drivers etc.

Real-world Example

Imagine that an application on a server has several parts creating its own connection to a database and also performing different operations on the database, chaotic right?

A singleton allows you to create just one instance of the connection to the database and that same object is used to perform other operations on the database in all the parts of the application.

In summary, Singleton ensures that a class has only one instance and provides a global point of access to it.

Implementation of Singleton in Python

The Singleton pattern can be easily implemented in Python because python gives more freedom to the user to modify the constructors of classes.

Below is an example of a simple implementation of a singleton.

We would see that obj1 and obj2 are the same instances and print out the same objects. This is because the __new__() method is a default constructor used to create and return a new instance of the class. In most cases, there isn’t a need to modify this default method because it automatically returns a new instance when a class is called. But in this case where we have to implement the singleton pattern, we will modify it to make sure that only one instance of the class will be created.

Conclusion

Having introduced, discussed and implemented the Singleton Design Pattern, it is important to note that just like any other design pattern, the Singleton pattern has its advantages and disadvantages and we can choose the best design pattern to use depending on our specific scenarios.

Note also that design patterns are just good conventions to follow in programming as it makes the application work better and increases its extendability. Design patterns can be used in different programming languages for different situations.

--

--